You are on page 1of 1612

WWW.TESTBENCH.

IN

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

SystemVerilog Verilog OpenVera Miscellanious


Basic Constructs Verification Concepts Verification Concepts Constructs Articles
Interface UVM Tutorial Switch Example Switch Example Specman E Tutorial
OOPS VMM Tutorial Basic Constructs RVM Switch Example Interview Questions
Randomization OVM Tutorial ... RVM Ethernet Sample ...
Functional Coverage Easy Labs : SV ... ... ...
Assertion Easy Labs : UVM ... ... ...
DPI Easy Labs : OVM ... ... ...
VMM Ethernet Example Easy Labs : VMM ... ... ...
... Easy Labs : AVM ... ... ...

New to this site ? Then check these links


>What People are saying about this Site
>What is on this Site
>Table of Contents

copyright © 2007 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/[9/26/2012 1:55:44 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INDEX Index


Introduction
SystemVerilog Data Types
Verification ............INTRODUCTION Literals
Strings
Constructs ............DATA TYPES Userdefined Datatypes
Interface ..................... Signed And Unsigned Enumarations
..................... Void Structures And Uniouns
OOPS Typedef
Randomization ............LITERALS Arrays
..................... Integer And Logic Literals Array Methods
Functional Coverage Dynamic Arrays
..................... Time Literals
Assertion ..................... Array Literals Associative Arrays
..................... Structure Literals Queues
DPI Comparison Of Arrays
UVM Tutorial ............STRINGS Linked List
..................... String Methods Casting
VMM Tutorial Data Declaration
..................... String Pattren Match
OVM Tutorial ..................... String Operators Reg And Logic
..................... Equality Operators 1
Easy Labs : SV
..................... Inequality. Operators 2
Easy Labs : UVM ..................... Comparison. Operator Precedency
..................... Concatenation. Events
Easy Labs : OVM
..................... Replication. Control Statements
Easy Labs : VMM ..................... Indexing. Program Block
AVM Switch TB Procedural Blocks
............USERDEFINED DATATYPES Fork Join
VMM Ethernet sample Fork Control
............ENUMARATIONS Subroutines
..................... Enumarated Methods Semaphore
Verilog ..................... Enum Numerical Expressions Mailbox
Fine Grain Process
Verification
............STRUCTURES AND UNIOUNS Control
Verilog Switch TB ..................... Structure
Basic Constructs ..................... Assignments To Struct Members Report a Bug or Comment
..................... Union on This section - Your
..................... Packed Structures input is what keeps
Testbench.in improving
OpenVera ............TYPEDEF with time!
Constructs ..................... Advantages Of Using Typedef
Switch TB
............ARRAYS
RVM Switch TB ..................... Fixed Arrays
RVM Ethernet sample ..................... Operations On Arrays
..................... Accessing Individual Elements Of Multidimensional Arrays

............ARRAY METHODS
Specman E ..................... Array Methods
Interview Questions ..................... Array Querying Functions
..................... Array Locator Methods
..................... Array Ordering Methods
..................... Array Reduction Methods
..................... Iterator Index Querying

............DYNAMIC ARRAYS
..................... Declaration Of Dynmic Array
..................... Allocating Elements
..................... Initializing Dynamic Arrays
..................... Resizing Dynamic Arrays

http://testbench.in/SV_00_INDEX.html[9/26/2012 1:55:53 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

..................... Copying Elements

............ASSOCIATIVE ARRAYS
..................... Associative Array Methods

............QUEUES
..................... Queue Operators
..................... Queue Methods
..................... Dynamic Array Of Queues Queues Of Queues

............COMPARISON OF ARRAYS
..................... Static Array
..................... Associative Array
..................... Dynamic Array
..................... Queues

............LINKED LIST
..................... List Definitions
..................... Procedure To Create And Use List
..................... List_iterator Methods
..................... List Methods

............CASTING
..................... Static Casting
..................... Dynamic Casting
..................... Cast Errors

............DATA DECLARATION
..................... Scope And Lifetime
..................... Global
..................... Local
..................... Alias
..................... Data Types On Ports
..................... Parameterized Data Types
..................... Declaration And Initialization

............REG AND LOGIC

............OPERATORS 1
..................... Operators In Systemverilog
..................... Assignment Operators
..................... Assignments In Expression
..................... Concatenation
..................... Arithmetic
..................... Relational
..................... Equality

............OPERATORS 2
..................... Logical
..................... Bitwise
..................... Reduction
..................... Shift
..................... Increment And Decrement
..................... Set
..................... Streaming Operator
..................... Re-Ordering Of The Generic Stream
..................... Packing Using Streaming Operator
..................... Unpacking Using Streaming Operator

http://testbench.in/SV_00_INDEX.html[9/26/2012 1:55:53 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

..................... Streaming Dynamically Sized Data

............OPERATOR PRECEDENCY

............EVENTS
..................... Triggered
..................... Wait()
..................... Race Condition
..................... Nonblocking Event Trigger
..................... Merging Events
..................... Null Events
..................... Wait Sequence
..................... Events Comparison

............CONTROL STATEMENTS
..................... Sequential Control
..................... Enhanced For Loop
..................... Unique
..................... Priority

............PROGRAM BLOCK

............PROCEDURAL BLOCKS
..................... Final
..................... Jump Statements
..................... Event Control
..................... Always

............FORK JOIN
..................... Fork Join None
..................... Fork Join Any
..................... For Join All

............FORK CONTROL
..................... Wait Fork Statement
..................... Disable Fork Statement

............SUBROUTINES
..................... Begin End
..................... Tasks
..................... Return In Tasks
..................... Functions
..................... Return Values And Void Functions:
..................... Pass By Reference
..................... Default Values To Arguments
..................... Argument Binding By Name
..................... Optional Argument List

............SEMAPHORE

............MAILBOX

............FINE GRAIN PROCESS CONTROL

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SV_00_INDEX.html[9/26/2012 1:55:53 PM]


WWW.TESTBENCH.IN - Systemverilog Interface

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INDEX Index


Interface
SystemVerilog Ports
Verification ............INTERFACE Interface Methods
..................... Advantages Of Using Inteface Clocking Block
Constructs Virtual Interface
Interface ............PORTS Svtb N Verilog Dut
..................... Interface Ports
OOPS ..................... Modports Report a Bug or Comment
Randomization ..................... Modport Selection Duing Module Definition. on This section - Your
..................... Modport Selection Duing Module Instance. input is what keeps
Functional Coverage Testbench.in improving
Assertion ............INTERFACE METHODS with time!
DPI
..................... Methods In Interfaces

UVM Tutorial ............CLOCKING BLOCK


VMM Tutorial ..................... Clocking Blocks
..................... Skew
OVM Tutorial ..................... Cycle Delay
Easy Labs : SV
............VIRTUAL INTERFACE
Easy Labs : UVM ..................... Virtual Interfaces
Easy Labs : OVM ..................... Advantages Of Virtual Interface
..................... Multi Bus Interface
Easy Labs : VMM
AVM Switch TB ............SVTB N VERILOG DUT
..................... Working With Verilog Dut
VMM Ethernet sample ..................... Connecting In Top
..................... Connecting Using A Wrapper

Verilog
Verification
Verilog Switch TB
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/IF_00_INDEX.html[9/26/2012 1:56:01 PM]


WWW.TESTBENCH.IN - Systemverilog Interface

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/IF_00_INDEX.html[9/26/2012 1:56:01 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INDEX Index


Introduction
SystemVerilog Class
Verification ............INTRODUCTION Object
..................... Brief Introduction To Oop This
Constructs ..................... Class Inheritance
Interface ..................... Object Encapsulation
..................... Methods Polymorphism
OOPS ..................... Inheritance Abstract Classes
Randomization ..................... Abstraction Parameterised Class
..................... Encapsulation Nested Classes
Functional Coverage Constant
..................... Polymorphism
Assertion Static
............CLASS Casting
DPI Copy
..................... Class Properties
UVM Tutorial Scope Resolution
............OBJECT Operator
VMM Tutorial Null
..................... Creating Objects
OVM Tutorial ..................... Declaration External Declaration
..................... Instantiating A Class Classes And Structures
Easy Labs : SV
..................... Initializing An Object Typedef Class
Easy Labs : UVM ..................... Constructor Pure
Other Oops Features
Easy Labs : OVM
............THIS Misc
Easy Labs : VMM ..................... Using The This Keyword
AVM Switch TB Report a Bug or Comment
............INHERITANCE on This section - Your
VMM Ethernet sample ..................... What You Can Do In A Subclass input is what keeps
..................... Overriding Testbench.in improving
..................... Super with time!
Verilog ..................... Is Only Method
Verification ..................... Is First Method
..................... Is Also Method
Verilog Switch TB ..................... Overriding Constraints.
Basic Constructs ..................... Overriding Datamembers

............ENCAPSULATION
..................... Access Specifiers
OpenVera
Constructs ............POLYMORPHISM
Switch TB
............ABSTRACT CLASSES
RVM Switch TB
RVM Ethernet sample ............PARAMETERISED CLASS
..................... Type Parameterised Class
..................... Value Parameterised Class
..................... Generic Parameterised Class
Specman E ..................... Extending Parameterised Class
Interview Questions
............NESTED CLASSES
..................... Why Use Nested Classes

............CONSTANT
..................... Constant Class
..................... Global Constant
..................... Instance Constants

............STATIC
..................... Static Class Properties

http://testbench.in/CL_00_INDEX.html[9/26/2012 1:56:09 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

..................... Static Methods


..................... Static Lifetime Method.

............CASTING

............COPY
..................... Shallow Copy
..................... Deep Copy
..................... Clone

............SCOPE RESOLUTION OPERATOR

............NULL

............EXTERNAL DECLARATION

............CLASSES AND STRUCTURES

............TYPEDEF CLASS
..................... Forward Reference
..................... Circular Dependency

............PURE

............OTHER OOPS FEATURES


..................... Multiple Inheritence
..................... Method Overloading

............MISC
..................... Always Block In Classes

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CL_00_INDEX.html[9/26/2012 1:56:09 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INDEX Index


Constrained Random
SystemVerilog Verification
Verification ............CONSTRAINED RANDOM VERIFICATION Verilog Crv
..................... Introduction Systemverilog Crv
Constructs Randomizing Objects
Interface ............VERILOG CRV Random Variables
..................... Constrained Random Stimulus Generation In Verilog Randomization Methods
OOPS Checker
Randomization ............SYSTEMVERILOG CRV Constraint Block
..................... Systemverilog Constraint Random Stmulus Generaion Inline Constraint
Functional Coverage Global Constraint
..................... Random Number Generator System Functions
Assertion ..................... $Urandom_range Constraint Mode
..................... Scope Randomize Function External Constraints
DPI Randomization
..................... Randomizing Objects
UVM Tutorial ..................... Random Unpacked Structs Controlability
..................... Rand Case Static Constraint
VMM Tutorial Constraint Expression
..................... Rand Sequence
OVM Tutorial Variable Ordering
............RANDOMIZING OBJECTS Constraint Solver Speed
Easy Labs : SV
..................... Generating Random Stimulus Within Class Randcase
Easy Labs : UVM Randsequence
............RANDOM VARIABLES Random Stability
Easy Labs : OVM
..................... Random Varible Declaration Array Randomization
Easy Labs : VMM ..................... Rand Modifier Constraint Guards
AVM Switch TB ..................... Randc Modifier Titbits

VMM Ethernet sample ............RANDOMIZATION METHODS Report a Bug or Comment


..................... Randomization Built-In Methods on This section - Your
..................... Randomize() input is what keeps
Verilog ..................... Pre_randomize And Post_randomize Testbench.in improving
..................... Disabling Random Variable with time!
Verification
..................... Random Static Variable
Verilog Switch TB ..................... Randomizing Nonrand Varible
Basic Constructs
............CHECKER

............CONSTRAINT BLOCK
OpenVera ..................... Inheritance
Constructs ..................... Overrighting Constraints
Switch TB
............INLINE CONSTRAINT
RVM Switch TB
RVM Ethernet sample ............GLOBAL CONSTRAINT
............CONSTRAINT MODE
..................... Disabling Constraint Block
Specman E
Interview Questions ............EXTERNAL CONSTRAINTS
..................... Constraint Hiding

............RANDOMIZATION CONTROLABILITY
..................... Controlability

............STATIC CONSTRAINT

............CONSTRAINT EXPRESSION
..................... Set Membership
..................... Weighted Distribution

http://testbench.in/CR_00_INDEX.html[9/26/2012 1:56:18 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

..................... Implication
..................... If..Else

............VARIABLE ORDERING
..................... Functions
..................... Iterative Constraints

............CONSTRAINT SOLVER SPEED

............RANDCASE

............RANDSEQUENCE
..................... Random Productions
..................... Random Production Weights
..................... If..Else
..................... Case
..................... Repeat Production Statements
..................... Rand Join
..................... Break
..................... Return
..................... Value Passing Between Productions

............RANDOM STABILITY
..................... Srandom

............ARRAY RANDOMIZATION

............CONSTRAINT GUARDS

............TITBITS
..................... Constraining Non Integral Data Types
..................... Saving Memory

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CR_00_INDEX.html[9/26/2012 1:56:18 PM]


WWW.TESTBENCH.IN - SystemVerilog Functional Coverage

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INDEX Index


Introduction
SystemVerilog Cover Group
Verification ............INTRODUCTION Sample
..................... Systemverilog Functional Coverage Features Cover Points
Constructs Coverpoint Expression
Interface ............COVER GROUP Generic Coverage Groups
Coverage Bins
OOPS ............SAMPLE Explicit Bin Creation
Randomization Transition Bins
............COVER POINTS Wildcard Bins
Functional Coverage Ignore Bins
..................... Commands To Simulate And Get The Coverage Report
Assertion Illegal Bins
............COVERPOINT EXPRESSION Cross Coverage
DPI Coverage Options
..................... Coverpoint Expression
UVM Tutorial ..................... Coverage Filter Coverage Methods
System Tasks
VMM Tutorial Cover Property
............GENERIC COVERAGE GROUPS
OVM Tutorial
............COVERAGE BINS Report a Bug or Comment
Easy Labs : SV
..................... Implicit Bins on This section - Your
Easy Labs : UVM input is what keeps
Easy Labs : OVM ............EXPLICIT BIN CREATION Testbench.in improving
..................... Array Of Bins with time!
Easy Labs : VMM ..................... Default Bin
AVM Switch TB
............TRANSITION BINS
VMM Ethernet sample ..................... Single Value Transition
..................... Sequence Of Transitions
..................... Set Of Transitions
Verilog ..................... Consecutive Repetitions
Verification ..................... Range Of Repetition
..................... Goto Repetition
Verilog Switch TB ..................... Non Consecutive Repetition
Basic Constructs
............WILDCARD BINS

............IGNORE BINS
OpenVera
Constructs ............ILLEGAL BINS
Switch TB
............CROSS COVERAGE
RVM Switch TB ..................... User-Defined Cross Bins
RVM Ethernet sample
............COVERAGE OPTIONS
..................... Weight
..................... Goal
Specman E ..................... Name
Interview Questions ..................... Comment
..................... At_least
..................... Detect_overlap
..................... Auto_bin_max
..................... Cross_num_print_missing
..................... Per_instance
..................... Get_inst_coverage

............COVERAGE METHODS

............SYSTEM TASKS

http://testbench.in/CO_00_INDEX.html[9/26/2012 1:56:27 PM]


WWW.TESTBENCH.IN - SystemVerilog Functional Coverage

............COVER PROPERTY
..................... Cover Property Results
..................... Cover Sequence Results
..................... Comparison Of Cover Property And Cover Group.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CO_00_INDEX.html[9/26/2012 1:56:27 PM]


WWW.TESTBENCH.IN - System Verilog Assertion - SVA

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INDEX Index


Introduction
SystemVerilog Event Simulation
Verification ............INTRODUCTION Assertion Types
..................... Advantages Of Assertion Assertion System Tasks
Constructs ..................... What Assertions Can Verify Concurrent Assertion
Interface Layers
............EVENT SIMULATION Sequences
OOPS Properties
Randomization ............ASSERTION TYPES Verification Directive
Functional Coverage Report a Bug or Comment
............ASSERTION SYSTEM TASKS
Assertion ..................... Assertion Control System Tasks on This section - Your
..................... Boolean System Function input is what keeps
DPI Testbench.in improving
UVM Tutorial ............CONCURRENT ASSERTION LAYERS with time!
VMM Tutorial ..................... Boolean Expressions
OVM Tutorial ............SEQUENCES
Easy Labs : SV ..................... Fixed Delay
..................... Zero Delay
Easy Labs : UVM ..................... Constant Range Delay
Easy Labs : OVM ..................... Unbounded Delay Range
..................... Repetation Operators
Easy Labs : VMM ..................... Consecutive Repetition
AVM Switch TB ..................... Goto Repetition
..................... Nonconsecutive Repetition
VMM Ethernet sample ..................... Sequence And
..................... Sequence Or
..................... Sequence Intersect
Verilog ..................... Sequence Within
Verification ..................... Sequence First_match
..................... Sequence Throughout
Verilog Switch TB ..................... Sequence Ended
Basic Constructs ..................... Operator Precedence Associativy

............PROPERTIES
..................... Overlap Implication
OpenVera ..................... Non Overlapping Implication
Constructs
Switch TB ............VERIFICATION DIRECTIVE
..................... Assert
RVM Switch TB ..................... Assume
RVM Ethernet sample ..................... Cover Statement
..................... Expect Statement
..................... Binding
Specman E
Interview Questions

http://testbench.in/AS_00_INDEX.html[9/26/2012 1:56:34 PM]


WWW.TESTBENCH.IN - System Verilog Assertion - SVA

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/AS_00_INDEX.html[9/26/2012 1:56:34 PM]


WWW.TESTBENCH.IN - Systemverilog DPI

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INDEX Index


Introductions
SystemVerilog Layers
Verification ............INTRODUCTIONS Import
..................... What Is Dpi-C ? Naming
Constructs Export
Interface ............LAYERS Pure And Context
..................... Two Layers Of Dpi-C Data Types
OOPS ..................... Dpi-C Systemverilog Layer Arrays
Randomization ..................... Dpi-C Foreign Language Layer Passing Structs And
Unions
Functional Coverage Arguments Type
............IMPORT
Assertion ..................... Import Methods Disablie
DPI
..................... Steps To Write Import Metyhods
..................... Standard C Functions Report a Bug or Comment
UVM Tutorial on This section - Your
............NAMING input is what keeps
VMM Tutorial
..................... Global Name Testbench.in improving
OVM Tutorial ..................... Local Name with time!
Easy Labs : SV ..................... Sv Keyword As Linkage Name
Easy Labs : UVM ............EXPORT
Easy Labs : OVM ..................... Export Methods
..................... Steps To Write Export Methods
Easy Labs : VMM ..................... Blocking Export Dpi Task
AVM Switch TB
............PURE AND CONTEXT
VMM Ethernet sample ..................... Pure Function
..................... Context Function

Verilog ............DATA TYPES


Verification ..................... Passing Logic Datatype
Verilog Switch TB ............ARRAYS
Basic Constructs ..................... Open Arrays
..................... Packed Arrays
..................... Linearized And Normalized
..................... Array Querying Functions
OpenVera
Constructs ............PASSING STRUCTS AND UNIONS
Switch TB ..................... Passing Structure Example
..................... Passing Openarray Structs
RVM Switch TB ..................... Passing Union Example
RVM Ethernet sample
............ARGUMENTS TYPE
..................... What You Specify Is What You Get
..................... Pass By Ref
Specman E ..................... Pass By Value
Interview Questions ..................... Passing String
..................... Example Passing String From Sv To C
..................... Example Passing String From C To Sv

............DISABLIE
..................... Disable Dpi-C Tasks And Functions
..................... Include Files

http://testbench.in/DP_00_INDEX.html[9/26/2012 1:56:42 PM]


WWW.TESTBENCH.IN - Systemverilog DPI

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/DP_00_INDEX.html[9/26/2012 1:56:42 PM]


WWW.TESTBENCH.IN

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS VMM Ethernet


SystemVerilog
Verification This testbench is developed in VMM (Systemverilog) for the Ethernet core available from opencores.org. My
intension here is to explore the VMM methodology but not to verify the Ethernet core, as a result there are many
Constructs bugs in the environment. I dont remember the versions of VMM but I developed these in the third quarter of 2007.
Interface To simulate this testbench some dependencies on libraries has to be removed from RTL files. It takes bit time for
these changes in RTL.
OOPS
Randomization
Feauters:
Functional Coverage
Assertion Full support of automatic random, constrained random, and directed testcase creation.
DPI Supports injuction of random errored packets.
Supports 1G Fullduplex modeled both in RX and TX paths.
UVM Tutorial Protocol Checker/Monitor for self checking.
VMM Tutorial Built in function coverage support for packets.
Developed in Systemverilog using Synopsys VMM base classes.
OVM Tutorial
Easy Labs : SV NOTE: All trademarks are the property of their respective owners.
Easy Labs : UVM
Easy Labs : OVM Download vmm.tar
Browse the code in vmm_eth.tar
Easy Labs : VMM
AVM Switch TB
BLOCK DIAGRAM OF ETHERNET VERIFICATION ENVIRONMENT
VMM Ethernet sample

Verilog
Verification
Verilog Switch TB
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/ethernet_vmm.html[9/26/2012 1:56:49 PM]


WWW.TESTBENCH.IN

copyright © 2007 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/ethernet_vmm.html[9/26/2012 1:56:49 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INDEX Index


Asic Design
SystemVerilog Bottle Neck In Asic Flow
Verification ............ASIC DESIGN Functional Verification
..................... Mrd Need
Constructs ..................... Architecture Specification Testbench
Interface ..................... Design Specification Linear Testbench
..................... Verification Plan Linear Random
OOPS ..................... Rtl Design Testbench
Randomization ..................... Functional Verification How To Check The
..................... Synthesis Results
Functional Coverage Self Checking Testbenchs
..................... Physical Design
Assertion ..................... Timing Analysis How To Get Scenarios
..................... Tapeout Which We Never Thought
DPI How To Check Whether
UVM Tutorial ............BOTTLE NECK IN ASIC FLOW The Testbench Has
Satisfactorily Exercised
VMM Tutorial The Design
............FUNCTIONAL VERIFICATION NEED
OVM Tutorial Types Of Code Coverage
............TESTBENCH Statement Coverage
Easy Labs : SV
Block Coverage
Easy Labs : UVM ............LINEAR TESTBENCH Conditional Coverage
Branch Coverage
Easy Labs : OVM
............LINEAR RANDOM TESTBENCH Path Coverage
Easy Labs : VMM Toggle Coverage
AVM Switch TB ............HOW TO CHECK THE RESULTS Fsm Coverage
Make Your Goal 100
VMM Ethernet sample ............SELF CHECKING TESTBENCHS Percent Code Coverage
Nothing Less
............HOW TO GET SCENARIOS WHICH WE NEVER THOUGHT Functional Coverage
Verilog Coverage Driven
............HOW TO CHECK WHETHER THE TESTBENCH HAS SATISFACTORILY EXERCISED Constraint Random
Verification
THE DESIGN Verification Architecture
Verilog Switch TB Phases Of Verification
............TYPES OF CODE COVERAGE Ones Counter Example
Basic Constructs
Verification Plan
............STATEMENT COVERAGE
Report a Bug or Comment
OpenVera ............BLOCK COVERAGE on This section - Your
Constructs input is what keeps
............CONDITIONAL COVERAGE Testbench.in improving
Switch TB
with time!
RVM Switch TB ............BRANCH COVERAGE
RVM Ethernet sample
............PATH COVERAGE

............TOGGLE COVERAGE
Specman E
Interview Questions ............FSM COVERAGE
..................... State Coverage
..................... Transition Coverage

............MAKE YOUR GOAL 100 PERCENT CODE COVERAGE NOTHING LESS


..................... Dont Be Fooled By The Code Coverage Report
..................... When To Stop Testing?

............FUNCTIONAL COVERAGE
..................... Introduction To Functional Coverage
..................... Item

http://testbench.in/TS_00_INDEX.html[9/26/2012 1:56:57 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

..................... Cross
..................... Transitional
..................... Assertion Coverage

............COVERAGE DRIVEN CONSTRAINT RANDOM VERIFICATION ARCHITECTURE


..................... Verification Components Required For Cdcrv
..................... Stimulus
..................... Stimulus Generator
..................... Transactor
..................... Driver
..................... Monitor
..................... Assertion Based Monitor
..................... Data Checker
..................... Scoreboard
..................... Coverage
..................... Utilities
..................... Environment
..................... Tests

............PHASES OF VERIFICATION
..................... Verification Plan
..................... Building Testbench
..................... Writing Tests
..................... Integrating Code Coverage
..................... Analyze Coverage

............ONES COUNTER EXAMPLE


..................... Specification
..................... Test Plan
..................... Block Diagram
..................... Verification Environment Hierarchy
..................... Testbench Components
..................... Stimulus
..................... Driver
..................... Monitor
..................... Assertion Coverage
..................... Scoreboard
..................... Environment
..................... Top
..................... Tests

............VERIFICATION PLAN
..................... Verification Plan Contains The Following
..................... Overview
..................... Feature Extraction
..................... Resources, Budget And Schedule
..................... Verification Environment
..................... System Verilog Verification Flow
..................... Stimulus Generation Plan
..................... Checker Plan
..................... Coverage Plan
..................... Details Of Reusable Components

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/TS_00_INDEX.html[9/26/2012 1:56:57 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TS_00_INDEX.html[9/26/2012 1:56:57 PM]


WWW.TESTBENCH.IN - UVM Tutorial

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INDEX Index


Introduction
SystemVerilog Uvm Testbench
Verification ............INTRODUCTION Uvm Reporting
..................... Installing Uvm Library Uvm Transaction
Constructs Uvm Configuration
Interface ............UVM TESTBENCH Uvm Factory
..................... Uvm_env Uvm Sequence 1
OOPS ..................... Verification Components Uvm Sequence 2
Randomization ..................... About Uvm_component Class Uvm Sequence 3
..................... Uvm_test Uvm Sequence 4
Functional Coverage Uvm Sequence 5
..................... Top Module
Assertion Uvm Sequence 6
............UVM REPORTING Uvm Tlm 1
DPI Uvm Tlm 2
..................... Reporting Methods
UVM Tutorial ..................... Actions Uvm Callback
VMM Tutorial ..................... Configuration
Report a Bug or Comment
OVM Tutorial ............UVM TRANSACTION on This section - Your
..................... Core Utilities input is what keeps
Easy Labs : SV
..................... User Defined Implementations Testbench.in improving
Easy Labs : UVM ..................... Shorthand Macros with time!
Easy Labs : OVM
............UVM CONFIGURATION
Easy Labs : VMM ..................... Set_config_* Methods
AVM Switch TB ..................... Automatic Configuration
..................... Manual Configurations
VMM Ethernet sample ..................... Configuration Setting Members

............UVM FACTORY
Verilog ..................... Registration
Verification ..................... Construction
..................... Overriding
Verilog Switch TB
Basic Constructs ............UVM SEQUENCE 1
..................... Introduction
..................... Sequence And Driver Communication
..................... Simple Example
OpenVera ..................... Sequence Item
Constructs ..................... Sequence
Switch TB ..................... Sequencer
..................... Driver
RVM Switch TB ..................... Driver And Sequencer Connectivity
RVM Ethernet sample ..................... Testcase
............UVM SEQUENCE 2
..................... Pre Defined Sequences
Specman E ..................... Sequence Action Macro
Interview Questions ..................... Example Of Pre_do,Mid_do And Post_do
..................... List Of Sequence Action Macros
..................... Examples With Sequence Action Macros

............UVM SEQUENCE 3
..................... Body Callbacks
..................... Hierarchical Sequences
..................... Sequential Sequences
..................... Parallel Sequences

............UVM SEQUENCE 4

http://testbench.in/UT_00_INDEX.html[9/26/2012 1:57:04 PM]


WWW.TESTBENCH.IN - UVM Tutorial

..................... Sequencer Arbitration


..................... Setting The Sequence Priority

............UVM SEQUENCE 5
..................... Sequencer Registration Macros
..................... Setting Sequence Members

............UVM SEQUENCE 6
..................... Exclusive Access
..................... Lock-Unlock
..................... Grab-Ungrab

............UVM TLM 1
..................... Port Based Data Transfer
..................... Task Based Data Transfer
..................... Operation Supported By Tlm Interface
..................... Methods
..................... Tlm Terminology
..................... Tlm Interface Compilation Models
..................... Interfaces
..................... Direction
..................... All Interfaces In Uvm

............UVM TLM 2
..................... Analysis
..................... Tlm Fifo
..................... Example

............UVM CALLBACK
..................... Driver And Driver Callback Class Source Code
..................... Testcase Source Code
..................... Testcase 2 Source Code
..................... Testcase 3 Source Code
..................... Testcase 4 Source Code
..................... Methods
..................... Macros

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/UT_00_INDEX.html[9/26/2012 1:57:04 PM]


WWW.TESTBENCH.IN - VMM Tutorial

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INDEX Index


Introduction
SystemVerilog Vmm Log
Verification ............INTRODUCTION Vmm Env
Vmm Data
Constructs ............VMM LOG Vmm Channel
Interface ..................... Vmm Message Type Vmm Atomic Generator
..................... Message Severity Vmm Xactor
OOPS ..................... Vmm Log Macros Vmm Callback
Randomization ..................... Message Handling Vmm Test
..................... Counting Number Of Messages Based Of Message Severity Vmm Channel Record
Functional Coverage And Playback
Assertion ............VMM ENV Vmm Scenario Generator
Vmm Opts
DPI
............VMM DATA
UVM Tutorial ..................... Complete Packet Class Report a Bug or Comment
..................... Vmm_data Methods on This section - Your
VMM Tutorial
input is what keeps
OVM Tutorial ............VMM CHANNEL Testbench.in improving
..................... Complete Example with time!
Easy Labs : SV
..................... Vmm Channel Methods.
Easy Labs : UVM
Easy Labs : OVM ............VMM ATOMIC GENERATOR
..................... Completed Example
Easy Labs : VMM
AVM Switch TB ............VMM XACTOR
..................... Complete Vmm_xactor Example
VMM Ethernet sample ..................... Vmm_xactor Members

............VMM CALLBACK
Verilog ..................... Complete Source Code
Verification ..................... Testcase 1 Source Code
..................... Testcase 2 Source Code
Verilog Switch TB ..................... Testcase 3 Source Code
Basic Constructs ..................... Testcase 4 Source Code

............VMM TEST
..................... Writing A Testcase
OpenVera ..................... Example Of Using Vmm_test
Constructs
Switch TB ............VMM CHANNEL RECORD AND PLAYBACK
..................... Recording
RVM Switch TB ..................... Playing Back
RVM Ethernet sample
............VMM SCENARIO GENERATOR
..................... Example
..................... Scenario Code
Specman E ..................... Testcase
Interview Questions
............VMM OPTS

http://testbench.in/VM_00_INDEX.html[9/26/2012 1:57:13 PM]


WWW.TESTBENCH.IN - VMM Tutorial

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/VM_00_INDEX.html[9/26/2012 1:57:13 PM]


WWW.TESTBENCH.IN - OVM Tutorial

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INDEX Index


Introduction
SystemVerilog Ovm Testbench
Verification ............INTRODUCTION Ovm Reporting
Ovm Transaction
Constructs ............OVM TESTBENCH Ovm Factory
Interface ..................... Ovm_env Ovm Sequence 1
..................... Verification Components Ovm Sequence 2
OOPS ..................... About Ovm_component Class Ovm Sequence 3
Randomization ..................... Ovm_test Ovm Sequence 4
..................... Top Module Ovm Sequence 5
Functional Coverage Ovm Sequence 6
Assertion ............OVM REPORTING Ovm Configuration
DPI
..................... Reporting Methods
..................... Actions Report a Bug or Comment
UVM Tutorial ..................... Configuration on This section - Your
input is what keeps
VMM Tutorial
............OVM TRANSACTION Testbench.in improving
OVM Tutorial ..................... Core Utilities with time!
Easy Labs : SV ..................... User Defined Implementations
..................... Shorthand Macros
Easy Labs : UVM
Easy Labs : OVM ............OVM FACTORY
..................... Registration
Easy Labs : VMM ..................... Construction
AVM Switch TB ..................... Overriding
VMM Ethernet sample ............OVM SEQUENCE 1
..................... Introduction
..................... Sequence And Driver Communication
Verilog ..................... Simple Example
Verification ..................... Sequence Item
..................... Sequence
Verilog Switch TB ..................... Sequencer
Basic Constructs ..................... Driver
..................... Driver And Sequencer Connectivity
..................... Testcase
OpenVera ............OVM SEQUENCE 2
Constructs ..................... Pre Defined Sequences
Switch TB ..................... Sequence Action Macro
..................... Example Of Pre_do,Mid_do And Post_do
RVM Switch TB ..................... List Of Sequence Action Macros
RVM Ethernet sample ..................... Examples With Sequence Action Macros
............OVM SEQUENCE 3
..................... Body Callbacks
Specman E ..................... Hierarchical Sequences
Interview Questions ..................... Sequential Sequences
..................... Parallel Sequences

............OVM SEQUENCE 4
..................... Sequencer Arbitration
..................... Setting The Sequence Priority

............OVM SEQUENCE 5
..................... Sequencer Registration Macros
..................... Setting Sequence Members

http://testbench.in/OT_00_INDEX.html[9/26/2012 1:57:21 PM]


WWW.TESTBENCH.IN - OVM Tutorial

............OVM SEQUENCE 6
..................... Exclusive Access
..................... Lock-Unlock
..................... Grab-Ungrab

............OVM CONFIGURATION
..................... Set_config_* Methods
..................... Automatic Configuration
..................... Manual Configurations
..................... Configuration Setting Members

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OT_00_INDEX.html[9/26/2012 1:57:21 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INDEX Index


Introduction
SystemVerilog Specification
Verification ............INTRODUCTION Verification Plan
Phase 1 Top
Constructs ............SPECIFICATION Phase 2 Environment
Interface ..................... Switch Specification Phase 3 Reset
..................... Packet Format Phase 4 Packet
OOPS ..................... Packet Header Phase 5 Driver
Randomization ..................... Configuration Phase 6 Receiver
..................... Interface Specification Phase 7 Scoreboard
Functional Coverage Phase 8 Coverage
..................... Memory Interface
Assertion ..................... Input Port Phase 9 Testcase
DPI
..................... Output Port
Report a Bug or Comment
UVM Tutorial ............VERIFICATION PLAN on This section - Your
..................... Overview input is what keeps
VMM Tutorial
..................... Feature Extraction Testbench.in improving
OVM Tutorial ..................... Stimulus Generation Plan with time!
Easy Labs : SV ..................... Coverage Plan
..................... Verification Environment
Easy Labs : UVM
Easy Labs : OVM ............PHASE 1 TOP
..................... Interfaces
Easy Labs : VMM ..................... Testcase
AVM Switch TB ..................... Top Module
..................... Top Module Source Code
VMM Ethernet sample
............PHASE 2 ENVIRONMENT
..................... Environment Class
Verilog ..................... Run
Verification ..................... Environment Class Source Code
Verilog Switch TB ............PHASE 3 RESET
Basic Constructs
............PHASE 4 PACKET
..................... Packet Class Source Code
..................... Program Block Source Code
OpenVera
Constructs ............PHASE 5 DRIVER
Switch TB ..................... Driver Class Source Code
..................... Environment Class Source Code
RVM Switch TB
RVM Ethernet sample ............PHASE 6 RECEIVER
..................... Receiver Class Source Code
..................... Environment Class Source Code
Specman E ............PHASE 7 SCOREBOARD
Interview Questions ..................... Scoreboard Class Source Code
..................... Source Code Of The Environment Class

............PHASE 8 COVERAGE
..................... Source Code Of Coverage Class
..................... Source Code Of The Scoreboard Class

............PHASE 9 TESTCASE
..................... Source Code Of Constraint Testcase

http://testbench.in/SL_00_INDEX.html[9/26/2012 1:57:28 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SL_00_INDEX.html[9/26/2012 1:57:28 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INDEX Index


Introduction
SystemVerilog Specification
Verification ............INTRODUCTION Verification Plan
..................... Installing Uvm Library Phase 1 Top
Constructs Phase 2 Configuration
Interface ............SPECIFICATION Phase 3 Environment N
..................... Switch Specification Testcase
OOPS ..................... Packet Format Phase 4 Packet
Randomization ..................... Configuration Phase 5 Sequencer N
..................... Interface Specification Sequence
Functional Coverage Phase 6 Driver
Assertion ............VERIFICATION PLAN Phase 7 Receiver
..................... Overview Phase 8 Scoreboard
DPI
..................... Feature Extraction
UVM Tutorial ..................... Stimulus Generation Plan Report a Bug or Comment
..................... Verification Environment on This section - Your
VMM Tutorial
input is what keeps
OVM Tutorial ............PHASE 1 TOP Testbench.in improving
..................... Interface with time!
Easy Labs : SV
..................... Top Module
Easy Labs : UVM
Easy Labs : OVM ............PHASE 2 CONFIGURATION
..................... Configuration
Easy Labs : VMM ..................... Updates To Top Module
AVM Switch TB
............PHASE 3 ENVIRONMENT N TESTCASE
VMM Ethernet sample ..................... Environment
..................... Testcase

Verilog ............PHASE 4 PACKET


Verification ..................... Packet
..................... Test The Transaction Implementation
Verilog Switch TB
Basic Constructs ............PHASE 5 SEQUENCER N SEQUENCE
..................... Sequencer
..................... Sequence
OpenVera ............PHASE 6 DRIVER
Constructs ..................... Driver
Switch TB ..................... Environment Updates
..................... Testcase Updates
RVM Switch TB
RVM Ethernet sample ............PHASE 7 RECEIVER
..................... Receiver
..................... Environment Class Updates
Specman E ............PHASE 8 SCOREBOARD
Interview Questions ..................... Scoreboard
..................... Environment Class Updates

http://testbench.in/UL_00_INDEX.html[9/26/2012 1:57:36 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/UL_00_INDEX.html[9/26/2012 1:57:36 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INDEX Index


Introduction
SystemVerilog Specification
Verification ............INTRODUCTION Verification Plan
Phase 1 Top
Constructs ............SPECIFICATION Phase 2 Configuration
Interface ..................... Switch Specification Phase 3 Environment N
..................... Packet Format Testcase
OOPS ..................... Configuration Phase 4 Packet
Randomization ..................... Interface Specification Phase 5 Sequencer N
Sequence
Functional Coverage Phase 6 Driver
............VERIFICATION PLAN
Assertion ..................... Overview Phase 7 Receiver
..................... Feature Extraction Phase 8 Scoreboard
DPI
..................... Stimulus Generation Plan
UVM Tutorial ..................... Verification Environment Report a Bug or Comment
on This section - Your
VMM Tutorial
............PHASE 1 TOP input is what keeps
OVM Tutorial ..................... Interface Testbench.in improving
..................... Top Module with time!
Easy Labs : SV
Easy Labs : UVM ............PHASE 2 CONFIGURATION
Easy Labs : OVM ..................... Configuration
..................... Updates To Top Module
Easy Labs : VMM
AVM Switch TB ............PHASE 3 ENVIRONMENT N TESTCASE
..................... Environment
VMM Ethernet sample ..................... Testcase

............PHASE 4 PACKET
Verilog ..................... Packet
Verification ..................... Test The Transaction Implementation
Verilog Switch TB ............PHASE 5 SEQUENCER N SEQUENCE
Basic Constructs ..................... Sequencer
..................... Sequence

............PHASE 6 DRIVER
OpenVera ..................... Driver
Constructs ..................... Environment Updates
Switch TB ..................... Testcase Updates
RVM Switch TB ............PHASE 7 RECEIVER
RVM Ethernet sample ..................... Receiver
..................... Environment Class Updates

............PHASE 8 SCOREBOARD
Specman E ..................... Scoreboard
Interview Questions ..................... Environment Class Updates

http://testbench.in/CM_00_INDEX.html[9/26/2012 1:57:46 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CM_00_INDEX.html[9/26/2012 1:57:46 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INDEX Index


Introduction
SystemVerilog Specification
Verification ............INTRODUCTION Verification Plan
Phase 1 Top
Constructs ............SPECIFICATION Phase 2 Environment
Interface ..................... Switch Specification Phase 3 Reset
..................... Packet Format Phase 4 Packet
OOPS ..................... Configuration Phase 5 Generator
Randomization ..................... Interface Specification Phase 6 Driver
Phase 7 Receiver
Functional Coverage Phase 8 Scoreboard
............VERIFICATION PLAN
Assertion ..................... Overview Phase 9 Coverage
DPI
..................... Feature Extraction
..................... Stimulus Generation Plan Report a Bug or Comment
UVM Tutorial ..................... Coverage Plan on This section - Your
..................... Verification Environment input is what keeps
VMM Tutorial
Testbench.in improving
OVM Tutorial ............PHASE 1 TOP with time!
Easy Labs : SV ..................... Interfaces
..................... Testcase
Easy Labs : UVM ..................... Top Module
Easy Labs : OVM ..................... Top Module Source Code
Easy Labs : VMM ............PHASE 2 ENVIRONMENT
AVM Switch TB ..................... Environment Class
..................... Run
VMM Ethernet sample ..................... Environment Class Source Code

............PHASE 3 RESET
Verilog
Verification ............PHASE 4 PACKET
..................... Packet Class Source Code
Verilog Switch TB ..................... Program Block Source Code
Basic Constructs
............PHASE 5 GENERATOR
..................... Environment Class Source Code
OpenVera ............PHASE 6 DRIVER
Constructs ..................... Driver Class Source Code
Switch TB ..................... Environment Class Source Code
RVM Switch TB ............PHASE 7 RECEIVER
RVM Ethernet sample ..................... Receiver Class Source Code
..................... Environment Class Source Code

............PHASE 8 SCOREBOARD
Specman E ..................... Scoreboard Class Source Code
Interview Questions ..................... Source Code Of The Environment Class

............PHASE 9 COVERAGE
..................... Source Code Of Coverage Class

http://testbench.in/VL_00_INDEX.html[9/26/2012 1:57:53 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/VL_00_INDEX.html[9/26/2012 1:57:53 PM]


WWW.TESTBENCH.IN - AVM Switch TB

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INDEX Index


Avm Introduction
SystemVerilog Dut Specification
Verification ............AVM INTRODUCTION Rtl
..................... Tlm Top
Constructs ..................... Building Blocks Interface
Interface ..................... Avm_transactors Environment
..................... Avm_env Packet
OOPS ..................... Avm_messaging Packet Generator
Randomization Configuration
............DUT SPECIFICATION Driver
Functional Coverage Reciever
..................... Configuration
Assertion ..................... Interface Specification Scoreboard
DPI
..................... Memory Interface
..................... Input Interface Report a Bug or Comment
UVM Tutorial ..................... Output Interface on This section - Your
input is what keeps
VMM Tutorial
............RTL Testbench.in improving
OVM Tutorial with time!
Easy Labs : SV ............TOP
..................... Verilog Top
Easy Labs : UVM
Easy Labs : OVM ............INTERFACE
Easy Labs : VMM ............ENVIRONMENT
AVM Switch TB
............PACKET
VMM Ethernet sample
............PACKET GENERATOR

Verilog ............CONFIGURATION
Verification
............DRIVER
Verilog Switch TB
Basic Constructs ............RECIEVER

............SCOREBOARD
OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/AV_00_INDEX.html[9/26/2012 1:58:01 PM]


WWW.TESTBENCH.IN - AVM Switch TB

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/AV_00_INDEX.html[9/26/2012 1:58:01 PM]


WWW.TESTBENCH.IN - Verilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INDEX Index


Introduction
SystemVerilog Linear Tb
Verification ............INTRODUCTION File Io Tb
..................... Test Bench Overview State Machine Based Tb
Constructs Task Based Tb
Interface ............LINEAR TB Self Checking Testbench
..................... Linear Testbench Verification Flow
OOPS Clock Generator
Randomization ............FILE IO TB Simulation
..................... File I/O Based Testbench Incremental Compilation
Functional Coverage Store And Restore
Assertion ............STATE MACHINE BASED TB Event Cycle Simulation
Time Scale And Precision
DPI Stimulus Generation
............TASK BASED TB
UVM Tutorial ..................... Task And Function Based Tb System Function Random
A Myth
VMM Tutorial Race Condition
............SELF CHECKING TESTBENCH
OVM Tutorial ..................... Stimulus Generator Checker
..................... Bus Functional Models Task And Function
Easy Labs : SV
..................... Driver Process Control
Easy Labs : UVM ..................... Reciver Disableing The Block
..................... Protocol Monitor Watchdog
Easy Labs : OVM
..................... Scoreboard Compilation N Simulation
Easy Labs : VMM ..................... Checker Switchs
AVM Switch TB ..................... Coverage Debugging
..................... Code Coverage About Code Coverage
VMM Ethernet sample ..................... Functional Coverage Testing Stratigies
File Handling
............VERIFICATION FLOW Verilog Semaphore
Verilog ..................... Planning Finding Testsenarious
..................... Feature Extraction Handling Testcase Files
Verification
..................... Verification Environment Architecture Plan Terimination
Verilog Switch TB Error Injuction
............CLOCK GENERATOR Register Verification
Basic Constructs
..................... Timescale And Precision Enlightment Parameterised Macros
White Gray Black Box
............SIMULATION Regression
OpenVera ..................... Simulation Steps Tips
Constructs ..................... Macro Preprocessing
..................... Compilation (Analyzer) Report a Bug or Comment
Switch TB
..................... Elaboration on This section - Your
RVM Switch TB ..................... Optimization input is what keeps
Testbench.in improving
RVM Ethernet sample ..................... Initialization
..................... Execution with time!
..................... Simulation Process
Specman E ............INCREMENTAL COMPILATION
Interview Questions
............STORE AND RESTORE

............EVENT CYCLE SIMULATION


..................... Event Based Simulation
..................... Cycle Based Simulation

............TIME SCALE AND PRECISION


..................... Time Scale And Time Precision
..................... $Time Vs $Realtime
..................... System Task Printtimescale

http://testbench.in/TB_00_INDEX.html[9/26/2012 1:58:09 PM]


WWW.TESTBENCH.IN - Verilog for Verification

..................... System Task Timeformat

............STIMULUS GENERATION

............SYSTEM FUNCTION RANDOM A MYTH

............RACE CONDITION
..................... What Is Race Condition?
..................... Why Race Condition?
..................... When Race Is Visible?
..................... How To Prevent Race Condition?
..................... Types Of Race Condition
..................... Write-Write Race
..................... Read-Write Race
..................... More Race Example
..................... Event Terminology
..................... The Stratified Event Queue
..................... Determinism
..................... Nondeterminism
..................... Guideline To Avoid Race Condition
..................... Avoid Race Between Testbench And Dut

............CHECKER
..................... Protocol Checker
..................... Data_checker
..................... Modularization

............TASK AND FUNCTION


..................... Functions
..................... Task
..................... Task And Function Queries
..................... Constant Function
..................... Reentrant Tasks And Functions

............PROCESS CONTROL
..................... Nonblocking Task
..................... Fork/Join Recap
..................... Fork/Join None
..................... Fork/Join Any

............DISABLEING THE BLOCK


..................... Disable
..................... Goto
..................... Break
..................... Continue

............WATCHDOG

............COMPILATION N SIMULATION SWITCHS


..................... Compilation And Simulation Directives
..................... Example

............DEBUGGING
..................... Pass Or Fail
..................... Waveform Viewer
..................... Log File
..................... Message Control System
..................... Message Severity Levels
..................... Message Controlling Levels
..................... Passing Comments To Waveform Debugger
..................... $Display N $Strobe
..................... Who Should Do The Rtl Debugging?

............ABOUT CODE COVERAGE

http://testbench.in/TB_00_INDEX.html[9/26/2012 1:58:09 PM]


WWW.TESTBENCH.IN - Verilog for Verification

..................... Types Of Coverage


..................... Code Coverage
..................... Statement Coverage /Line Coverage
..................... Block/Segment Coverage
..................... Branch / Decision / Conditional Coverage
..................... Path Coverage
..................... Expression Coverage
..................... Toggle Coverage
..................... Variable Coverage
..................... Triggering / Event Coverage
..................... Parameter Coverage
..................... Functional Coverage
..................... Fsm Coverage
..................... State Coverage
..................... Transition Coverage
..................... Sequence Coverage
..................... Tool Support
..................... Limitation Of Code Coverage

............TESTING STRATIGIES
..................... Bottom-Up
..................... Unit Level
..................... Sub-Asic Level
..................... Asic Level
..................... System Level
..................... Flat

............FILE HANDLING
..................... Fopen And Fclose
..................... Fdisplay
..................... Fmonitor
..................... Fwrite
..................... Mcd
..................... Formating Data To String

............VERILOG SEMAPHORE
..................... Semaphore In Verilog

............FINDING TESTSENARIOUS
..................... Register Tests
..................... System Tests
..................... Interrupt Tests
..................... Interface Tests
..................... Functional Tests
..................... Error Tests
..................... Golden Tests
..................... Performance Tests

............HANDLING TESTCASE FILES

............TERIMINATION

............ERROR INJUCTION
..................... Value Errors
..................... Temporal Errors
..................... Interface Error
..................... Sequence Errors

............REGISTER VERIFICATION
..................... Register Verification
..................... Register Classification
..................... Features

............PARAMETERISED MACROS

............WHITE GRAY BLACK BOX


..................... Black Box Verification
..................... White Box Verification
..................... Gray Box Verification

............REGRESSION

............TIPS
..................... How To Avoid "Module Xxx Already Defined" Error

http://testbench.in/TB_00_INDEX.html[9/26/2012 1:58:09 PM]


WWW.TESTBENCH.IN - Verilog for Verification

..................... Colourful Messages


..................... Debugging Macros

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TB_00_INDEX.html[9/26/2012 1:58:09 PM]


WWW.TESTBENCH.IN - Verilog Switch TestBench

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INDEX Index


Dut Specification
SystemVerilog Rtl
Verification ............DUT SPECIFICATION Top
..................... Configuration Packet
Constructs ..................... Interface Specification Driver
Interface ..................... Memory Interface Reciever
..................... Input Interface Scoreboard
OOPS ..................... Output Interface Env
Randomization
............RTL Report a Bug or Comment
Functional Coverage on This section - Your
Assertion ............TOP input is what keeps
..................... Verification Environment Testbench.in improving
DPI with time!
..................... Top Module
UVM Tutorial
VMM Tutorial ............PACKET
OVM Tutorial ............DRIVER
Easy Labs : SV
............RECIEVER
Easy Labs : UVM
Easy Labs : OVM ............SCOREBOARD
Easy Labs : VMM ............ENV
AVM Switch TB
VMM Ethernet sample

Verilog
Verification
Verilog Switch TB
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/VS_00_INDEX.html[9/26/2012 1:58:17 PM]


WWW.TESTBENCH.IN - Verilog Switch TestBench

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/VS_00_INDEX.html[9/26/2012 1:58:17 PM]


WWW.TESTBENCH.IN - Verilog Basic Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INDEX Index


Introduction
SystemVerilog Syntax
Verification ............INTRODUCTION Data Types
..................... Introduction Operators
Constructs Assignments
Interface ............SYNTAX Control Constructs
Procedural Timing
OOPS ............DATA TYPES Controls
Randomization ..................... Value Set Structure
..................... Net Block Statements
Functional Coverage Structured Procedures
..................... Variable Or Reg
Assertion ..................... Vectors
..................... Memories Report a Bug or Comment
DPI on This section - Your
..................... Net Types
UVM Tutorial input is what keeps
............OPERATORS Testbench.in improving
VMM Tutorial
..................... Binary Arithmetic Operators with time!
OVM Tutorial ..................... Unary Arithmetic Operators
Easy Labs : SV ..................... Relational Operators
..................... Logical Operators
Easy Labs : UVM ..................... Bitwise Operators
Easy Labs : OVM ..................... Unary Reduction Operators
..................... Other Operators
Easy Labs : VMM ..................... Operator Precedence
AVM Switch TB
............ASSIGNMENTS
VMM Ethernet sample ..................... Blocking Procedural Assignments
..................... The Nonblocking Procedural Assignment
..................... Procedural Continuous Assignments
Verilog ..................... Assign And Deassign Procedural Statements
Verification ..................... Force And Release Procedural Statements
..................... Delays
Verilog Switch TB ..................... Inter Assignmnet Delay .
Basic Constructs ..................... Intra-Assignment Delay Control

............CONTROL CONSTRUCTS
..................... If And If Else Statements
OpenVera ..................... Case
Constructs ..................... Forever
Switch TB ..................... Repeat
..................... While
RVM Switch TB ..................... For
RVM Ethernet sample
............PROCEDURAL TIMING CONTROLS
..................... Delay Control
..................... Event Control
Specman E ..................... Named Events
Interview Questions
............STRUCTURE
..................... Module
..................... Ports
..................... Signals

............BLOCK STATEMENTS
..................... Sequential Blocks
..................... Parallel Blocks

............STRUCTURED PROCEDURES

http://testbench.in/VT_00_INDEX.html[9/26/2012 1:58:27 PM]


WWW.TESTBENCH.IN - Verilog Basic Constructs

..................... Initial
..................... Always
..................... Functions
..................... Task

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/VT_00_INDEX.html[9/26/2012 1:58:27 PM]


WWW.TESTBENCH.IN - Vera Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INDEX Index


Introduction
SystemVerilog Data Types
Verification ............INTRODUCTION Linked List
..................... Introduction Operators Part 1
Constructs ..................... Comments In Openvera Operators Part 2
Interface ..................... Numbers In Openvera Operators Part 3
Operator Precedence
OOPS ............DATA TYPES Control Statements
Randomization ..................... Basic Data Types Procedures And Methods
..................... Integer Interprocess
Functional Coverage Fork Join
..................... Register
Assertion ..................... String Shadow Variables
..................... Event Fork Join Control
DPI Wait Var
..................... Enumerated Types
UVM Tutorial ..................... Virtual Ports Event Sync
..................... Arrays Event Trigger
VMM Tutorial Semaphore
..................... Fixed-Size Arrays
OVM Tutorial ..................... Dynamic Arrays Regions
..................... Associative Arrays Mailbox
Easy Labs : SV
..................... Smart Queues Timeouts
Easy Labs : UVM ..................... Class Oop
Casting
Easy Labs : OVM
............LINKED LIST Randomization
Easy Labs : VMM ..................... Linked List Randomization Methods
AVM Switch TB ..................... List Methods Constraint Block
Constraint Expression
VMM Ethernet sample ............OPERATORS PART 1 Variable Ordaring
..................... Operators Aop
..................... Concatenation Predefined Methods
Verilog ..................... Arithmetic String Methods
..................... Relational Queue Methods
Verification
..................... Equality Dut Communication
Verilog Switch TB Functional Coverage
Basic Constructs ............OPERATORS PART 2
..................... Logical Report a Bug or Comment
..................... Bitwise on This section - Your
..................... Reduction input is what keeps
OpenVera Testbench.in improving
Constructs ............OPERATORS PART 3 with time!
Switch TB ..................... Shift
..................... Bit-Reverse
RVM Switch TB ..................... Increment And Decrement
RVM Ethernet sample ..................... Conditional
..................... Set
..................... Replication
Specman E ............OPERATOR PRECEDENCE
Interview Questions ..................... Operator Precedence

............CONTROL STATEMENTS
..................... Sequential Statements

............PROCEDURES AND METHODS


..................... Procedures And Methods
..................... Pass By Value
..................... Pass By Reference
..................... Default Arguments
..................... Optional Arguments

http://testbench.in/OV_00_INDEX.html[9/26/2012 1:58:37 PM]


WWW.TESTBENCH.IN - Vera Constructs

............INTERPROCESS
..................... Interprocess Synchronization And Communication

............FORK JOIN
..................... Fork Join

............SHADOW VARIABLES
..................... Shadow Variables

............FORK JOIN CONTROL


..................... Fork And Join Control
..................... Wait_chiled()
..................... Terminate
..................... Suspend_thread

............WAIT VAR
..................... Wait_var

............EVENT SYNC
..................... Event Methods

............EVENT TRIGGER
..................... Event Trigger
..................... Event Variables

............SEMAPHORE
..................... Semaphore

............REGIONS
..................... Regions

............MAILBOX
..................... Mailbox

............TIMEOUTS
..................... Timeouts

............OOP
..................... Object Oriented Programming
..................... Properties
..................... This
..................... Class Extensions
..................... Polymorphism
..................... Super
..................... Abstract Class

............CASTING

............RANDOMIZATION
..................... Constrained Random Verification
..................... Random Varible Declaration
..................... Rand Modifier
..................... Randc Modifier

............RANDOMIZATION METHODS
..................... Randomization Built-In Methods
..................... Randomize()
..................... Pre_randomize And Post_randomize

http://testbench.in/OV_00_INDEX.html[9/26/2012 1:58:37 PM]


WWW.TESTBENCH.IN - Vera Constructs

............CONSTRAINT BLOCK
..................... Constraint Block
..................... Inline Constraints
..................... Disabling Constraint Block

............CONSTRAINT EXPRESSION
..................... Constraint Expressions
..................... Set Membership
..................... Weighted Distribution
..................... Implication
..................... If..Else
..................... Iterative

............VARIABLE ORDARING
..................... Variable Ordaring

............AOP
..................... Aspect Oriented Extensions

............PREDEFINED METHODS
..................... Predefined Methods
..................... New()
..................... Finalize()
..................... Object_print
..................... Deep Object Compare
..................... Deep Object Copy
..................... Pack And Unpack

............STRING METHODS

............QUEUE METHODS

............DUT COMMUNICATION
..................... Connecting To Hdl
..................... Interface Declaration
..................... Direct Hdl Node Connection
..................... Blocking And Non-Blocking Drives

............FUNCTIONAL COVERAGE
..................... Functional Coverage
..................... Coverage Group
..................... Sample_event
..................... Coverage_point
..................... Cross Coverage

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OV_00_INDEX.html[9/26/2012 1:58:37 PM]


WWW.TESTBENCH.IN - Vera Switch TestBench

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INDEX Index


Dut Specification
SystemVerilog Rtl
Verification ............DUT SPECIFICATION Top
..................... Configuration Interface
Constructs ..................... Interface Specification Packet
Interface ..................... Memory Interface Packet Generator
..................... Input Interface Cfg Driver
OOPS ..................... Output Interface Driver
Randomization Reciever
............RTL Scoreboard
Functional Coverage Env
Assertion ............TOP
..................... Verification Environment Report a Bug or Comment
DPI on This section - Your
..................... Top Module
UVM Tutorial input is what keeps
............INTERFACE Testbench.in improving
VMM Tutorial
with time!
OVM Tutorial ............PACKET
Easy Labs : SV
............PACKET GENERATOR
Easy Labs : UVM
Easy Labs : OVM ............CFG DRIVER
Easy Labs : VMM ............DRIVER
AVM Switch TB
............RECIEVER
VMM Ethernet sample
............SCOREBOARD

Verilog ............ENV
Verification
Verilog Switch TB
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/OS_00_INDEX.html[9/26/2012 1:58:44 PM]


WWW.TESTBENCH.IN - Vera Switch TestBench

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OS_00_INDEX.html[9/26/2012 1:58:44 PM]


WWW.TESTBENCH.IN - RVM Switch TB

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INDEX Index


Introduction
SystemVerilog Rtl
Verification ............INTRODUCTION Top
..................... Dut Specification Interface
Constructs ..................... Configuration Program Block
Interface ..................... Interface Specification Environment
..................... Memory Interface Packet
OOPS ..................... Input Interface Configuration
Randomization ..................... Output Interface Driver
Reciever
Functional Coverage Scoreboard
............RTL
Assertion
............TOP Report a Bug or Comment
DPI on This section - Your
UVM Tutorial ............INTERFACE input is what keeps
Testbench.in improving
VMM Tutorial
............PROGRAM BLOCK with time!
OVM Tutorial ..................... Testbench Program
Easy Labs : SV
............ENVIRONMENT
Easy Labs : UVM
Easy Labs : OVM ............PACKET
Easy Labs : VMM ............CONFIGURATION
AVM Switch TB
............DRIVER
VMM Ethernet sample
............RECIEVER

Verilog ............SCOREBOARD
Verification
Verilog Switch TB
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/RV_00_INDEX.html[9/26/2012 1:58:52 PM]


WWW.TESTBENCH.IN - RVM Switch TB

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/RV_00_INDEX.html[9/26/2012 1:58:52 PM]


WWW.TESTBENCH.IN

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS RVM Ethernet


SystemVerilog
Verification This testbench is developed in RVM (Vera) for the Ethernet core available from opencores.org. My intension here is
to explore the RVM methodology but not to verify the Ethernet core, as a result there are many bugs in the
Constructs environment. I dont remember the versions of RVM but I developed these in the third quarter of 2007. To simulate
Interface this testbench some dependencies on libraries has to be removed from RTL. It takes bit time for these changes in
RTL.
OOPS
Randomization
Feauters:
Functional Coverage
Assertion Full support of automatic random, constrained random, and directed testcase creation.
DPI Supports injuction of random errored packets.
Supports 1G Fullduplex modeled both in RX and TX paths.
UVM Tutorial Protocol Checker/Monitor for self checking.
VMM Tutorial Built in function coverage support for packets.
Developed in Vera using Synopsys RVM base classes.
OVM Tutorial
Easy Labs : SV NOTE: All trademarks are the property of their respective owners.
Easy Labs : UVM
Easy Labs : OVM Download rvm.tar
Browse the code in rvm_eth.tar
Easy Labs : VMM
AVM Switch TB
BLOCK DIAGRAM OF ETHERNET VERIFICATION ENVIRONMENT
VMM Ethernet sample

Verilog
Verification
Verilog Switch TB
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/ethernet_rvm.html[9/26/2012 1:58:59 PM]


WWW.TESTBENCH.IN

copyright © 2007 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/ethernet_rvm.html[9/26/2012 1:58:59 PM]


WWW.TESTBENCH.IN

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS

SystemVerilog
Verification
Constructs UVM/OVM Killing Sequences on Sequencer Abruptly by Vishnu Prashant.
Interface Sometimes you may need to drive input until you see come condition or some timer expires. Read ...
OOPS
Randomization
Do not rely on illegal_bins for checking purpose. by Ankit Gopani.
Functional Coverage If you rely on cover group where you have written illegal_bins,
Assertion what happens when you turn off the coverage?? Read ...
DPI
UVM Tutorial
PASS and FAIL Messages with Colors...! by Ankit Gopani.
VMM Tutorial How many among you know that you can actually display color messages using Verilog and SystemVerilog? Read ...
OVM Tutorial
Easy Labs : SV
Easy Labs : UVM VMM 1.2 and VMM_sb_ds example by Ankit Shah.
Easy Labs : VMM
This example contains VMM 1.2 based layered testbench architeracture. My intensation here is to demonstrate
different component of testbench using different base class of VMM. Read ...
Easy Labs : OVM
AVM Switch TB
VMM Ethernet sample Whats new in Systemverilog 2009 ? by Ankit Shah.
The SystemVerilog working group worked hard in the past four years on improving the language and in 2009
Systemverilog LRM was released. There are 30+ noticeable new constructs and 25+ system task are introduced in
Verilog SystemVerilog 2009. Read ...
Verification
Verilog Switch TB
Basic Constructs
Introduction To Ethernet Frames: Part 1 by Bhavani shankar.
The Ethernet protocol basically implements the bottom two layers of the Open Systems Interconnection (OSI) 7-
layer model, i.e., the data link and physical sub layers. Read ...

OpenVera
Constructs
Introduction To Ethernet Frames: Part 2 by Bhavani shankar.
Switch TB we will see a simple testplan for 10G Ethernet Frames. Read ...
RVM Switch TB
RVM Ethernet sample
Introduction To PCI Express by Arjun Shetty.
We will start with a conceptual understanding of PCI Express. This will let us appreciate the importance of PCI
Specman E Express. This will be followed by a brief study of the PCI Express protocol. Then we will look at the enhancements
and improvements of the protocol in the newer 3.0 specs. Read ...
Interview Questions

VCSMX Separate compilation example by Emmanuelle Chu.


When I started to use VCSMX along with system Verilog, one main problem came up: I had to generate one
executable for each program. Read ...

Psychology of Verification Engineer by Gopi Krishna.

http://testbench.in/art.html[9/26/2012 1:59:07 PM]


WWW.TESTBENCH.IN

Soft skills are extremely important for the people in Verification and this is something that is often found to be
neglected by the upcoming Verification engineers. Read ...

Graphical TestBench Generation by Donna Mitchell.


Test Benches can be generated from language independent timing diagrams, which are a natural way to design and
display the parallel activity that occurs in within test benches. Read ...

Verilog Basic Examples by Nithin Singani.


Verilog examples with output: and,or,not,halfadder,fulladder etc Read ...

testbench.in was started in June 2007. This website gets 1,00,000 page visits per month.

If you are interested in sharing your knowledge and get noticed in VLSI WORLD, we are happy to host your thoughts.
If you are interested, please drop us a mail at feedback@testbench.in .

copyright © 2007 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/art.html[9/26/2012 1:59:07 PM]


WWW.TESTBENCH.IN - Specman E

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INDEX Index


Introduction
SystemVerilog E Basics
Verification ............INTRODUCTION Data Types
Operators
Constructs ............E BASICS Struct
Interface ..................... Code Segments Units
..................... Comments List
OOPS ..................... Literals And Constants Methods
Randomization ..................... Sized Numbers Concurrency Actions
..................... Predeï¬Ned Constants Constraints
Functional Coverage Extend
Assertion ............DATA TYPES When And Like
..................... Enumerated Types Events
DPI Temporal Expressions
UVM Tutorial ............OPERATORS Temporal Operators 1
..................... Unary Bitwise Operators Temporal Operators 2
VMM Tutorial Synchronizing With The
..................... Binary Bitwise Operations
OVM Tutorial ..................... Shift Operators Simulator
..................... Boolean Operators Wait And Sync
Easy Labs : SV
..................... Arithmetic Operators Physical Virual Feilds
Easy Labs : UVM ..................... Comparison Operators Packing N Unpacking
..................... Extraction And Concatenation Operators Pre Run N On The Fly
Easy Labs : OVM
..................... Special-Purpose Operators Coverage
Easy Labs : VMM Commands
AVM Switch TB ............STRUCT Extendable Methods
Non Extendable Methods
VMM Ethernet sample ............UNITS And Gate Evc
..................... Units Vs Structs
Report a Bug or Comment
Verilog ............LIST on This section - Your
..................... Regular List input is what keeps
Verification
..................... List Operations Testbench.in improving
Verilog Switch TB ..................... Keyed List with time!
Basic Constructs
............METHODS
..................... Time-Consuming Methods(Tcms)
..................... Invoking Tcms
OpenVera ..................... Execution Flow
Constructs
Switch TB ............Concurrency Actions
..................... All Of
RVM Switch TB ..................... First Of
RVM Ethernet sample
............CONSTRAINTS

............EXTEND
Specman E ..................... Is Also
Interview Questions ..................... Is First
..................... Is Only

............When and Like


..................... Like
..................... When

............EVENTS

............TEMPORAL EXPRESSIONS
..................... Basic Temporal Expressions

http://testbench.in/SP_00_INDEX.html[9/26/2012 1:59:15 PM]


WWW.TESTBENCH.IN - Specman E

..................... Temporal Checking

............Temporal operators 1
..................... Not
..................... Fail
..................... And
..................... Or
..................... { Exp ; Exp }
..................... Eventually
..................... [ Exp ]
..................... [ Exp..Exp ]
..................... ~[ Exp..Exp ]
..................... Temporal Yield Operator

............TEMPORAL OPERATORS 2
..................... Detach
..................... Delay
..................... @ Unary Event Operator
..................... @ Sampling Operator
..................... Cycle
..................... True(Exp)
..................... Change(Exp), Fall(Exp), Rise(Exp)
..................... Consume
..................... Exec

............SYNCHRONIZING WITH THE SIMULATOR

............WAIT AND SYNC


..................... Wait Action
..................... Sync Action
..................... Difference Between Wait And Sync

............PHYSICAL VIRUAL FEILDS


..................... Physical Fields
..................... Ungenerated Fields

............PACKING N UNPACKING
..................... Packing.High
..................... Packing.Low

............PRE RUN N ON THE FLY


..................... Pre-Run Generation
..................... On-The-Fly Generation

............COVERAGE
..................... Coverage Groups
..................... Cover Group Options
..................... Cross-Coverage

............COMMANDS

............Extendable Methods

http://testbench.in/SP_00_INDEX.html[9/26/2012 1:59:15 PM]


WWW.TESTBENCH.IN - Specman E

............Non Extendable Methods

............AND GATE EVC

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SP_00_INDEX.html[9/26/2012 1:59:15 PM]


WWW.TESTBENCH.IN - Systemverilog Interview Questions

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INDEX Index


Functional Verification
SystemVerilog Questions
Verification ............FUNCTIONAL VERIFICATION QUESTIONS Functional Verification
Questions 2
Constructs ............FUNCTIONAL VERIFICATION QUESTIONS 2 Test Your Systemverilog
Interface Skills 1
............TEST YOUR SYSTEMVERILOG SKILLS 1 Test Your Systemverilog
OOPS Skills 2
Randomization ............TEST YOUR SYSTEMVERILOG SKILLS 2 Test Your Systemverilog
Skills 3
Functional Coverage Test Your Systemverilog
............TEST YOUR SYSTEMVERILOG SKILLS 3
Assertion Skills 4
............TEST YOUR SYSTEMVERILOG SKILLS 4 Test Your Sva Skills
DPI Test Your Verilog Skills 1
UVM Tutorial ............TEST YOUR SVA SKILLS Test Your Verilog Skills 2
Test Your Verilog Skills 3
VMM Tutorial Test Your Verilog Skills 4
............TEST YOUR VERILOG SKILLS 1
OVM Tutorial Test Your Verilog Skills 5
............TEST YOUR VERILOG SKILLS 2 Test Your Verilog Skills 6
Easy Labs : SV
Test Your Verilog Skills 7
Easy Labs : UVM ............TEST YOUR VERILOG SKILLS 3 Test Your Verilog Skills 8
Test Your Verilog Skills 9
Easy Labs : OVM
............TEST YOUR VERILOG SKILLS 4 Test Your Verilog Skills
Easy Labs : VMM 10
AVM Switch TB ............TEST YOUR VERILOG SKILLS 5 Test Your Verilog Skills
11
VMM Ethernet sample ............TEST YOUR VERILOG SKILLS 6 Test Your Verilog Skills
12
............TEST YOUR VERILOG SKILLS 7 Test Your Verilog Skills
Verilog 13
............TEST YOUR VERILOG SKILLS 8 Test Your Verilog Skills
Verification
14
Verilog Switch TB ............TEST YOUR VERILOG SKILLS 9 Test Your Verilog Skills
15
Basic Constructs
............TEST YOUR VERILOG SKILLS 10 Test Your Verilog Skills
16
............TEST YOUR VERILOG SKILLS 11 Test Your Verilog Skills
OpenVera 17
Constructs ............TEST YOUR VERILOG SKILLS 12 Test Your Specman Skills
1
Switch TB Test Your Specman Skills
............TEST YOUR VERILOG SKILLS 13
RVM Switch TB 2
Test Your Specman Skills
RVM Ethernet sample ............TEST YOUR VERILOG SKILLS 14
3
............TEST YOUR VERILOG SKILLS 15 Test Your Specman Skills
4
Specman E ............TEST YOUR VERILOG SKILLS 16 Test Your Sta Skills 1
Test Your Sta Skills 2
Interview Questions
............TEST YOUR VERILOG SKILLS 17 Test Your Sta Skills 3
Test Your Sta Skills 4
............TEST YOUR SPECMAN SKILLS 1 Test Your Sta Skills 5
Test Your Sta Skills 6
............TEST YOUR SPECMAN SKILLS 2 Test Your Sta Skills 7
Test Your Dft Skills 1
............TEST YOUR SPECMAN SKILLS 3 Test Your Dft Skills 2
Test Your Dft Skills 3
............TEST YOUR SPECMAN SKILLS 4 Test Your Dft Skills 4
Test Your Uvm Ovm Skills

http://testbench.in/IQ_00_INDEX.html[9/26/2012 1:59:22 PM]


WWW.TESTBENCH.IN - Systemverilog Interview Questions

............TEST YOUR STA SKILLS 1


Report a Bug or Comment
............TEST YOUR STA SKILLS 2 on This section - Your
input is what keeps
............TEST YOUR STA SKILLS 3 Testbench.in improving
with time!
............TEST YOUR STA SKILLS 4

............TEST YOUR STA SKILLS 5

............TEST YOUR STA SKILLS 6

............TEST YOUR STA SKILLS 7

............TEST YOUR DFT SKILLS 1

............TEST YOUR DFT SKILLS 2

............TEST YOUR DFT SKILLS 3

............TEST YOUR DFT SKILLS 4

............TEST YOUR UVM OVM SKILLS

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/IQ_00_INDEX.html[9/26/2012 1:59:22 PM]


WWW.TESTBENCH.IN

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

SystemVerilog Verilog OpenVera Miscellanious


Basic Constructs Verification Concepts Verification Concepts Constructs Articles
Interface UVM Tutorial Switch Example Switch Example Specman E Tutorial
OOPS VMM Tutorial Basic Constructs RVM Switch Example Interview Questions
Randomization OVM Tutorial ... RVM Ethernet Sample ...
Functional Coverage Easy Labs : SV ... ... ...
Assertion Easy Labs : UVM ... ... ...
DPI Easy Labs : OVM ... ... ...
VMM Ethernet Example Easy Labs : VMM ... ... ...
... Easy Labs : AVM ... ... ...

New to this site ? Then check these links


>What People are saying about this Site
>What is on this Site
>Table of Contents

copyright © 2007 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/index.html[9/26/2012 1:59:34 PM]


WWW.TESTBENCH.IN

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS

SystemVerilog
Verification
Gopikrishna
Constructs
Interface He is working with Infinera as Verification Engineer. He has 4 years of experience as ASIC Design Verification
Engineer. Prior to Infinera, he worked with Synopsys,Axiom Design Automation,Syschip and Ample Communication.
OOPS He is expertise in various Hardware verification languages and methodologies. He has experience in Verification of
Randomization Ethernet,PCI Express,I2C and Interlaken.
He is an M.Tech in VLSI Design From Sathyabama University, Chennai.
Functional Coverage
Assertion You can reach him at: gopi@testbench.in
Connect to Gopi @ Linkedin : http://in.linkedin.com/in/systemverilog
DPI
UVM Tutorial Naresh
VMM Tutorial You can reach him at: naresh@testbench.in
OVM Tutorial
Easy Labs : SV
Easy Labs : UVM
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

Verilog
Verification
Verilog Switch TB
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

copyright © 2007 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/aboutus.html[9/26/2012 1:59:43 PM]


WWW.TESTBENCH.IN

http://testbench.in/aboutus.html[9/26/2012 1:59:43 PM]


WWW.TESTBENCH.IN

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS

SystemVerilog
Verification
We would like to express our gratitude to all those who gave us their great support to complete this website.
Constructs
Interface Special thanks to Mr. Vishnu Prasanth and Mr. Ankit J Shah for their valuble time in reviewing the contents of this
site.
OOPS
Randomization Vishnu is currently working with Vitesse, Hyderabad, India and Ankit is currently working with Sibridge Technologies
Pvt. Ltd, Ahmedabad,India .
Functional Coverage
Assertion
DPI
UVM Tutorial
VMM Tutorial
OVM Tutorial
Easy Labs : SV
Easy Labs : UMM
Easy Labs : VMM
Easy Labs : OVM
AVM Switch TB
VMM Ethernet sample

Verilog
Verification
Verilog Switch TB
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

copyright © 2007 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/ack.html[9/26/2012 1:59:52 PM]


WWW.TESTBENCH.IN

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS

SystemVerilog
Verification
Hi Readers,
Constructs
Interface We are continuously working on this site. Since the collection is vast and lot of hard work goes in summing and
providing you the latest and correct information. We sincerely apologize for any typo error if you may come across.
OOPS Very religiously we are trying to improve the quality of the contents and we will really appreciate your suggestions
Randomization and comments. We welcome all innovative ideas and thoughts. Do write to us. You can reach us at
feedback@testbench.in .
Functional Coverage
Assertion
Happy Reading. Life is Good, keep smiling :)
DPI
UVM Tutorial Cheers,
TestBencher Team
VMM Tutorial
OVM Tutorial What People are saying about this Site
Easy Labs : SV
Easy Labs : UVM
Feedback form
Easy Labs : OVM
Easy Labs : VMM
* Required
AVM Switch TB
VMM Ethernet sample Your Email ID *

Verilog
Verification
Comments *
Verilog Switch TB
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample
Submit

Specman E
Powered by Google Docs
Interview Questions
Report Abuse - Terms of Service - Additional Terms

http://testbench.in/feedback.html[9/26/2012 2:00:00 PM]


WWW.TESTBENCH.IN

copyright © 2007 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/feedback.html[9/26/2012 2:00:00 PM]


WWW.TESTBENCH.IN

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG |

TABLE OF CONTENTS

............SystemVerilog Verification -- ASIC DESIGN


..................... Mrd
..................... Architecture Specification
..................... Design Specification
..................... Verification Plan
..................... Rtl Design
..................... Functional Verification
..................... Synthesis
..................... Physical Design
..................... Timing Analysis
..................... Tapeout

............SystemVerilog Verification -- BOTTLE NECK IN ASIC FLOW

............SystemVerilog Verification -- FUNCTIONAL VERIFICATION NEED

............SystemVerilog Verification -- TESTBENCH

............SystemVerilog Verification -- LINEAR TESTBENCH

............SystemVerilog Verification -- LINEAR RANDOM TESTBENCH

............SystemVerilog Verification -- HOW TO CHECK THE RESULTS

............SystemVerilog Verification -- SELF CHECKING TESTBENCHS

............SystemVerilog Verification -- HOW TO GET SCENARIOS WHICH WE NEVER THOUGHT

............SystemVerilog Verification -- HOW TO CHECK WHETHER THE TESTBENCH HAS SATISFACTORILY EXERCISED THE DESIGN

............SystemVerilog Verification -- TYPES OF CODE COVERAGE

............SystemVerilog Verification -- STATEMENT COVERAGE

............SystemVerilog Verification -- BLOCK COVERAGE

............SystemVerilog Verification -- CONDITIONAL COVERAGE

............SystemVerilog Verification -- BRANCH COVERAGE

............SystemVerilog Verification -- PATH COVERAGE

............SystemVerilog Verification -- TOGGLE COVERAGE

............SystemVerilog Verification -- FSM COVERAGE


..................... State Coverage
..................... Transition Coverage

............SystemVerilog Verification -- MAKE YOUR GOAL 100 PERCENT CODE COVERAGE NOTHING LESS
..................... Dont Be Fooled By The Code Coverage Report
..................... When To Stop Testing?

............SystemVerilog Verification -- FUNCTIONAL COVERAGE


..................... Introduction To Functional Coverage

http://testbench.in/sitemap.html[9/26/2012 2:00:07 PM]


WWW.TESTBENCH.IN

..................... Item
..................... Cross
..................... Transitional
..................... Assertion Coverage

............SystemVerilog Verification -- COVERAGE DRIVEN CONSTRAINT RANDOM VERIFICATION ARCHITECTURE


..................... Verification Components Required For Cdcrv
..................... Stimulus
..................... Stimulus Generator
..................... Transactor
..................... Driver
..................... Monitor
..................... Assertion Based Monitor
..................... Data Checker
..................... Scoreboard
..................... Coverage
..................... Utilities
..................... Environment
..................... Tests

............SystemVerilog Verification -- PHASES OF VERIFICATION


..................... Verification Plan
..................... Building Testbench
..................... Writing Tests
..................... Integrating Code Coverage
..................... Analyze Coverage

............SystemVerilog Verification -- ONES COUNTER EXAMPLE


..................... Specification
..................... Test Plan
..................... Block Diagram
..................... Verification Environment Hierarchy
..................... Testbench Components
..................... Stimulus
..................... Driver
..................... Monitor
..................... Assertion Coverage
..................... Scoreboard
..................... Environment
..................... Top
..................... Tests

............SystemVerilog Verification -- VERIFICATION PLAN


..................... Verification Plan Contains The Following
..................... Overview
..................... Feature Extraction
..................... Resources, Budget And Schedule
..................... Verification Environment
..................... System Verilog Verification Flow
..................... Stimulus Generation Plan
..................... Checker Plan
..................... Coverage Plan
..................... Details Of Reusable Components

............SystemVerilog Constructs -- INTRODUCTION

............SystemVerilog Constructs -- DATA TYPES


..................... Signed And Unsigned
..................... Void

............SystemVerilog Constructs -- LITERALS


..................... Integer And Logic Literals
..................... Time Literals
..................... Array Literals
..................... Structure Literals

............SystemVerilog Constructs -- STRINGS


..................... String Methods
..................... String Pattren Match
..................... String Operators
..................... Equality
..................... Inequality.

http://testbench.in/sitemap.html[9/26/2012 2:00:07 PM]


WWW.TESTBENCH.IN

..................... Comparison.
..................... Concatenation.
..................... Replication.
..................... Indexing.

............SystemVerilog Constructs -- USERDEFINED DATATYPES

............SystemVerilog Constructs -- ENUMARATIONS


..................... Enumarated Methods
..................... Enum Numerical Expressions

............SystemVerilog Constructs -- STRUCTURES AND UNIOUNS


..................... Structure
..................... Assignments To Struct Members
..................... Union
..................... Packed Structures

............SystemVerilog Constructs -- TYPEDEF


..................... Advantages Of Using Typedef

............SystemVerilog Constructs -- ARRAYS


..................... Fixed Arrays
..................... Operations On Arrays
..................... Accessing Individual Elements Of Multidimensional Arrays

............SystemVerilog Constructs -- ARRAY METHODS


..................... Array Methods
..................... Array Querying Functions
..................... Array Locator Methods
..................... Array Ordering Methods
..................... Array Reduction Methods
..................... Iterator Index Querying

............SystemVerilog Constructs -- DYNAMIC ARRAYS


..................... Declaration Of Dynmic Array
..................... Allocating Elements
..................... Initializing Dynamic Arrays
..................... Resizing Dynamic Arrays
..................... Copying Elements

............SystemVerilog Constructs -- ASSOCIATIVE ARRAYS


..................... Associative Array Methods

............SystemVerilog Constructs -- QUEUES


..................... Queue Operators
..................... Queue Methods
..................... Dynamic Array Of Queues Queues Of Queues

............SystemVerilog Constructs -- COMPARISON OF ARRAYS


..................... Static Array
..................... Associative Array
..................... Dynamic Array
..................... Queues

............SystemVerilog Constructs -- LINKED LIST


..................... List Definitions
..................... Procedure To Create And Use List
..................... List_iterator Methods
..................... List Methods

............SystemVerilog Constructs -- CASTING


..................... Static Casting
..................... Dynamic Casting
..................... Cast Errors

............SystemVerilog Constructs -- DATA DECLARATION


..................... Scope And Lifetime
..................... Global
..................... Local
..................... Alias
..................... Data Types On Ports
..................... Parameterized Data Types
..................... Declaration And Initialization

http://testbench.in/sitemap.html[9/26/2012 2:00:07 PM]


WWW.TESTBENCH.IN

............SystemVerilog Constructs -- REG AND LOGIC

............SystemVerilog Constructs -- OPERATORS 1


..................... Operators In Systemverilog
..................... Assignment Operators
..................... Assignments In Expression
..................... Concatenation
..................... Arithmetic
..................... Relational
..................... Equality

............SystemVerilog Constructs -- OPERATORS 2


..................... Logical
..................... Bitwise
..................... Reduction
..................... Shift
..................... Increment And Decrement
..................... Set
..................... Streaming Operator
..................... Re-Ordering Of The Generic Stream
..................... Packing Using Streaming Operator
..................... Unpacking Using Streaming Operator
..................... Streaming Dynamically Sized Data

............SystemVerilog Constructs -- OPERATOR PRECEDENCY

............SystemVerilog Constructs -- EVENTS


..................... Triggered
..................... Wait()
..................... Race Condition
..................... Nonblocking Event Trigger
..................... Merging Events
..................... Null Events
..................... Wait Sequence
..................... Events Comparison

............SystemVerilog Constructs -- CONTROL STATEMENTS


..................... Sequential Control
..................... Enhanced For Loop
..................... Unique
..................... Priority

............SystemVerilog Constructs -- PROGRAM BLOCK

............SystemVerilog Constructs -- PROCEDURAL BLOCKS


..................... Final
..................... Jump Statements
..................... Event Control
..................... Always

............SystemVerilog Constructs -- FORK JOIN


..................... Fork Join None
..................... Fork Join Any
..................... For Join All

............SystemVerilog Constructs -- FORK CONTROL


..................... Wait Fork Statement
..................... Disable Fork Statement

............SystemVerilog Constructs -- SUBROUTINES


..................... Begin End
..................... Tasks
..................... Return In Tasks
..................... Functions
..................... Return Values And Void Functions:
..................... Pass By Reference
..................... Default Values To Arguments
..................... Argument Binding By Name
..................... Optional Argument List

............SystemVerilog Constructs -- SEMAPHORE

............SystemVerilog Constructs -- MAILBOX

http://testbench.in/sitemap.html[9/26/2012 2:00:07 PM]


WWW.TESTBENCH.IN

............SystemVerilog Constructs -- FINE GRAIN PROCESS CONTROL

............SystemVerilog Interface -- INTERFACE


..................... Advantages Of Using Inteface

............SystemVerilog Interface -- PORTS


..................... Interface Ports
..................... Modports
..................... Modport Selection Duing Module Definition.
..................... Modport Selection Duing Module Instance.

............SystemVerilog Interface -- INTERFACE METHODS


..................... Methods In Interfaces

............SystemVerilog Interface -- CLOCKING BLOCK


..................... Clocking Blocks
..................... Skew
..................... Cycle Delay

............SystemVerilog Interface -- VIRTUAL INTERFACE


..................... Virtual Interfaces
..................... Advantages Of Virtual Interface
..................... Multi Bus Interface

............SystemVerilog Interface -- SVTB N VERILOG DUT


..................... Working With Verilog Dut
..................... Connecting In Top
..................... Connecting Using A Wrapper

............SystemVerilog OOPS -- INTRODUCTION


..................... Brief Introduction To Oop
..................... Class
..................... Object
..................... Methods
..................... Inheritance
..................... Abstraction
..................... Encapsulation
..................... Polymorphism

............SystemVerilog OOPS -- CLASS


..................... Class Properties

............SystemVerilog OOPS -- OBJECT


..................... Creating Objects
..................... Declaration
..................... Instantiating A Class
..................... Initializing An Object
..................... Constructor

............SystemVerilog OOPS -- THIS


..................... Using The This Keyword

............SystemVerilog OOPS -- INHERITANCE


..................... What You Can Do In A Subclass
..................... Overriding
..................... Super
..................... Is Only Method
..................... Is First Method
..................... Is Also Method
..................... Overriding Constraints.
..................... Overriding Datamembers

............SystemVerilog OOPS -- ENCAPSULATION


..................... Access Specifiers

............SystemVerilog OOPS -- POLYMORPHISM

............SystemVerilog OOPS -- ABSTRACT CLASSES

http://testbench.in/sitemap.html[9/26/2012 2:00:07 PM]


WWW.TESTBENCH.IN

............SystemVerilog OOPS -- PARAMETERISED CLASS


..................... Type Parameterised Class
..................... Value Parameterised Class
..................... Generic Parameterised Class
..................... Extending Parameterised Class

............SystemVerilog OOPS -- NESTED CLASSES


..................... Why Use Nested Classes

............SystemVerilog OOPS -- CONSTANT


..................... Constant Class
..................... Global Constant
..................... Instance Constants

............SystemVerilog OOPS -- STATIC


..................... Static Class Properties
..................... Static Methods
..................... Static Lifetime Method.

............SystemVerilog OOPS -- CASTING

............SystemVerilog OOPS -- COPY


..................... Shallow Copy
..................... Deep Copy
..................... Clone

............SystemVerilog OOPS -- SCOPE RESOLUTION OPERATOR

............SystemVerilog OOPS -- NULL

............SystemVerilog OOPS -- EXTERNAL DECLARATION

............SystemVerilog OOPS -- CLASSES AND STRUCTURES

............SystemVerilog OOPS -- TYPEDEF CLASS


..................... Forward Reference
..................... Circular Dependency

............SystemVerilog OOPS -- PURE

............SystemVerilog OOPS -- OTHER OOPS FEATURES


..................... Multiple Inheritence
..................... Method Overloading

............SystemVerilog OOPS -- MISC


..................... Always Block In Classes

............SystemVerilog Randomization -- CONSTRAINED RANDOM VERIFICATION


..................... Introduction

............SystemVerilog Randomization -- VERILOG CRV


..................... Constrained Random Stimulus Generation In Verilog

............SystemVerilog Randomization -- SYSTEMVERILOG CRV


..................... Systemverilog Constraint Random Stmulus Generaion
..................... Random Number Generator System Functions
..................... $Urandom_range
..................... Scope Randomize Function
..................... Randomizing Objects
..................... Random Unpacked Structs
..................... Rand Case
..................... Rand Sequence

............SystemVerilog Randomization -- RANDOMIZING OBJECTS


..................... Generating Random Stimulus Within Class

............SystemVerilog Randomization -- RANDOM VARIABLES


..................... Random Varible Declaration
..................... Rand Modifier
..................... Randc Modifier

............SystemVerilog Randomization -- RANDOMIZATION METHODS

http://testbench.in/sitemap.html[9/26/2012 2:00:07 PM]


WWW.TESTBENCH.IN

..................... Randomization Built-In Methods


..................... Randomize()
..................... Pre_randomize And Post_randomize
..................... Disabling Random Variable
..................... Random Static Variable
..................... Randomizing Nonrand Varible

............SystemVerilog Randomization -- CHECKER

............SystemVerilog Randomization -- CONSTRAINT BLOCK


..................... Inheritance
..................... Overrighting Constraints

............SystemVerilog Randomization -- INLINE CONSTRAINT

............SystemVerilog Randomization -- GLOBAL CONSTRAINT

............SystemVerilog Randomization -- CONSTRAINT MODE


..................... Disabling Constraint Block

............SystemVerilog Randomization -- EXTERNAL CONSTRAINTS


..................... Constraint Hiding

............SystemVerilog Randomization -- RANDOMIZATION CONTROLABILITY


..................... Controlability

............SystemVerilog Randomization -- STATIC CONSTRAINT

............SystemVerilog Randomization -- CONSTRAINT EXPRESSION


..................... Set Membership
..................... Weighted Distribution
..................... Implication
..................... If..Else

............SystemVerilog Randomization -- VARIABLE ORDERING


..................... Functions
..................... Iterative Constraints

............SystemVerilog Randomization -- CONSTRAINT SOLVER SPEED

............SystemVerilog Randomization -- RANDCASE

............SystemVerilog Randomization -- RANDSEQUENCE


..................... Random Productions
..................... Random Production Weights
..................... If..Else
..................... Case
..................... Repeat Production Statements
..................... Rand Join
..................... Break
..................... Return
..................... Value Passing Between Productions

............SystemVerilog Randomization -- RANDOM STABILITY


..................... Srandom

............SystemVerilog Randomization -- ARRAY RANDOMIZATION

............SystemVerilog Randomization -- CONSTRAINT GUARDS

............SystemVerilog Randomization -- TITBITS


..................... Constraining Non Integral Data Types
..................... Saving Memory

............SystemVerilog Functional Coverage -- INTRODUCTION


..................... Systemverilog Functional Coverage Features

............SystemVerilog Functional Coverage -- COVER GROUP

............SystemVerilog Functional Coverage -- SAMPLE

............SystemVerilog Functional Coverage -- COVER POINTS

http://testbench.in/sitemap.html[9/26/2012 2:00:07 PM]


WWW.TESTBENCH.IN

..................... Commands To Simulate And Get The Coverage Report

............SystemVerilog Functional Coverage -- COVERPOINT EXPRESSION


..................... Coverpoint Expression
..................... Coverage Filter

............SystemVerilog Functional Coverage -- GENERIC COVERAGE GROUPS

............SystemVerilog Functional Coverage -- COVERAGE BINS


..................... Implicit Bins

............SystemVerilog Functional Coverage -- EXPLICIT BIN CREATION


..................... Array Of Bins
..................... Default Bin

............SystemVerilog Functional Coverage -- TRANSITION BINS


..................... Single Value Transition
..................... Sequence Of Transitions
..................... Set Of Transitions
..................... Consecutive Repetitions
..................... Range Of Repetition
..................... Goto Repetition
..................... Non Consecutive Repetition

............SystemVerilog Functional Coverage -- WILDCARD BINS

............SystemVerilog Functional Coverage -- IGNORE BINS

............SystemVerilog Functional Coverage -- ILLEGAL BINS

............SystemVerilog Functional Coverage -- CROSS COVERAGE


..................... User-Defined Cross Bins

............SystemVerilog Functional Coverage -- COVERAGE OPTIONS


..................... Weight
..................... Goal
..................... Name
..................... Comment
..................... At_least
..................... Detect_overlap
..................... Auto_bin_max
..................... Cross_num_print_missing
..................... Per_instance
..................... Get_inst_coverage

............SystemVerilog Functional Coverage -- COVERAGE METHODS

............SystemVerilog Functional Coverage -- SYSTEM TASKS

............SystemVerilog Functional Coverage -- COVER PROPERTY


..................... Cover Property Results
..................... Cover Sequence Results
..................... Comparison Of Cover Property And Cover Group.

............SystemVerilog Assertion -- INTRODUCTION


..................... Advantages Of Assertion
..................... What Assertions Can Verify

............SystemVerilog Assertion -- EVENT SIMULATION

............SystemVerilog Assertion -- ASSERTION TYPES

............SystemVerilog Assertion -- ASSERTION SYSTEM TASKS


..................... Assertion Control System Tasks
..................... Boolean System Function

............SystemVerilog Assertion -- CONCURRENT ASSERTION LAYERS


..................... Boolean Expressions

............SystemVerilog Assertion -- SEQUENCES


..................... Fixed Delay
..................... Zero Delay

http://testbench.in/sitemap.html[9/26/2012 2:00:07 PM]


WWW.TESTBENCH.IN

..................... Constant Range Delay


..................... Unbounded Delay Range
..................... Repetation Operators
..................... Consecutive Repetition
..................... Goto Repetition
..................... Nonconsecutive Repetition
..................... Sequence And
..................... Sequence Or
..................... Sequence Intersect
..................... Sequence Within
..................... Sequence First_match
..................... Sequence Throughout
..................... Sequence Ended
..................... Operator Precedence Associativy

............SystemVerilog Assertion -- PROPERTIES


..................... Overlap Implication
..................... Non Overlapping Implication

............SystemVerilog Assertion -- VERIFICATION DIRECTIVE


..................... Assert
..................... Assume
..................... Cover Statement
..................... Expect Statement
..................... Binding

............SystemVerilog DPI -- INTRODUCTIONS


..................... What Is Dpi-C ?

............SystemVerilog DPI -- LAYERS


..................... Two Layers Of Dpi-C
..................... Dpi-C Systemverilog Layer
..................... Dpi-C Foreign Language Layer

............SystemVerilog DPI -- IMPORT


..................... Import Methods
..................... Steps To Write Import Metyhods
..................... Standard C Functions

............SystemVerilog DPI -- NAMING


..................... Global Name
..................... Local Name
..................... Sv Keyword As Linkage Name

............SystemVerilog DPI -- EXPORT


..................... Export Methods
..................... Steps To Write Export Methods
..................... Blocking Export Dpi Task

............SystemVerilog DPI -- PURE AND CONTEXT


..................... Pure Function
..................... Context Function

............SystemVerilog DPI -- DATA TYPES


..................... Passing Logic Datatype

............SystemVerilog DPI -- ARRAYS


..................... Open Arrays
..................... Packed Arrays
..................... Linearized And Normalized
..................... Array Querying Functions

............SystemVerilog DPI -- PASSING STRUCTS AND UNIONS


..................... Passing Structure Example
..................... Passing Openarray Structs
..................... Passing Union Example

............SystemVerilog DPI -- ARGUMENTS TYPE


..................... What You Specify Is What You Get
..................... Pass By Ref
..................... Pass By Value
..................... Passing String

http://testbench.in/sitemap.html[9/26/2012 2:00:07 PM]


WWW.TESTBENCH.IN

..................... Example Passing String From Sv To C


..................... Example Passing String From C To Sv

............SystemVerilog DPI -- DISABLIE


..................... Disable Dpi-C Tasks And Functions
..................... Include Files

............SystemVerilog VMM Tutorial -- INTRODUCTION

............SystemVerilog VMM Tutorial -- VMM LOG


..................... Vmm Message Type
..................... Message Severity
..................... Vmm Log Macros
..................... Message Handling
..................... Counting Number Of Messages Based Of Message Severity

............SystemVerilog VMM Tutorial -- VMM ENV

............SystemVerilog VMM Tutorial -- VMM DATA


..................... Complete Packet Class
..................... Vmm_data Methods

............SystemVerilog VMM Tutorial -- VMM CHANNEL


..................... Complete Example
..................... Vmm Channel Methods.

............SystemVerilog VMM Tutorial -- VMM ATOMIC GENERATOR


..................... Completed Example

............SystemVerilog VMM Tutorial -- VMM XACTOR


..................... Complete Vmm_xactor Example
..................... Vmm_xactor Members

............SystemVerilog VMM Tutorial -- VMM CALLBACK


..................... Complete Source Code
..................... Testcase 1 Source Code
..................... Testcase 2 Source Code
..................... Testcase 3 Source Code
..................... Testcase 4 Source Code

............SystemVerilog VMM Tutorial -- VMM TEST


..................... Writing A Testcase
..................... Example Of Using Vmm_test

............SystemVerilog VMM Tutorial -- VMM CHANNEL RECORD AND PLAYBACK


..................... Recording
..................... Playing Back

............SystemVerilog VMM Tutorial -- VMM SCENARIO GENERATOR


..................... Example
..................... Scenario Code
..................... Testcase

............SystemVerilog VMM Tutorial -- VMM OPTS

............SystemVerilog UMM Tutorial -- INTRODUCTION


..................... Installing Uvm Library

............SystemVerilog UMM Tutorial -- UVM TESTBENCH


..................... Uvm_env
..................... Verification Components
..................... About Uvm_component Class
..................... Uvm_test
..................... Top Module

............SystemVerilog UMM Tutorial -- UVM REPORTING


..................... Reporting Methods
..................... Actions
..................... Configuration

http://testbench.in/sitemap.html[9/26/2012 2:00:07 PM]


WWW.TESTBENCH.IN

............SystemVerilog UMM Tutorial -- UVM TRANSACTION


..................... Core Utilities
..................... User Defined Implementations
..................... Shorthand Macros

............SystemVerilog UMM Tutorial -- UVM CONFIGURATION


..................... Set_config_* Methods
..................... Automatic Configuration
..................... Manual Configurations
..................... Configuration Setting Members

............SystemVerilog UMM Tutorial -- UVM FACTORY


..................... Registration
..................... Construction
..................... Overriding

............SystemVerilog UMM Tutorial -- UVM SEQUENCE 1


..................... Introduction
..................... Sequence And Driver Communication
..................... Simple Example
..................... Sequence Item
..................... Sequence
..................... Sequencer
..................... Driver
..................... Driver And Sequencer Connectivity
..................... Testcase

............SystemVerilog UMM Tutorial -- UVM SEQUENCE 2


..................... Pre Defined Sequences
..................... Sequence Action Macro
..................... Example Of Pre_do,Mid_do And Post_do
..................... List Of Sequence Action Macros
..................... Examples With Sequence Action Macros

............SystemVerilog UMM Tutorial -- UVM SEQUENCE 3


..................... Body Callbacks
..................... Hierarchical Sequences
..................... Sequential Sequences
..................... Parallel Sequences

............SystemVerilog UMM Tutorial -- UVM SEQUENCE 4


..................... Sequencer Arbitration
..................... Setting The Sequence Priority

............SystemVerilog UMM Tutorial -- UVM SEQUENCE 5


..................... Sequencer Registration Macros
..................... Setting Sequence Members

............SystemVerilog UMM Tutorial -- UVM SEQUENCE 6


..................... Exclusive Access
..................... Lock-Unlock
..................... Grab-Ungrab

............SystemVerilog UMM Tutorial -- UVM TLM 1


..................... Port Based Data Transfer
..................... Task Based Data Transfer
..................... Operation Supported By Tlm Interface
..................... Methods
..................... Tlm Terminology
..................... Tlm Interface Compilation Models
..................... Interfaces
..................... Direction
..................... All Interfaces In Uvm

............SystemVerilog UMM Tutorial -- UVM TLM 2


..................... Analysis
..................... Tlm Fifo
..................... Example

............SystemVerilog UMM Tutorial -- UVM CALLBACK


..................... Driver And Driver Callback Class Source Code
..................... Testcase Source Code
..................... Testcase 2 Source Code

http://testbench.in/sitemap.html[9/26/2012 2:00:07 PM]


WWW.TESTBENCH.IN

..................... Testcase 3 Source Code


..................... Testcase 4 Source Code
..................... Methods
..................... Macros

............SystemVerilog OVM Tutorial -- INTRODUCTION

............SystemVerilog OVM Tutorial -- OVM TESTBENCH


..................... Ovm_env
..................... Verification Components
..................... About Ovm_component Class
..................... Ovm_test
..................... Top Module

............SystemVerilog OVM Tutorial -- OVM REPORTING


..................... Reporting Methods
..................... Actions
..................... Configuration

............SystemVerilog OVM Tutorial -- OVM TRANSACTION


..................... Core Utilities
..................... User Defined Implementations
..................... Shorthand Macros

............SystemVerilog OVM Tutorial -- OVM FACTORY


..................... Registration
..................... Construction
..................... Overriding

............SystemVerilog OVM Tutorial -- OVM SEQUENCE 1


..................... Introduction
..................... Sequence And Driver Communication
..................... Simple Example
..................... Sequence Item
..................... Sequence
..................... Sequencer
..................... Driver
..................... Driver And Sequencer Connectivity
..................... Testcase

............SystemVerilog OVM Tutorial -- OVM SEQUENCE 2


..................... Pre Defined Sequences
..................... Sequence Action Macro
..................... Example Of Pre_do,Mid_do And Post_do
..................... List Of Sequence Action Macros
..................... Examples With Sequence Action Macros

............SystemVerilog OVM Tutorial -- OVM SEQUENCE 3


..................... Body Callbacks
..................... Hierarchical Sequences
..................... Sequential Sequences
..................... Parallel Sequences

............SystemVerilog OVM Tutorial -- OVM SEQUENCE 4


..................... Sequencer Arbitration
..................... Setting The Sequence Priority

............SystemVerilog OVM Tutorial -- OVM SEQUENCE 5


..................... Sequencer Registration Macros
..................... Setting Sequence Members

............SystemVerilog OVM Tutorial -- OVM SEQUENCE 6


..................... Exclusive Access
..................... Lock-Unlock
..................... Grab-Ungrab

............SystemVerilog OVM Tutorial -- OVM CONFIGURATION


..................... Set_config_* Methods
..................... Automatic Configuration
..................... Manual Configurations
..................... Configuration Setting Members

http://testbench.in/sitemap.html[9/26/2012 2:00:07 PM]


WWW.TESTBENCH.IN

............SystemVerilog Easy Labs - SV -- INTRODUCTION

............SystemVerilog Easy Labs - SV -- SPECIFICATION


..................... Switch Specification
..................... Packet Format
..................... Packet Header
..................... Configuration
..................... Interface Specification
..................... Memory Interface
..................... Input Port
..................... Output Port

............SystemVerilog Easy Labs - SV -- VERIFICATION PLAN


..................... Overview
..................... Feature Extraction
..................... Stimulus Generation Plan
..................... Coverage Plan
..................... Verification Environment

............SystemVerilog Easy Labs - SV -- PHASE 1 TOP


..................... Interfaces
..................... Testcase
..................... Top Module
..................... Top Module Source Code

............SystemVerilog Easy Labs - SV -- PHASE 2 ENVIRONMENT


..................... Environment Class
..................... Run
..................... Environment Class Source Code

............SystemVerilog Easy Labs - SV -- PHASE 3 RESET

............SystemVerilog Easy Labs - SV -- PHASE 4 PACKET


..................... Packet Class Source Code
..................... Program Block Source Code

............SystemVerilog Easy Labs - SV -- PHASE 5 DRIVER


..................... Driver Class Source Code
..................... Environment Class Source Code

............SystemVerilog Easy Labs - SV -- PHASE 6 RECEIVER


..................... Receiver Class Source Code
..................... Environment Class Source Code

............SystemVerilog Easy Labs - SV -- PHASE 7 SCOREBOARD


..................... Scoreboard Class Source Code
..................... Source Code Of The Environment Class

............SystemVerilog Easy Labs - SV -- PHASE 8 COVERAGE


..................... Source Code Of Coverage Class
..................... Source Code Of The Scoreboard Class

............SystemVerilog Easy Labs - SV -- PHASE 9 TESTCASE


..................... Source Code Of Constraint Testcase

............SystemVerilog Easy Labs - OVM -- INTRODUCTION

............SystemVerilog Easy Labs - OVM -- SPECIFICATION


..................... Switch Specification
..................... Packet Format
..................... Configuration
..................... Interface Specification

............SystemVerilog Easy Labs - OVM -- VERIFICATION PLAN


..................... Overview
..................... Feature Extraction
..................... Stimulus Generation Plan
..................... Verification Environment

http://testbench.in/sitemap.html[9/26/2012 2:00:07 PM]


WWW.TESTBENCH.IN

............SystemVerilog Easy Labs - OVM -- PHASE 1 TOP


..................... Interface
..................... Top Module

............SystemVerilog Easy Labs - OVM -- PHASE 2 CONFIGURATION


..................... Configuration
..................... Updates To Top Module

............SystemVerilog Easy Labs - OVM -- PHASE 3 ENVIRONMENT N TESTCASE


..................... Environment
..................... Testcase

............SystemVerilog Easy Labs - OVM -- PHASE 4 PACKET


..................... Packet
..................... Test The Transaction Implementation

............SystemVerilog Easy Labs - OVM -- PHASE 5 SEQUENCER N SEQUENCE


..................... Sequencer
..................... Sequence

............SystemVerilog Easy Labs - OVM -- PHASE 6 DRIVER


..................... Driver
..................... Environment Updates
..................... Testcase Updates

............SystemVerilog Easy Labs - OVM -- PHASE 7 RECEIVER


..................... Receiver
..................... Environment Class Updates

............SystemVerilog Easy Labs - OVM -- PHASE 8 SCOREBOARD


..................... Scoreboard
..................... Environment Class Updates

............SystemVerilog Easy Labs - UVM -- INTRODUCTION


..................... Installing Uvm Library

............SystemVerilog Easy Labs - UVM -- SPECIFICATION


..................... Switch Specification
..................... Packet Format
..................... Configuration
..................... Interface Specification

............SystemVerilog Easy Labs - UVM -- VERIFICATION PLAN


..................... Overview
..................... Feature Extraction
..................... Stimulus Generation Plan
..................... Verification Environment

............SystemVerilog Easy Labs - UVM -- PHASE 1 TOP


..................... Interface
..................... Top Module

............SystemVerilog Easy Labs - UVM -- PHASE 2 CONFIGURATION


..................... Configuration
..................... Updates To Top Module

............SystemVerilog Easy Labs - UVM -- PHASE 3 ENVIRONMENT N TESTCASE


..................... Environment
..................... Testcase

............SystemVerilog Easy Labs - UVM -- PHASE 4 PACKET


..................... Packet
..................... Test The Transaction Implementation

............SystemVerilog Easy Labs - UVM -- PHASE 5 SEQUENCER N SEQUENCE


..................... Sequencer
..................... Sequence

............SystemVerilog Easy Labs - UVM -- PHASE 6 DRIVER


..................... Driver
..................... Environment Updates
..................... Testcase Updates

http://testbench.in/sitemap.html[9/26/2012 2:00:07 PM]


WWW.TESTBENCH.IN

............SystemVerilog Easy Labs - UVM -- PHASE 7 RECEIVER


..................... Receiver
..................... Environment Class Updates

............SystemVerilog Easy Labs - UVM -- PHASE 8 SCOREBOARD


..................... Scoreboard
..................... Environment Class Updates

............SystemVerilog Easy Labs - VMM -- INTRODUCTION

............SystemVerilog Easy Labs - VMM -- SPECIFICATION


..................... Switch Specification
..................... Packet Format
..................... Configuration
..................... Interface Specification

............SystemVerilog Easy Labs - VMM -- VERIFICATION PLAN


..................... Overview
..................... Feature Extraction
..................... Stimulus Generation Plan
..................... Coverage Plan
..................... Verification Environment

............SystemVerilog Easy Labs - VMM -- PHASE 1 TOP


..................... Interfaces
..................... Testcase
..................... Top Module
..................... Top Module Source Code

............SystemVerilog Easy Labs - VMM -- PHASE 2 ENVIRONMENT


..................... Environment Class
..................... Run
..................... Environment Class Source Code

............SystemVerilog Easy Labs - VMM -- PHASE 3 RESET

............SystemVerilog Easy Labs - VMM -- PHASE 4 PACKET


..................... Packet Class Source Code
..................... Program Block Source Code

............SystemVerilog Easy Labs - VMM -- PHASE 5 GENERATOR


..................... Environment Class Source Code

............SystemVerilog Easy Labs - VMM -- PHASE 6 DRIVER


..................... Driver Class Source Code
..................... Environment Class Source Code

............SystemVerilog Easy Labs - VMM -- PHASE 7 RECEIVER


..................... Receiver Class Source Code
..................... Environment Class Source Code

............SystemVerilog Easy Labs - VMM -- PHASE 8 SCOREBOARD


..................... Scoreboard Class Source Code
..................... Source Code Of The Environment Class

............SystemVerilog Easy Labs - VMM -- PHASE 9 COVERAGE


..................... Source Code Of Coverage Class

............SystemVerilog AVM Switch TB -- AVM INTRODUCTION


..................... Tlm
..................... Building Blocks
..................... Avm_transactors
..................... Avm_env
..................... Avm_messaging

............SystemVerilog AVM Switch TB -- DUT SPECIFICATION


..................... Configuration
..................... Interface Specification

http://testbench.in/sitemap.html[9/26/2012 2:00:07 PM]


WWW.TESTBENCH.IN

..................... Memory Interface


..................... Input Interface
..................... Output Interface

............SystemVerilog AVM Switch TB -- RTL

............SystemVerilog AVM Switch TB -- TOP


..................... Verilog Top

............SystemVerilog AVM Switch TB -- INTERFACE

............SystemVerilog AVM Switch TB -- ENVIRONMENT

............SystemVerilog AVM Switch TB -- PACKET

............SystemVerilog AVM Switch TB -- PACKET GENERATOR

............SystemVerilog AVM Switch TB -- CONFIGURATION

............SystemVerilog AVM Switch TB -- DRIVER

............SystemVerilog AVM Switch TB -- RECIEVER

............SystemVerilog AVM Switch TB -- SCOREBOARD

............Verilog Verification -- INTRODUCTION


..................... Test Bench Overview

............Verilog Verification -- LINEAR TB


..................... Linear Testbench

............Verilog Verification -- FILE IO TB


..................... File I/O Based Testbench

............Verilog Verification -- STATE MACHINE BASED TB

............Verilog Verification -- TASK BASED TB


..................... Task And Function Based Tb

............Verilog Verification -- SELF CHECKING TESTBENCH


..................... Stimulus Generator
..................... Bus Functional Models
..................... Driver
..................... Reciver
..................... Protocol Monitor
..................... Scoreboard
..................... Checker
..................... Coverage
..................... Code Coverage
..................... Functional Coverage

............Verilog Verification -- VERIFICATION FLOW


..................... Planning
..................... Feature Extraction
..................... Verification Environment Architecture Plan

............Verilog Verification -- CLOCK GENERATOR


..................... Timescale And Precision Enlightment

............Verilog Verification -- SIMULATION


..................... Simulation Steps
..................... Macro Preprocessing
..................... Compilation (Analyzer)
..................... Elaboration
..................... Optimization
..................... Initialization
..................... Execution
..................... Simulation Process

............Verilog Verification -- INCREMENTAL COMPILATION

............Verilog Verification -- STORE AND RESTORE

http://testbench.in/sitemap.html[9/26/2012 2:00:07 PM]


WWW.TESTBENCH.IN

............Verilog Verification -- EVENT CYCLE SIMULATION


..................... Event Based Simulation
..................... Cycle Based Simulation

............Verilog Verification -- TIME SCALE AND PRECISION


..................... Time Scale And Time Precision
..................... $Time Vs $Realtime
..................... System Task Printtimescale
..................... System Task Timeformat

............Verilog Verification -- STIMULUS GENERATION

............Verilog Verification -- SYSTEM FUNCTION RANDOM A MYTH

............Verilog Verification -- RACE CONDITION


..................... What Is Race Condition?
..................... Why Race Condition?
..................... When Race Is Visible?
..................... How To Prevent Race Condition?
..................... Types Of Race Condition
..................... Write-Write Race
..................... Read-Write Race
..................... More Race Example
..................... Event Terminology
..................... The Stratified Event Queue
..................... Determinism
..................... Nondeterminism
..................... Guideline To Avoid Race Condition
..................... Avoid Race Between Testbench And Dut

............Verilog Verification -- CHECKER


..................... Protocol Checker
..................... Data_checker
..................... Modularization

............Verilog Verification -- TASK AND FUNCTION


..................... Functions
..................... Task
..................... Task And Function Queries
..................... Constant Function
..................... Reentrant Tasks And Functions

............Verilog Verification -- PROCESS CONTROL


..................... Nonblocking Task
..................... Fork/Join Recap
..................... Fork/Join None
..................... Fork/Join Any

............Verilog Verification -- DISABLEING THE BLOCK


..................... Disable
..................... Goto
..................... Break
..................... Continue

............Verilog Verification -- WATCHDOG

............Verilog Verification -- COMPILATION N SIMULATION SWITCHS


..................... Compilation And Simulation Directives
..................... Example

............Verilog Verification -- DEBUGGING


..................... Pass Or Fail
..................... Waveform Viewer
..................... Log File
..................... Message Control System
..................... Message Severity Levels
..................... Message Controlling Levels
..................... Passing Comments To Waveform Debugger
..................... $Display N $Strobe
..................... Who Should Do The Rtl Debugging?

............Verilog Verification -- ABOUT CODE COVERAGE


..................... Types Of Coverage

http://testbench.in/sitemap.html[9/26/2012 2:00:07 PM]


WWW.TESTBENCH.IN

..................... Code Coverage


..................... Statement Coverage /Line Coverage
..................... Block/Segment Coverage
..................... Branch / Decision / Conditional Coverage
..................... Path Coverage
..................... Expression Coverage
..................... Toggle Coverage
..................... Variable Coverage
..................... Triggering / Event Coverage
..................... Parameter Coverage
..................... Functional Coverage
..................... Fsm Coverage
..................... State Coverage
..................... Transition Coverage
..................... Sequence Coverage
..................... Tool Support
..................... Limitation Of Code Coverage

............Verilog Verification -- TESTING STRATIGIES


..................... Bottom-Up
..................... Unit Level
..................... Sub-Asic Level
..................... Asic Level
..................... System Level
..................... Flat

............Verilog Verification -- FILE HANDLING


..................... Fopen And Fclose
..................... Fdisplay
..................... Fmonitor
..................... Fwrite
..................... Mcd
..................... Formating Data To String

............Verilog Verification -- VERILOG SEMAPHORE


..................... Semaphore In Verilog

............Verilog Verification -- FINDING TESTSENARIOUS


..................... Register Tests
..................... System Tests
..................... Interrupt Tests
..................... Interface Tests
..................... Functional Tests
..................... Error Tests
..................... Golden Tests
..................... Performance Tests

............Verilog Verification -- HANDLING TESTCASE FILES

............Verilog Verification -- TERIMINATION

............Verilog Verification -- ERROR INJUCTION


..................... Value Errors
..................... Temporal Errors
..................... Interface Error
..................... Sequence Errors

............Verilog Verification -- REGISTER VERIFICATION


..................... Register Verification
..................... Register Classification
..................... Features

............Verilog Verification -- PARAMETERISED MACROS

............Verilog Verification -- WHITE GRAY BLACK BOX


..................... Black Box Verification
..................... White Box Verification
..................... Gray Box Verification

............Verilog Verification -- REGRESSION

............Verilog Verification -- TIPS


..................... How To Avoid "Module Xxx Already Defined" Error
..................... Colourful Messages

http://testbench.in/sitemap.html[9/26/2012 2:00:07 PM]


WWW.TESTBENCH.IN

..................... Debugging Macros

............Verilog Switch TB -- DUT SPECIFICATION


..................... Configuration
..................... Interface Specification
..................... Memory Interface
..................... Input Interface
..................... Output Interface

............Verilog Switch TB -- RTL

............Verilog Switch TB -- TOP


..................... Verification Environment
..................... Top Module

............Verilog Switch TB -- PACKET

............Verilog Switch TB -- DRIVER

............Verilog Switch TB -- RECIEVER

............Verilog Switch TB -- SCOREBOARD

............Verilog Switch TB -- ENV

............Verilog Basic Constructs -- INTRODUCTION


..................... Introduction

............Verilog Basic Constructs -- SYNTAX

............Verilog Basic Constructs -- DATA TYPES


..................... Value Set
..................... Net
..................... Variable Or Reg
..................... Vectors
..................... Memories
..................... Net Types

............Verilog Basic Constructs -- OPERATORS


..................... Binary Arithmetic Operators
..................... Unary Arithmetic Operators
..................... Relational Operators
..................... Logical Operators
..................... Bitwise Operators
..................... Unary Reduction Operators
..................... Other Operators
..................... Operator Precedence

............Verilog Basic Constructs -- ASSIGNMENTS


..................... Blocking Procedural Assignments
..................... The Nonblocking Procedural Assignment
..................... Procedural Continuous Assignments
..................... Assign And Deassign Procedural Statements
..................... Force And Release Procedural Statements
..................... Delays
..................... Inter Assignmnet Delay .
..................... Intra-Assignment Delay Control

............Verilog Basic Constructs -- CONTROL CONSTRUCTS


..................... If And If Else Statements
..................... Case
..................... Forever
..................... Repeat
..................... While
..................... For

............Verilog Basic Constructs -- PROCEDURAL TIMING CONTROLS


..................... Delay Control
..................... Event Control

http://testbench.in/sitemap.html[9/26/2012 2:00:07 PM]


WWW.TESTBENCH.IN

..................... Named Events

............Verilog Basic Constructs -- STRUCTURE


..................... Module
..................... Ports
..................... Signals

............Verilog Basic Constructs -- BLOCK STATEMENTS


..................... Sequential Blocks
..................... Parallel Blocks

............Verilog Basic Constructs -- STRUCTURED PROCEDURES


..................... Initial
..................... Always
..................... Functions
..................... Task

............Vera Constructs -- INTRODUCTION


..................... Introduction
..................... Comments In Openvera
..................... Numbers In Openvera

............Vera Constructs -- DATA TYPES


..................... Basic Data Types
..................... Integer
..................... Register
..................... String
..................... Event
..................... Enumerated Types
..................... Virtual Ports
..................... Arrays
..................... Fixed-Size Arrays
..................... Dynamic Arrays
..................... Associative Arrays
..................... Smart Queues
..................... Class

............Vera Constructs -- LINKED LIST


..................... Linked List
..................... List Methods

............Vera Constructs -- OPERATORS PART 1


..................... Operators
..................... Concatenation
..................... Arithmetic
..................... Relational
..................... Equality

............Vera Constructs -- OPERATORS PART 2


..................... Logical
..................... Bitwise
..................... Reduction

............Vera Constructs -- OPERATORS PART 3


..................... Shift
..................... Bit-Reverse
..................... Increment And Decrement
..................... Conditional
..................... Set
..................... Replication

............Vera Constructs -- OPERATOR PRECEDENCE


..................... Operator Precedence

............Vera Constructs -- CONTROL STATEMENTS


..................... Sequential Statements

............Vera Constructs -- PROCEDURES AND METHODS


..................... Procedures And Methods
..................... Pass By Value
..................... Pass By Reference
..................... Default Arguments

http://testbench.in/sitemap.html[9/26/2012 2:00:07 PM]


WWW.TESTBENCH.IN

..................... Optional Arguments

............Vera Constructs -- INTERPROCESS


..................... Interprocess Synchronization And Communication

............Vera Constructs -- FORK JOIN


..................... Fork Join

............Vera Constructs -- SHADOW VARIABLES


..................... Shadow Variables

............Vera Constructs -- FORK JOIN CONTROL


..................... Fork And Join Control
..................... Wait_chiled()
..................... Terminate
..................... Suspend_thread

............Vera Constructs -- WAIT VAR


..................... Wait_var

............Vera Constructs -- EVENT SYNC


..................... Event Methods

............Vera Constructs -- EVENT TRIGGER


..................... Event Trigger
..................... Event Variables

............Vera Constructs -- SEMAPHORE


..................... Semaphore

............Vera Constructs -- REGIONS


..................... Regions

............Vera Constructs -- MAILBOX


..................... Mailbox

............Vera Constructs -- TIMEOUTS


..................... Timeouts

............Vera Constructs -- OOP


..................... Object Oriented Programming
..................... Properties
..................... This
..................... Class Extensions
..................... Polymorphism
..................... Super
..................... Abstract Class

............Vera Constructs -- CASTING

............Vera Constructs -- RANDOMIZATION


..................... Constrained Random Verification
..................... Random Varible Declaration
..................... Rand Modifier
..................... Randc Modifier

............Vera Constructs -- RANDOMIZATION METHODS


..................... Randomization Built-In Methods
..................... Randomize()
..................... Pre_randomize And Post_randomize

............Vera Constructs -- CONSTRAINT BLOCK


..................... Constraint Block
..................... Inline Constraints
..................... Disabling Constraint Block

............Vera Constructs -- CONSTRAINT EXPRESSION


..................... Constraint Expressions
..................... Set Membership
..................... Weighted Distribution
..................... Implication
..................... If..Else
..................... Iterative

http://testbench.in/sitemap.html[9/26/2012 2:00:07 PM]


WWW.TESTBENCH.IN

............Vera Constructs -- VARIABLE ORDARING


..................... Variable Ordaring

............Vera Constructs -- AOP


..................... Aspect Oriented Extensions

............Vera Constructs -- PREDEFINED METHODS


..................... Predefined Methods
..................... New()
..................... Finalize()
..................... Object_print
..................... Deep Object Compare
..................... Deep Object Copy
..................... Pack And Unpack

............Vera Constructs -- STRING METHODS

............Vera Constructs -- QUEUE METHODS

............Vera Constructs -- DUT COMMUNICATION


..................... Connecting To Hdl
..................... Interface Declaration
..................... Direct Hdl Node Connection
..................... Blocking And Non-Blocking Drives

............Vera Constructs -- FUNCTIONAL COVERAGE


..................... Functional Coverage
..................... Coverage Group
..................... Sample_event
..................... Coverage_point
..................... Cross Coverage

............Vera Switch TB -- DUT SPECIFICATION


..................... Configuration
..................... Interface Specification
..................... Memory Interface
..................... Input Interface
..................... Output Interface

............Vera Switch TB -- RTL

............Vera Switch TB -- TOP


..................... Verification Environment
..................... Top Module

............Vera Switch TB -- INTERFACE

............Vera Switch TB -- PACKET

............Vera Switch TB -- PACKET GENERATOR

............Vera Switch TB -- CFG DRIVER

............Vera Switch TB -- DRIVER

............Vera Switch TB -- RECIEVER

............Vera Switch TB -- SCOREBOARD

............Vera Switch TB -- ENV

............Vera RVM Switch TB -- INTRODUCTION


..................... Dut Specification
..................... Configuration
..................... Interface Specification
..................... Memory Interface
..................... Input Interface
..................... Output Interface

http://testbench.in/sitemap.html[9/26/2012 2:00:07 PM]


WWW.TESTBENCH.IN

............Vera RVM Switch TB -- RTL

............Vera RVM Switch TB -- TOP

............Vera RVM Switch TB -- INTERFACE

............Vera RVM Switch TB -- PROGRAM BLOCK


..................... Testbench Program

............Vera RVM Switch TB -- ENVIRONMENT

............Vera RVM Switch TB -- PACKET

............Vera RVM Switch TB -- CONFIGURATION

............Vera RVM Switch TB -- DRIVER

............Vera RVM Switch TB -- RECIEVER

............Vera RVM Switch TB -- SCOREBOARD

............Specman E -- INTRODUCTION

............Specman E -- E BASICS
..................... Code Segments
..................... Comments
..................... Literals And Constants
..................... Sized Numbers
..................... Predeï¬Ned Constants

............Specman E -- DATA TYPES


..................... Enumerated Types

............Specman E -- OPERATORS
..................... Unary Bitwise Operators
..................... Binary Bitwise Operations
..................... Shift Operators
..................... Boolean Operators
..................... Arithmetic Operators
..................... Comparison Operators
..................... Extraction And Concatenation Operators
..................... Special-Purpose Operators

............Specman E -- STRUCT

............Specman E -- UNITS
..................... Units Vs Structs

............Specman E -- LIST
..................... Regular List
..................... List Operations
..................... Keyed List

............Specman E -- METHODS
..................... Time-Consuming Methods(Tcms)
..................... Invoking Tcms
..................... Execution Flow

............Specman E -- Concurrency Actions


..................... All Of
..................... First Of

............Specman E -- CONSTRAINTS

............Specman E -- EXTEND
..................... Is Also
..................... Is First
..................... Is Only

............Specman E -- When and Like


..................... Like
..................... When

http://testbench.in/sitemap.html[9/26/2012 2:00:07 PM]


WWW.TESTBENCH.IN

............Specman E -- EVENTS

............Specman E -- TEMPORAL EXPRESSIONS


..................... Basic Temporal Expressions
..................... Temporal Checking

............Specman E -- Temporal operators 1


..................... Not
..................... Fail
..................... And
..................... Or
..................... { Exp ; Exp }
..................... Eventually
..................... [ Exp ]
..................... [ Exp..Exp ]
..................... ~[ Exp..Exp ]
..................... Temporal Yield Operator

............Specman E -- TEMPORAL OPERATORS 2


..................... Detach
..................... Delay
..................... @ Unary Event Operator
..................... @ Sampling Operator
..................... Cycle
..................... True(Exp)
..................... Change(Exp), Fall(Exp), Rise(Exp)
..................... Consume
..................... Exec

............Specman E -- SYNCHRONIZING WITH THE SIMULATOR

............Specman E -- WAIT AND SYNC


..................... Wait Action
..................... Sync Action
..................... Difference Between Wait And Sync

............Specman E -- PHYSICAL VIRUAL FEILDS


..................... Physical Fields
..................... Ungenerated Fields

............Specman E -- PACKING N UNPACKING


..................... Packing.High
..................... Packing.Low

............Specman E -- PRE RUN N ON THE FLY


..................... Pre-Run Generation
..................... On-The-Fly Generation

............Specman E -- COVERAGE
..................... Coverage Groups
..................... Cover Group Options
..................... Cross-Coverage

............Specman E -- COMMANDS

............Specman E -- Extendable Methods

............Specman E -- Non Extendable Methods

............Specman E -- AND GATE EVC

............Interview Questions -- FUNCTIONAL VERIFICATION QUESTIONS

............Interview Questions -- FUNCTIONAL VERIFICATION QUESTIONS 2

............Interview Questions -- TEST YOUR SYSTEMVERILOG SKILLS 1

............Interview Questions -- TEST YOUR SYSTEMVERILOG SKILLS 2

............Interview Questions -- TEST YOUR SYSTEMVERILOG SKILLS 3

http://testbench.in/sitemap.html[9/26/2012 2:00:07 PM]


WWW.TESTBENCH.IN

............Interview Questions -- TEST YOUR SYSTEMVERILOG SKILLS 4

............Interview Questions -- TEST YOUR SVA SKILLS

............Interview Questions -- TEST YOUR VERILOG SKILLS 1

............Interview Questions -- TEST YOUR VERILOG SKILLS 2

............Interview Questions -- TEST YOUR VERILOG SKILLS 3

............Interview Questions -- TEST YOUR VERILOG SKILLS 4

............Interview Questions -- TEST YOUR VERILOG SKILLS 5

............Interview Questions -- TEST YOUR VERILOG SKILLS 6

............Interview Questions -- TEST YOUR VERILOG SKILLS 7

............Interview Questions -- TEST YOUR VERILOG SKILLS 8

............Interview Questions -- TEST YOUR VERILOG SKILLS 9

............Interview Questions -- TEST YOUR VERILOG SKILLS 10

............Interview Questions -- TEST YOUR VERILOG SKILLS 11

............Interview Questions -- TEST YOUR VERILOG SKILLS 12

............Interview Questions -- TEST YOUR VERILOG SKILLS 13

............Interview Questions -- TEST YOUR VERILOG SKILLS 14

............Interview Questions -- TEST YOUR VERILOG SKILLS 15

............Interview Questions -- TEST YOUR VERILOG SKILLS 16

............Interview Questions -- TEST YOUR VERILOG SKILLS 17

............Interview Questions -- TEST YOUR SPECMAN SKILLS 1

............Interview Questions -- TEST YOUR SPECMAN SKILLS 2

............Interview Questions -- TEST YOUR SPECMAN SKILLS 3

............Interview Questions -- TEST YOUR SPECMAN SKILLS 4

............Interview Questions -- TEST YOUR STA SKILLS 1

............Interview Questions -- TEST YOUR STA SKILLS 2

............Interview Questions -- TEST YOUR STA SKILLS 3

............Interview Questions -- TEST YOUR STA SKILLS 4

............Interview Questions -- TEST YOUR STA SKILLS 5

............Interview Questions -- TEST YOUR STA SKILLS 6

............Interview Questions -- TEST YOUR STA SKILLS 7

............Interview Questions -- TEST YOUR DFT SKILLS 1

............Interview Questions -- TEST YOUR DFT SKILLS 2

............Interview Questions -- TEST YOUR DFT SKILLS 3

............Interview Questions -- TEST YOUR DFT SKILLS 4

VMM Ethernet sample


RVM Ethernet sample
Phychology of Verification Engineer

http://testbench.in/sitemap.html[9/26/2012 2:00:07 PM]


WWW.TESTBENCH.IN

Report a Bug or Comment on This section - Your input is what keeps Testbench.in improving with time!

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/sitemap.html[9/26/2012 2:00:07 PM]


WWW.TESTBENCH.IN

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS Recommended Links


SystemVerilog
Verification
Constructs
Interface
Asic With Ankit
OOPS
Randomization www.systemverilog.ru : First Russian site about SystemVerilog
Functional Coverage www.systemverilog.in : One stop solution for SV with active forum
Assertion Subash Nayak's The Ultimate Hitchhiker's Guide to SV-VMM
DPI
Free Systemverilog Verification IPs @ www.syswip.com
UVM Tutorial
VMM Tutorial vlsi-verification.blogspot.com
OVM Tutorial ChipDesign
Easy Labs : SV
Digital-IC-Design
Easy Labs : UVM
Fpga4Fun
Easy Labs : OVM
Easy Labs : VMM Digitalelectronis Blog
AVM Switch TB Asic.co.in
VMM Ethernet sample
Srinivasan Venkataramanan CVC blog
Puneet's asicguru.com
Verilog
Verification Asic-World
Verilog Switch TB Dipesh Chauhan's Blog
Basic Constructs

SV methodologies
OpenVera
Constructs VMM
Switch TB AVM
RVM Switch TB Truss & Teal
RVM Ethernet sample
OVM

Specman E If you wanna see your blog/site in the above list, Please submit the details in below form
Interview Questions
Send Details about your site.

* Required

Your name

http://testbench.in/links.html[9/26/2012 2:00:17 PM]


WWW.TESTBENCH.IN

Your Email ID *

Your Site link *

Description *

Submit

Powered by Google Docs

Report Abuse - Terms of Service - Additional Terms

copyright © 2007 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/links.html[9/26/2012 2:00:17 PM]


WWW.TESTBENCH.IN

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS

SystemVerilog What People are saying about my Site!


Verification
Constructs
Interface Here are a few comments people have sent me :
OOPS
Randomization
Functional Coverage Excellent Work. Awesome compilation of examples based tutorials. Innovative
approach to every aspect of Website. This website really helps engineers to have
Assertion great insight into real verification issues.
DPI Appreciate the good work in maintaining and updating the site very very well.
UVM Tutorial - Mr.Paul Kaunds, Chairman and CEO, Kacper Technologies Pvt. Ltd.
VMM Tutorial
OVM Tutorial This is very good site to a starter even for experienced people too.I have
Easy Labs : SV implemented and developed whole environment for my project taking your site as
reference. Now we are in good position . Keep rocking .
Easy Labs : UVM
Easy Labs : OVM - Mallikharjuna ,GDA Technologies Inc
Easy Labs : VMM
AVM Switch TB Your Site is Simply Superb !!! . You have proved " Example is not the way it is the only
VMM Ethernet sample way to teach ". By Understanding & Practicing SV, VMM examples in your site, I learnt
many topics.
I referred many of my colleagues to "testbench.in" site
Verilog - Prashanth Sunke , Transwitch India Pvt. Ltd.
Verification
Verilog Switch TB
Great work Guys. Superb compilation of tutorial and examples. Great in-depth
Basic Constructs knowledge of System verilog and VMM.

- Rizwan , Sr. Verification Engineer , Network Programs, Japan.


OpenVera
Constructs
TestBench.in provides a quick fetcher information which facilates easy learning
Switch TB capabilities with real time examples. Gopi and his team has initiated a very good pre-
dominatory approach to fetch valuable information in a single stretch of a click..
RVM Switch TB
Keep this noble work going.
RVM Ethernet sample
- Pavan.K.Shanbhag , AXIOM EDA Products.

Specman E
Amazing effort. Very useful material.
Interview Questions
- Lakshman , MindTree

I find this website a valuable resource for the beginners to have a good jumpstart. I
would fully recommend this website to someone who wants to get a good starting
point in verification. The Website is good in texts,its explanations and illustrative
examples.
Good job ..Keep it up

- Vipul , Design Verification lead ,Sanmedi Technologies Inc

http://testbench.in/What_people_are_saying_about_my_site.html[9/26/2012 2:00:24 PM]


WWW.TESTBENCH.IN

It is really a wonderful stuff to swallow as Verification Engineer. I am really impressed


by each and every stuff in the site.

- Nirav Bhatt , Sibridge Technologies, Ahmedabad, India

Your tutorial on SV test bench is really great.

- Emma , TI

Really very good site. Appreciate your continuous effort to show/share verification
world through your experience, indepth analysis with simple example.

- Pandithurai Sangaiyah, Technical Leader (ASIC Verification) at ST Microelectronics.

You did a good job. This tutorial give a quick start for VMM and is easy to handle.

- Hansjoerg Berberich ,Renesas

It was a very helpful tutorial. Excellent material.

- Vishnu ,Mirafra Techonologies

You can only feel like a Verification Engineer after visiting this site.

- Barindra Ghosh,Verification Engineer,Wipro Technologies.

You have done a great job in your site www.testbench.in. Your materials are very
good.

- Himanshu , WhizChip Design Technologies

You are maintaining a awesome site testbench.in with lots of useful material with
good example.

- Puneet, Author of http://www.asicguru.com

Besides, I would like to thank the development team for the great efforts made to
produce this wonderful site with detailed explanation, enabling us to learn and master
the hot in the market verificaton methodologies.

- Arun

Your site is very Useful in learning the important concepts in that. I would like to
appreciate your contribution for that.

- Rajiv Bhatia , sasken

I am learning system verilog and have experience in VHDL/Verilog.


I went through your website and find it extremely helpful. It is neatly organized

- Sudhir Shivanna Saligrama , Mindtree

This website is very informative and you guys have put a lot of effort in building
this...Keep up the good work and good luck.

http://testbench.in/What_people_are_saying_about_my_site.html[9/26/2012 2:00:24 PM]


WWW.TESTBENCH.IN

- Santhosh , Mindspeed

Actually past two day I used your documents .


It give me great pleasure to learning interest because of the Step by step process with
clear detail

- Nesan , Flowgicindia

My heartfelt congratulations for creating such a wonderful site with loads of useful
and quickly understandable information for professionals and beginners in the Chip
Verification domain.

- Ravi Kalyan , GDA techonologies

I have been following your website testbech.in for some time, it has good resources.
One think I like about it is that it continues evolve, maintained well and is up to date.
Great work.

- Mallikarjun Chillal, PhD , Infinera

I just found your site and was very impressed with the depth of testbench topics that
you covered.

- Donna Mitchell , VP Marketing , SynaptiCAD

This is amazing, wonderful!what else. Yes, it is a great start to putting things


together and helping others.

- Karthikeyan Subramaniyam , synopsys

Just wanted to congratulate you on your website. I have been a verification engineer
for 8 years and have never found a site as useful as this one.

- Richard Metzger , Firmware QA Engineer , Covidien Energy-based Devices (EbD)

Very good site you made , the site is very well organized and very informative.
Thanks for providing so much information on System verilog and other topics you
included.

- AnilKumar.M , Author of www.asic.co.in

This is definitely a great site.


Keep up the good work and I have referred this to my colleagues.

- Shankar , Freescale

copyright © 2007 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/What_people_are_saying_about_my_site.html[9/26/2012 2:00:24 PM]


WWW.TESTBENCH.IN

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS

SystemVerilog What is on Testbench.in


Verification
Constructs
Interface Systemverilog Tutorials
OOPS
SystemVerilog tutorial is divided in to following sub sections.

Randomization Systemverilog for Verification


Functional Coverage Discusses verification methodology starting from Linear testbenchs to
Constraint random coverage driven verification.
Assertion Systemverilog Constructs
DPI This section covers the SystemVerilog data types and constructs with lots of
examples and simulated results to analyze deeply.
UVM Tutorial Systemverilog Interfaces
VMM Tutorial This section covers SystemVerilog Interfaces , how they are used to build your
testbench and connect it to the design under test
OVM Tutorial
Systemverilog Object oriented programming
Easy Labs : SV In this section, Object oriented programming techniques are discussed.
Easy Labs : UVM
Systemverilog Constraint randomization
This section walks you through the Systemverilog constrained randomization
Easy Labs : OVM with more than 160 examples and many more to come.
Easy Labs : VMM Systemverilog Functional Coverage
This section explains the different types of coverages with examples with
AVM Switch TB their coverage reports.
VMM Ethernet sample Systemverilog Assertions
This section introducess SystemVerilog assertions.
Systemverilog DPI
This section walks you through the Systemverilog direct programming
Verilog interface with self explanatory examples.
Verification
Verilog Switch TB VMM Tutorial & UVM Tutorial & OVM Tutorial
These are unique UVM/VMM/OVM tutorial where each topic is explained using
Basic Constructs individual ready to run examples. User can tweak the example and explore more
indeep about the topic.

OpenVera Openvera
Constructs This section covers the basics of Openvera with lots of examples and simulated results
to analyze deeply.
Switch TB
RVM Switch TB Verilog For Verification
Newbies in the world of verification are missing a place where they can learn
RVM Ethernet sample verification theory along with practical examples. All the examples are discussed in
Verilog. Most of them are applicable to other languages also.

Specman E Know by example


"Example isn't another way to teach, it is the only way to teach" -- Albert Einstein
Interview Questions This section helps you to understand the verification environment with example. It
covers most of the language features. These examples are explained in Verilog,
Systemverilog and Openvera.

Easy Labs
These labs takes you through the complete cycle of a simple switch
verification. These lab starts with creating test plan and ends with achieving
coverage goal. These labs are divided in to multiple phases and each phase
has a lab files which can be download. Unlike other labs, where user can only
simulates the environment after developing the complete environment, In

http://testbench.in/What_is_on_Testbench.html[9/26/2012 2:00:41 PM]


WWW.TESTBENCH.IN

these labs, in every phase, user can simulate the environment and analyze the
implementation of that phase .

Easy Labs: SystemVerilog


Easy Labs: UVM
Easy Labs: OVM
Easy Labs: VMM

Simple Labs
These Labs are very simple and dry. User can download the labs and simulate
them.

AVM Switch example


OpenVera Switch example
RVM Switch example
Verilog Switch example

Articles submitted by readers


This section is for the articles submitted by testbench.in Readers.

Interview Questions
You can find Interview questions on Verification concepts, Verilog, Systemverilog,
SVA, Specman, STA and DFT.

copyright © 2007 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/What_is_on_Testbench.html[9/26/2012 2:00:41 PM]


WWW.TESTBENCH.IN

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS

SystemVerilog We don't make any claims, promises or guarantees about the accuracy, completeness, or adequacy of the contents
Verification of this website.

Constructs All the source code and tutorials are to be used on your own risk.
Interface
All trademarks are property of their respective owners.
OOPS
Randomization The content on this site is our own and not relates ,in any way, to organizations we work for.
Functional Coverage
Assertion
DPI
UVM Tutorial
VMM Tutorial
OVM Tutorial
Easy Labs : SV
Easy Labs : UVM
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

Verilog
Verification
Verilog Switch TB
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

copyright © 2007 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/disclaimer.html[9/26/2012 2:01:03 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INTRODUCTION Index


Introduction
SystemVerilog SystemVerilog is a combined Hardware Description Language and Hardware Data Types
Verification Verification Language based on extensions to Verilog. SystemVerilog was created by Literals
the donation of the Superlog language to Accellera in 2002. The bulk of the Strings
Constructs verification functionality is based on the OpenVera language donated by Synopsys. In Userdefined Datatypes
Interface 2005, SystemVerilog was adopted as IEEE Standard 1800-2005 . Enumarations
Structures And Uniouns
OOPS Typedef
Few of SystemVerilog's capabilities are unique, but it is significant that these
Randomization capabilities are combined and offered within a single HDL. There is great value in a Arrays
common HDL which handles all aspects of the design and verification flow: design Array Methods
Functional Coverage Dynamic Arrays
description, functional simulation, property specification, and formal verification.
Assertion Associative Arrays
Queues
DPI Comparison Of Arrays
UVM Tutorial Linked List
Casting
VMM Tutorial Data Declaration
OVM Tutorial Reg And Logic
Operators 1
Easy Labs : SV
Operators 2
Easy Labs : UVM Operator Precedency
Events
Easy Labs : OVM
Control Statements
Easy Labs : VMM Program Block
AVM Switch TB Procedural Blocks
Fork Join
VMM Ethernet sample Fork Control
Subroutines
Semaphore
Verilog Mailbox
Fine Grain Process
Verification
Control
Verilog Switch TB
Basic Constructs Report a Bug or Comment
on This section - Your
input is what keeps
Testbench.in improving
OpenVera with time!
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/SV_01_INTRODUCTION.html[9/26/2012 2:01:12 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SV_01_INTRODUCTION.html[9/26/2012 2:01:12 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS DATA TYPES Index


Introduction
SystemVerilog Data Types
Verification Literals
SystemVerilog adds extended and new data types to Verilog for better encapsulation Strings
Constructs and compactness.  SystemVerilog extends Verilog by introducing C like data Userdefined Datatypes
Interface types.  SystemVerilog adds a new 2-state data types that can only have bits with 0 or Enumarations
1 values unlike verilog 4-state data types which can have 0, 1, X and Z.   Structures And Uniouns
OOPS Typedef
SystemVerilog also allows user to define new data types.  
Randomization Arrays
Array Methods
Functional Coverage
SystemVerilog offers several data types, representing a hybrid of both Verilog and C Dynamic Arrays
Assertion data types. SystemVerilog 2-state data types can simulate faster, take less memory, Associative Arrays
DPI and are preferred in some design styles. Then a 4-state value is automatically Queues
converted to a 2-state value, X and Z will be converted to zeros. Comparison Of Arrays
UVM Tutorial Linked List
Casting
VMM Tutorial Data Declaration
OVM Tutorial Reg And Logic
Operators 1
Easy Labs : SV
Operators 2
Easy Labs : UVM Operator Precedency
Events
Easy Labs : OVM
Control Statements
Easy Labs : VMM Program Block
AVM Switch TB Procedural Blocks
Fork Join
VMM Ethernet sample Fork Control
Subroutines
Semaphore
Verilog Mailbox
Fine Grain Process
Verification
Control
Verilog Switch TB
Basic Constructs Report a Bug or Comment
on This section - Your
input is what keeps
Testbench.in improving
OpenVera with time!
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions TIP : If you don't need the x and z values then use the SystemVerilog int and bit types
which make execution faster.

Signed And Unsigned :

Integer types use integer arithmetic and can be signed or unsigned.The data types
byte, shortint, int, integer, and longint default to signed. The data types bit, reg, and
logic default to unsigned, as do arrays of these types.

To use these types as unsigned, user has to explicitly declare it as unsigned.

http://testbench.in/SV_02_DATA_TYPES.html[9/26/2012 2:01:21 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

    int unsigned ui;
    int signed si
    byte unsigned ubyte;

User can cast using signed and unsigned casting.

    if (signed'(ubyte)< 150) // ubyte is unsigned

Void :

 The void data type represents nonexistent data. This type can be specified as the
return type of functions to indicate no return value.

    void = function_call();

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SV_02_DATA_TYPES.html[9/26/2012 2:01:21 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS LITERALS Index


Introduction
SystemVerilog Integer And Logic Literals Data Types
Verification Literals
In verilog , to assign a value to all the bits of vector, user has to specify them Strings
Constructs explicitly. Userdefined Datatypes
Interface Enumarations
    reg[31:0] a = 32'hffffffff; Structures And Uniouns
OOPS Typedef
Randomization Systemverilog Adds the ability to specify unsized literal single bit values with a Arrays
preceding (').'0, '1, 'X, 'x, 'Z, 'z // sets all bits to this value. Array Methods
Functional Coverage Dynamic Arrays
Assertion     reg[31:0] a = '1;   Associative Arrays
Queues
DPI Comparison Of Arrays
'x is equivalent to Verilog-2001 'bx
UVM Tutorial 'z is equivalent to Verilog-2001 'bz Linked List
'1 is equivalent to making an assignment of all 1's Casting
VMM Tutorial Data Declaration
'0 is equivalent to making an assignment of 0
OVM Tutorial Reg And Logic
Time Literals Operators 1
Easy Labs : SV
Operators 2
Easy Labs : UVM Time is written in integer or fixed-point format, followed without a space by a time Operator Precedency
unit (fs ps ns us ms s step). Events
Easy Labs : OVM
Control Statements
Easy Labs : VMM EXAMPLE Program Block
AVM Switch TB   0.1ns Procedural Blocks
  40ps Fork Join
VMM Ethernet sample Fork Control
The time literal is interpreted as a realtime value scaled to the current time unit and Subroutines
rounded to the current time precision. Semaphore
Verilog Mailbox
Fine Grain Process
Verification
Array Literals Control
Verilog Switch TB
Basic Constructs Array literals are syntactically similar to C initializers, but with the replicate operator Report a Bug or Comment
( {{}} ) allowed. on This section - Your
input is what keeps
EXAMPLE Testbench.in improving
OpenVera int n[1:2][1:3] = '{'{0,1,2},'{3{4}}}; with time!
Constructs
Switch TB The nesting of braces must follow the number of dimensions, unlike in C. However,
replicate operators can be nested. The inner pair of braces in a replication is
RVM Switch TB removed. A replication expression only operates within one dimension.
RVM Ethernet sample
EXAMPLE:
int n[1:2][1:6] = '{2{'{3{4, 5}}}}; // same as '{'{4,5,4,5,4,5},'{4,5,4,5,4,5}}
Specman E Structure Literals
Interview Questions
 Structure literals are structure assignment patterns or pattern expressions with
constant member expressions A structure literal must have a type, which may be
either explicitly indicated with a prefix or implicitly indicated by an assignment-like
context.

EXAMPLE
    typedef struct {int a; shortreal b;} ab;
    ab c;
    c = '{0, 0.0}; // structure literal type determined from
                   // the left-hand context (c)

http://testbench.in/SV_03_LITERALS.html[9/26/2012 2:01:29 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

    

Nested braces should reflect the structure. 


EXAMPLE
    ab abarr[1:0] = '{'{1, 1.0}, '{2, 2.0}};

The C-like alternative '{1, 1.0, 2, 2.0} for the preceding example is not allowed.

EXAMPLE: default values


    c = '{a:0, b:0.0}; 
    c = '{default:0}; 
    d = ab'{int:1, shortreal:1.0}; 

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SV_03_LITERALS.html[9/26/2012 2:01:29 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS STRINGS Index


Introduction
SystemVerilog Data Types
Verification In Verilog, string literals are packed arrays of a width that is a multiple of 8 bits Literals
which hold ASCII values. In Verilog, if a string is larger than the destination string Strings
Constructs variable, the string is truncated to the left, and the leftmost characters will be Userdefined Datatypes
Interface lost.  SystemVerilog adds new keyword "string" which is used to declare string data Enumarations
types unlike verilog. String data types can be of arbitrary length and no truncation Structures And Uniouns
OOPS Typedef
occurs.
Randomization Arrays
string myName = "TEST BENCH"; Array Methods
Functional Coverage Dynamic Arrays
Assertion String Methods : Associative Arrays
Queues
DPI Comparison Of Arrays
SystemVerilog also includes a number of special methods to work with strings. These
UVM Tutorial methods use the built-in method notation. These methods are: Linked List
1.      str.len() returns the length of the string, i.e., the number of characters in the Casting
VMM Tutorial Data Declaration
string.
OVM Tutorial 2.      str.putc(i, c) replaces the ith character in str with the given integral value. Reg And Logic
3.      str.getc(i) returns the ASCII code of the ith character in str. Operators 1
Easy Labs : SV
4.      str.toupper() returns a string with characters in str converted to uppercase. Operators 2
Easy Labs : UVM 5.      str.tolower() returns a string with characters in str converted to lowercase. Operator Precedency
6.      str.compare(s) compares str and s, and return value. This comparison is case Events
Easy Labs : OVM
sensitive. Control Statements
Easy Labs : VMM 7.      str.icompare(s) compares str and s, and return value  .This comparison is case Program Block
AVM Switch TB insensitive. Procedural Blocks
8.      str.substr(i, j) returns a new string that is a substring formed by index i through Fork Join
VMM Ethernet sample j of str. Fork Control
9.      str.atoi() returns the integer corresponding to the ASCII decimal representation Subroutines
in str. Semaphore
Verilog 10.     str.atoreal() returns the real number corresponding to the ASCII decimal Mailbox
representation in str. Fine Grain Process
Verification
11.     str.itoa(i) stores the ASCII decimal representation of i into str (inverse of atoi). Control
Verilog Switch TB 12.     str.hextoa(i) stores the ASCII hexadecimal representation of i into str (inverse of
Basic Constructs atohex). Report a Bug or Comment
13.     str.bintoa(i) stores the ASCII binary representation of i into str (inverse of on This section - Your
atobin). input is what keeps
14.     str.realtoa(r) stores the ASCII real representation of r into str (inverse of Testbench.in improving
OpenVera atoreal) with time!
Constructs
Switch TB
RVM Switch TB EXAMPLE : String methods
RVM Ethernet sample     module str;
         string A;
         string B;
         initial
Specman E          begin
Interview Questions              A = "TEST ";
             B = "Bench";
             $display(" %d ",A.len() );
             $display(" %s ",A.getc(5) );
             $display(" %s ",A.tolower);
             $display(" %s ",B.toupper);
             $display(" %d ",B.compare(A) );
             $display(" %d ",A.compare("test") );
             $display(" %s ",A.substr(2,3) ); A = "111";
             $display(" %d ",A.atoi() );
         end

http://testbench.in/SV_04_STRINGS.html[9/26/2012 2:01:38 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

    endmodule

RESULTS :

           5

 test
 BENCH
         -18
         -32
 ST
         111

String Pattren Match

Use the following method for pattern matching in SystemVerilog. Match method which
is in OpenVera or C , is not available in SystemVerilog . For using match method which
is in C , use the DPI calls . For native SystemVerilog string match method, hear is the
example.  

CODE:
   function match(string s1,s2);
       int l1,l2;
       l1 = s1.len();
       l2 = s2.len();
       match = 0 ;
       if( l2 > l1 )
           return 0;
       for(int i = 0;i < l1 - l2 + 1; i ++)
           if( s1.substr(i,i+l2 -1) == s2)
               return 1;
   endfunction

EXAMPLE:
    program main;
    
    string str1,str2;
    int i;
    
    
    initial
    begin
        str1 = "this is first string";
        str2 = "this";
        if(match(str1,str2))
            $display(" str2 : %s : found in :%s:",str2,str1);

        str1 = "this is first string";


        str2 = "first";
        if(match(str1,str2))
            $display(" str2 : %s : found in :%s:",str2,str1);

        str1 = "this is first string";


        str2 = "string";
        if(match(str1,str2))
            $display(" str2 : %s : found in :%s:",str2,str1);

http://testbench.in/SV_04_STRINGS.html[9/26/2012 2:01:38 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

        str1 = "this is first string";


        str2 = "this is ";
        if(match(str1,str2))
            $display(" str2 : %s : found in :%s:",str2,str1);

        str1 = "this is first string";


        str2 = "first string";
        if(match(str1,str2))
            $display(" str2 : %s : found in :%s:",str2,str1);

        str1 = "this is first string";


        str2 = "first string ";// one space at end
        if(match(str1,str2))
            $display(" str2 : %s : found in :%s:",str2,str1);
        
    end
    
    endprogram

RESULTS:

str2 : this : found in :this is first string:


str2 : first : found in :this is first string:
str2 : string : found in :this is first string:
str2 : this is : found in :this is first string:
str2 : first string : found in :this is first string:

String Operators

SystemVerilog provides a set of operators that can be used to manipulate


combinations of string variables and string literals. The basic operators defined on the
string data type are

Equality

Syntax : Str1 == Str2

Checks whether the two strings are equal. Result is 1 if they are equal and 0 if they
are not. Both strings can be of type string. Or one of them can be a string literal. If
both operands are string literals, the operator is the same Verilog equality operator as
for integer types.

EXAMPLE
   program main;
      initial
      begin
          string str1,str2,str3;
          str1 = "TEST BENCH";
          str2 = "TEST BENCH";
          str3 = "test bench";
          if(str1 == str2)
              $display(" Str1 and str2 are equal");
          else
              $display(" Str1 and str2 are not equal");
          if(str1 == str3)
              $display(" Str1 and str3 are equal");
          else
              $display(" Str1 and str3 are not equal");
          
      end
   endprogram

RESULT

Str1 and str2 are equal


Str1 and str3 are not equal

http://testbench.in/SV_04_STRINGS.html[9/26/2012 2:01:38 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

Inequality.

Syntax: Str1 != Str2

Logical negation of Equality operator.  Result is 0 if they are equal and 1 if they are
not. Both strings can be of type string. Or one of them can be a string literal. If both
operands are string literals, the operator is the same Verilog equality operator as for
integer types.

EXAMPLE
   program main;
      initial
      begin
         string str1,str2,str3;
         str1 = "TEST BENCH";
         str2 = "TEST BENCH";
         str3 = "test bench";
         if(str1 != str2)
             $display(" Str1 and str2 are not equal");
         else
             $display(" Str1 and str2 are equal");
         if(str1 != str3)
             $display(" Str1 and str3 are not equal");
         else
             $display(" Str1 and str3 are equal");
        
      end
   endprogram
RESULT

 Str1 and str2 are equal


 Str1 and str3 are not equal

Comparison.

Syntax: 
Str1 < Str2
Str1 <= Str2
Str1 > Str2
Str1 >= Str2

Relational operators return 1 if the corresponding condition is true using the


lexicographical ordering of the two strings Str1 and Str2. The comparison uses the
compare string method. Both operands can be of type string, or one of them can be a
string literal.

EXAMPLE
   program main;
      initial
      begin
          string Str1,Str2,Str3;
          Str1 = "c";
          Str2 = "d";
          Str3 = "e";
          
          if(Str1 < Str2)
              $display(" Str1 < Str2 ");
          if(Str1 <= Str2)
              $display(" Str1 <= Str2 ");
          if(Str3 > Str2)
              $display(" Str3 > Str2");
          if(Str3 >= Str2)
              $display(" Str3 >= Str2");
      end
   endprogram

RESULT

 Str1 < Str2


 Str1 <= Str2
 Str3 > Str2

http://testbench.in/SV_04_STRINGS.html[9/26/2012 2:01:38 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

 Str3 >= Str2

Concatenation.
Syntax: {Str1,Str2,...,Strn} 

Each operand can be of type string or a string literal (it shall be implicitly converted
to type string). If at least one operand is of type string, then the expression evaluates
to the concatenated string and is of type string. If all the operands are string literals,
then the expression behaves like a Verilog concatenation of integral types; if the
result is then used in an expression involving string types, it is implicitly converted to
the string type.

EXAMPLE
   program main;
       initial
       begin
           string Str1,Str2,Str3,Str4,Str5;
           Str1 = "WWW.";
           Str2 = "TEST";
           Str3 = "";
           Str4 = "BENCH";
           Str5 = ".IN";
           $display(" %s ",{Str1,Str2,Str3,Str4,Str5});
       end
   endprogram

RESULT

 WWW.TESTBENCH.IN

Replication.

Syntax : {multiplier{Str}} 

Str can be of type string or a string literal. Multiplier must be of integral type and can
be nonconstant. If multiplier is nonconstant or Str is of type string, the result is a
string containing N concatenated copies of Str, where N is specified by the multiplier.
If Str is a literal and the multiplier is constant, the expression behaves like numeric
replication in Verilog (if the result is used in another expression involving string types,
it is implicitly converted to the string type).

EXAMPLE
    program main;
        initial
        begin
            string Str1,Str2;
            Str1 = "W";
            Str2 = ".TESTBENCH.IN";
            $display(" %s ",{{3{Str1}},Str2});
        end
    endprogram

RESULT

 WWW.TESTBENCH.IN

Indexing.
Syntax: Str[index] 

Returns a byte, the ASCII code at the given index. Indexes range from 0 to N-1, where
N is the number of characters in the string. If given an index out of range, returns 0.
Semantically equivalent to Str.getc(index)

EXAMPLE
    program main;
       initial
       begin
          string Str1;
          Str1 = "WWW.TESTBENCH.IN";
          for(int i =0 ;i < 16 ; i++)
             $write("%s ",Str1[i]);

http://testbench.in/SV_04_STRINGS.html[9/26/2012 2:01:38 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

       end
    endprogram

RESULT

WWW.TESTBENCH.IN

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SV_04_STRINGS.html[9/26/2012 2:01:38 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS USERDEFINED DATATYPES Index


Introduction
SystemVerilog Data Types
Verification Systemverilog allos the user to define datatypes. There are different ways to define Literals
user defined datatypes. They are Strings
Constructs 1.      Class. Userdefined Datatypes
Interface 2.      Enumarations. Enumarations
3.      Struct. Structures And Uniouns
OOPS Typedef
4.      Union.
Randomization 5.      Typedef. Arrays
Array Methods
Functional Coverage Dynamic Arrays
Assertion Associative Arrays
Queues
DPI Comparison Of Arrays
UVM Tutorial Linked List
Casting
VMM Tutorial Data Declaration
OVM Tutorial Reg And Logic
Operators 1
Easy Labs : SV
Operators 2
Easy Labs : UVM Operator Precedency
Events
Easy Labs : OVM
Control Statements
Easy Labs : VMM Program Block
AVM Switch TB Procedural Blocks
Fork Join
VMM Ethernet sample Fork Control
Subroutines
Semaphore
Verilog Mailbox
Fine Grain Process
Verification
Control
Verilog Switch TB
Basic Constructs Report a Bug or Comment
on This section - Your
input is what keeps
Testbench.in improving
OpenVera with time!
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/SV_05_USERDEFINED_DATATYPES.html[9/26/2012 2:01:47 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SV_05_USERDEFINED_DATATYPES.html[9/26/2012 2:01:47 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS ENUMARATIONS Index


Introduction
SystemVerilog Data Types
Verification You'll sometimes be faced with the need for variables that have a limited set of Literals
possible values that can be usally referred to by name.  For example, the state Strings
Constructs variable like IDLE,READY,BUZY etx of state machine can only have the all the states Userdefined Datatypes
Interface defined and Refraining or  displaying  these states using the state name will be more Enumarations
comfortable. There's a specific facility, called an enumeration in SystemVerilog . Structures And Uniouns
OOPS Typedef
Enumerated data types assign a symbolic name to each legal value taken by the data
Randomization type.  Let's create an example using one of the ideas I just mentioned-a state Arrays
machine . Array Methods
Functional Coverage Dynamic Arrays
Assertion You can define this as follows: Associative Arrays
Queues
DPI Comparison Of Arrays
     enum {IDLE,READY,BUZY} states;
UVM Tutorial Linked List
This declares an enumerated data type called states, and variables of this type can Casting
VMM Tutorial Data Declaration
only have values from the set that appears between the braces, IDLE,READY and
OVM Tutorial BUZY. If you try to set a variable of type states to a value that isn't one of the values Reg And Logic
specified, it will cause an error. Enumerated data type are strongly typed. Operators 1
Easy Labs : SV
Operators 2
Easy Labs : UVM One more advantage of enumerated datatypes  is that if you don't initialize then , Operator Precedency
each one would have a unique value. By defaule they are int types.  In the previous Events
Easy Labs : OVM
examples, IDLE is 0, READY is 1 and BUZY is 2. These values can be printed as values Control Statements
Easy Labs : VMM or strings. Program Block
AVM Switch TB The values can be set for some of the names and not set for other names. A name Procedural Blocks
without a value is automatically assigned an increment of the value of the previous Fork Join
VMM Ethernet sample name. The value of first name  by default is 0. Fork Control
Subroutines
Semaphore
Verilog      // c is automatically assigned the increment-value of 8 Mailbox
     enum {a=3, b=7, c} alphabet; Fine Grain Process
Verification
     Control
Verilog Switch TB      // Syntax error: c and d are both assigned 8
Basic Constructs      enum {a=0, b=7, c, d=8} alphabet; Report a Bug or Comment
     on This section - Your
     // a=0, b=7, c=8 input is what keeps
     enum {a, b=7, c} alphabet; Testbench.in improving
OpenVera with time!
Constructs Enumarated Methods:
Switch TB
RVM Switch TB SystemVerilog includes a set of specialized methods to enable iterating over the
RVM Ethernet sample values of enumerated.

The first() method returns the value of the first member of the enumeration.
Specman E The last() method returns the value of the last member of the enumeration.
Interview Questions
The next() method returns the Nth next enumeration value (default is the next one)
starting from the current value of the given variable.

The prev() method returns the Nth previous enumeration value (default is the
previous one) starting from the current value of the given variable.

The name() method returns the string representation of the given enumeration value.
If the given value is not a member of the enumeration, the name() method returns the
empty string.

http://testbench.in/SV_06_ENUMARATIONS.html[9/26/2012 2:01:54 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

EXAMPLE : ENUM methods


    module enum_method;
       typedef enum {red,blue,green} colour;
       colour c;
       initial
       begin
          c = c.first();
          $display(" %s ",c.name);
          c = c.next();
          $display(" %s ",c.name);
          c = c.last();
          $display(" %s ",c.name);
          c = c.prev();
          $display(" %s ",c.name);
       end
    endmodule

RESULTS :

 red
 blue
 green
 blue

Enum Numerical Expressions

Elements of enumerated type variables can be used in numerical expressions. The


value used in the expression is the numerical value associated with the enumerated
value.

An enum variable or identifier used as part of an expression is automatically cast to


the base type of the enum declaration (either explicitly or using int as the default). A
cast shall be required for an expression that is assigned to an enum variable where
the type of the expression is not equivalent to the enumeration type of the variable.

EXAMPLE:
    module enum_method;
    typedef enum {red,blue,green} colour;
    colour c,d;
    int i;
        initial
        begin
            $display("%s",c.name());
            d = c;
            $display("%s",d.name());
            d = colour'(c + 1); // use casting
            $display("%s",d.name());
            i = d; // automatic casting
            $display("%0d",i);
            c = colour'(i);
            $display("%s",c.name());
        end
    endmodule
RESULT

http://testbench.in/SV_06_ENUMARATIONS.html[9/26/2012 2:01:54 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

red
red
blue
1
blue

TIP: If you want to use X or Z as enum values, then define it using 4-state data type
explicitly.

     enum integer {IDLE, XX='x, S1='b01, S2='b10} state, next;

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SV_06_ENUMARATIONS.html[9/26/2012 2:01:54 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS STRUCTURES AND UNIOUNS Index


Introduction
SystemVerilog Structure: Data Types
Verification Literals
The disadvantage of arrays is that all the elements stored in then are to be of the Strings
Constructs same data type. If we need to use a collection of different data types, it is not Userdefined Datatypes
Interface possible using an array. When we require using a collection of different data items of Enumarations
different data types we can use a structure.  Structure is a method of packing data of Structures And Uniouns
OOPS Typedef
different types. A structure is a convenient method of handling a group of related
Randomization data items of different data types. Arrays
Array Methods
Functional Coverage Dynamic Arrays
struct  {
Assertion    int a; Associative Arrays
   byte b; Queues
DPI Comparison Of Arrays
   bit [7:0] c;
UVM Tutorial } my_data_struct;  Linked List
Casting
VMM Tutorial Data Declaration
The keyword "struct" declares a structure to holds the details of four fields namely a,b
OVM Tutorial and c. These are members of the structures. Each member may belong to different or Reg And Logic
same data type. The structured variables can be accessed using the variable name Operators 1
Easy Labs : SV
"my_data_struct". Operators 2
Easy Labs : UVM Operator Precedency
    my_data_struct.a = 123; Events
Easy Labs : OVM
    $display(" a value is %d ",my_data_struct.a); Control Statements
Easy Labs : VMM Program Block
AVM Switch TB Procedural Blocks
Assignments To Struct Members: Fork Join
VMM Ethernet sample Fork Control
A structure  literal must have a type, which may be either explicitly indicated with a Subroutines
prefix or implicitly indicated by an  assignment-like context. Semaphore
Verilog Mailbox
    my_data_struct = `{1234,8'b10,8'h20}; Fine Grain Process
Verification
Control
Verilog Switch TB Structure literals can also use member name and value, or data type and default
Basic Constructs value. Report a Bug or Comment
on This section - Your
    my_data_struct = `{a:1234,default:8'h20}; input is what keeps
Testbench.in improving
OpenVera Union with time!
Constructs
Switch TB Unions like structure contain members whose individual data types may differ from
one another. However the members that compose a union all share the same storage
RVM Switch TB area.  A union allows us to treat the same space in memory as a number of different
RVM Ethernet sample variables. That is a Union offers a way for a section of memory to be treated as a
variable of one type on one occasion and as a different variable of a different type on
another occasion.
Specman E union  {
Interview Questions    int a;
   byte b;
   bit [7:0] c;
} my_data; 

memory allocation for the above defined struct "my_data_struct".

http://testbench.in/SV_07_STRUCTURES_AND_UNIOUNS.html[9/26/2012 2:02:03 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

Memory allocation for the above defined union "my_data_union".

Packed Structures:

In verilog , it is not convenient for subdividing a vector into subfield. Accessing


subfield requires the index ranges.

For example

    reg [0:47] my_data;
    `define  a_indx 16:47
    `define b_indx 8:15
    `define c_indx 0:7
    
     my_data[`b_indx] = 8'b10; // writing to subfield b
     $display(" %d ",my_data[`a_indx]); // reading subfield a

A packed structure is a mechanism for subdividing a vector into subfields that can be
conveniently accessed as members. Consequently, a packed structure consists of bit
fields, which are packed together in memory without gaps.  A packed struct or union
type must be declared explicitly using keyword "packed".

    struct packed {
       integer a;
       byte b;
       bit [0:7] c;
    } my_data; 
    
    my_data.b =  8'b10; 
    $display("%d", my_data.a);
    

Memory allocation for the above defined packed struct "my_data".

One or more bits of a packed structure can be selected as if it were a packed array,
assuming an [n-1:0] numbering:

My_data [15:8] // b

http://testbench.in/SV_07_STRUCTURES_AND_UNIOUNS.html[9/26/2012 2:02:03 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

If all members of packed structure are 2-state, the structure as a whole is treated as
a 2-state vector.
If all members of packed structure is 4-state, the structure as a whole is treated as a
4-state vector.
If there are also 2-state members, there is an implicit conversion from 4-state to 2-
state when reading those members, and from 2-state to 4-state when writing them.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SV_07_STRUCTURES_AND_UNIOUNS.html[9/26/2012 2:02:03 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS TYPEDEF Index


Introduction
SystemVerilog Data Types
Verification A typedef declaration lets you define your own identifiers that can be used in place of Literals
type specifiers such as int, byte, real.  Let us see an example of creating data type Strings
Constructs "nibble". Userdefined Datatypes
Interface Enumarations
    typedef bit[3:0] nibble; // Defining nibble data type. Structures And Uniouns
OOPS Typedef
    
Randomization     nibble a, b;  // a and b are variables with nibble data types. Arrays
     Array Methods
Functional Coverage Dynamic Arrays
Advantages Of Using Typedef :
Assertion Associative Arrays
Shorter names are easier to type and reduce typing errors. Queues
DPI Comparison Of Arrays
Improves readability by shortening complex declarations.
UVM Tutorial Improves understanding by clarifying the meaning of data. Linked List
VMM Tutorial Changing a data type in one place is easier than changing all of its uses throughout Casting
the code. Data Declaration
OVM Tutorial Allows defining new data types using structs, unions and Enumerations also. Reg And Logic
Increases reusability. Operators 1
Easy Labs : SV
Useful is type casting. Operators 2
Easy Labs : UVM Operator Precedency
Example of  typedef using struct, union and enum data types. Events
Easy Labs : OVM
Control Statements
Easy Labs : VMM    typedef enum {NO, YES} boolean; Program Block
AVM Switch TB    typedef union { int i; shortreal f; } num; // named union type Procedural Blocks
   typedef struct { Fork Join
VMM Ethernet sample       bit isfloat; Fork Control
      union { int i; shortreal f; } n; // anonymous type Subroutines
   } tagged_st; // named structure Semaphore
Verilog    Mailbox
   boolean myvar; // Enum type variable Fine Grain Process
Verification
   num n;         // Union type variable Control
Verilog Switch TB    tagged_st a[9:0]; // array of structures
Basic Constructs Report a Bug or Comment
on This section - Your
input is what keeps
Testbench.in improving
OpenVera with time!
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/SV_08_TYPEDEF.html[9/26/2012 2:02:14 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SV_08_TYPEDEF.html[9/26/2012 2:02:14 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS ARRAYS Index


Introduction
SystemVerilog Arrays hold a fixed number of equally-sized data elements. Individual elements are Data Types
Verification accessed by index using a consecutive range of integers.  Some type of arrays allows Literals
to access individual elements using non consecutive values of any data types.  Arrays Strings
Constructs can be classified as fixed-sized arrays (sometimes known as static arrays) whose size Userdefined Datatypes
Interface cannot change once their declaration is done, or dynamic arrays, which can be Enumarations
resized. Structures And Uniouns
OOPS Typedef
Randomization Fixed Arrays: Arrays
Array Methods
Functional Coverage Dynamic Arrays
"Packed array" to refer to the dimensions declared before the object name and
Assertion "unpacked array" refers to the dimensions declared after the object name.   Associative Arrays
SystemVerilog accepts a single number, as an alternative to a range, to specify the Queues
DPI Comparison Of Arrays
size of an unpacked array. That is, [size] becomes the same as [0:size-1].
UVM Tutorial Linked List
   int Array[8][32]; is the same as: int Array[0:7][0:31]; Casting
VMM Tutorial Data Declaration
OVM Tutorial Reg And Logic
Operators 1
Easy Labs : SV
Operators 2
Easy Labs : UVM Operator Precedency
Events
Easy Labs : OVM
Control Statements
Easy Labs : VMM Program Block
AVM Switch TB Procedural Blocks
Fork Join
VMM Ethernet sample Fork Control
Subroutines
   // Packed Arrays Semaphore
   reg [0:10] vari; // packed array of 4-bits Mailbox
Verilog    wire [31:0] [1:0] vari; // 2-dimensional packed array Fine Grain Process
Verification    Control
Verilog Switch TB    // Unpacked Arrays
   wire status [31:0]; // 1 dimensional unpacked array Report a Bug or Comment
Basic Constructs    wire status [32]; // 1 dimensional unpacked array on This section - Your
   input is what keeps
   integer matrix[7:0][0:31][15:0]; // 3-dimensional unpacked array of integers Testbench.in improving
OpenVera    integer matrix[8][32][16]; // 3-dimensional unpacked array of integers with time!
Constructs   
   reg [31:0] registers1 [0:255]; // unpacked array of 256 registers; each  
Switch TB    reg [31:0] registers2 [256];   // register is packed 32 bit wide
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/SV_09_ARRAYS.html[9/26/2012 2:02:26 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

Operations On Arrays

The following operations can be performed on all arrays, packed or unpacked:

   register1 [6][7:0] = `1;         // Packed indexes can be sliced


   register1 = ~register1 ;         // Can operate on entire memory
   register1 = register2 ;          // Reading and writing the entire array
   register1[7:4] = register2[3:0]  // Reading and writing a slice of the array
   register1[4+:i]= register2[4+;i] // Reading and writing a variable slice
   if(register1 == register2)       //Equality operations on the entire array
   int n[1:2][1:3] = `{`{0,1,2},`{4,4,3}};// multidimensional assignment
   int triple [1:3] = `{1:1, default:0}; // indexes 2 and 3 assigned 0

Accessing Individual Elements Of Multidimensional Arrays:

In a list of multi dimensions, the rightmost one varies most rapidly than the left most
one.  Packed dimension varies more rapidly than an unpacked.

In the following example, each dimension is having unique range and reading and
writing to a element shows exactly which index corresponds to which dimension.

   module index();
   bit [1:5][10:16] foo [21:27][31:38];
   initial

http://testbench.in/SV_09_ARRAYS.html[9/26/2012 2:02:26 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

   begin
   foo[24][34][4][14] = 1;
   $display(" foo[24][34][4][14] is %d ",foo[24][34][4][14] );
   end
   endmodule

The result of reading from an array with an out of the address bounds or if any bit in
the address is X or Z shall return the default uninitialized value for the array element
type.

As in Verilog, a comma-separated list of array declarations can be made. All arrays in


the list shall have the same data type and the same packed array dimensions.

   module array();
      bit [1:5][10:16] foo1 [21:27][31:38],foo2 [31:27][33:38];
      initial
      begin
         $display(" dimensions of foo1 is %d foo2 is
%d",$dimensions(foo1),$dimensions(foo2) );
         $display(" reading with out of bound resulted %d",foo1[100][100][100][100]);
         $display(" reading with index x resulted %d",foo1[33][1'bx]);
      end
   endmodule
RESULT:

dimensions of foo1 is 4 foo2 is 4


reading with out of bound resulted x
reading with index x resulted x

bit [3:4][5:6]Array [0:2];

Accessing "Array[2]" will access 4 elements Array[2][3][5],Array[2][3][6],Array[2][4][5]


and Array[2][4][6].
Accessing "Array[1][3]" will access 2 elements Array[1][3][5] and Array[1][3][6].
Accessing "Array[0][3][6]" will access one element.

http://testbench.in/SV_09_ARRAYS.html[9/26/2012 2:02:26 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SV_09_ARRAYS.html[9/26/2012 2:02:26 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS ARRAY METHODS Index


Introduction
SystemVerilog Data Types
Verification Array Methods: Literals
Strings
Constructs Systemverilog provides various kinds of methods that can be used on arrays. They are Userdefined Datatypes
Interface Enumarations
    Array querying functions Structures And Uniouns
OOPS Typedef
    Array Locator Methods Arrays
Randomization     Array ordering methods Array Methods
Functional Coverage     Array reduction methods Dynamic Arrays
Assertion     Iterator index querying Associative Arrays
Queues
DPI Comparison Of Arrays
UVM Tutorial Array Querying Functions: Linked List
Casting
VMM Tutorial SystemVerilog provides new system functions to return information about an array. Data Declaration
OVM Tutorial They are Reg And Logic
Operators 1
Easy Labs : SV $left Operators 2
Easy Labs : UVM Operator Precedency
$left shall return the left bound (MSB) of the dimension. Events
Easy Labs : OVM
Control Statements
Easy Labs : VMM $right Program Block
AVM Switch TB Procedural Blocks
$right shall return the right bound (LSB) of the dimension. Fork Join
VMM Ethernet sample Fork Control
$low Subroutines
Semaphore
Verilog $low shall return the minimum of $left and $right of the dimension. Mailbox
Fine Grain Process
Verification $high Control
Verilog Switch TB
$high shall return the maximum of $left and $right of the dimension. Report a Bug or Comment
Basic Constructs
on This section - Your
$increment input is what keeps
Testbench.in improving
OpenVera $increment shall return 1 if $left is greater than or equal to $right and -1 if $left is with time!
Constructs less than $right.
Switch TB $size
RVM Switch TB
$size shall return the number of elements in the dimension, which is equivalent to
RVM Ethernet sample $high - $low +1.

$dimensions
Specman E
$dimensions shall return the total number of dimensions in the array.
Interview Questions

EXAMPLE : arrays
    module arr;
    bit [2:0][3:0] arr [4:0][5:0];
    
       initial
       begin
           $display(" $left %0d $right %0d $low %0d $high %0d $increment %0d $size %0d
$dimensions

http://testbench.in/SV_10_ARRAY_METHODS.html[9/26/2012 2:02:34 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

%0d",$left(arr),$right(arr),$low(arr),$high(arr),$increment(arr),$size(arr),$dimensions(arr) 
);
       end
    endmodule

RESULTS :

 $left 4 $right 0 $low 0 $high 4 $increment 1 $size 5 $dimensions 4

Array Locator Methods:

Array locator methods operate on any unpacked array, including queues, but their
return type is a queue. These locator methods allow searching an array for elements
(or their indexes) that satisfies a given expression. Array locator methods traverse the
array in an unspecified order. The optional "with" expression should not include any
side effects; if it does, the results are unpredictable.

The following locator methods are supported (the "with" clause is mandatory) :

find()

find() returns all the elements satisfying the given expression

find_index()

find_index() returns the indexes of all the elements satisfying the given expression

find_first()

find_first() returns the first element satisfying the given expression

find_first_index()

find_first_index() returns the index of the first element satisfying the given expression

find_last()

find_last() returns the last element satisfying the given expression

find_last_index()

find_last_index() returns the index of the last element satisfying the given expression

For the following locator methods the "with" clause (and its expression) can be
omitted if the relational operators (<, >, ==) are defined for the element type of the
given array. If a "with" clause is specified, the relational operators (<, >, ==) must be
defined for the type of the expression.

min()

min() returns the element with the minimum value or whose expression evaluates to a
minimum

max()

http://testbench.in/SV_10_ARRAY_METHODS.html[9/26/2012 2:02:34 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

max() returns the element with the maximum value or whose expression evaluates to
a maximum

unique()

unique() returns all elements with unique values or whose expression is unique

unique_index()

unique_index() returns the indexes of all elements with unique values or whose
expression is unique

EXAMPLE :
  module arr_me;
    string SA[10], qs[$];
    int IA[*], qi[$];
    initial
       begin
       SA[1:5] ={"Bob","Abc","Bob","Henry","John"};
       IA[2]=3;
       IA[3]=13;
       IA[5]=43;
       IA[8]=36;
       IA[55]=237;
       IA[28]=39;
       // Find all items greater than 5
       qi = IA.find( x ) with ( x > 5 );
       for ( int j = 0; j < qi.size; j++ ) $write("%0d_",qi[j] );
       $display("");
       // Find indexes of all items equal to 3
       qi = IA.find_index with ( item == 3 );
       for ( int j = 0; j < qi.size; j++ ) $write("%0d_",qi[j] );
       $display("");
       // Find first item equal to Bob
       qs = SA.find_first with ( item == "Bob" );
       for ( int j = 0; j < qs.size; j++ ) $write("%s_",qs[j] );
       $display("");
       // Find last item equal to Henry
       qs = SA.find_last( y ) with ( y == "Henry" );
       for ( int j = 0; j < qs.size; j++ ) $write("%s_",qs[j] );
       $display("");
       // Find index of last item greater than Z
       qi = SA.find_last_index( s ) with ( s > "Z" );
       for ( int j = 0; j < qi.size; j++ ) $write("%0d_",qi[j] );
       $display("");
       // Find smallest item
       qi = IA.min;
       for ( int j = 0; j < qi.size; j++ ) $write("%0d_",qi[j] );
       $display("");
       // Find string with largest numerical value
       qs = SA.max with ( item.atoi );
       for ( int j = 0; j < qs.size; j++ ) $write("%s_",qs[j] );
       $display("");
       // Find all unique strings elements
       qs = SA.unique;
       for ( int j = 0; j < qs.size; j++ ) $write("%s_",qs[j] );
       $display("");
       // Find all unique strings in lowercase
       qs = SA.unique( s ) with ( s.tolower );
       for ( int j = 0; j < qs.size; j++ ) $write("%s_",qs[j] );
    end
  endmodule

RESULTS :

13_43_36_39_237_
2_
Bob_
Henry_

3_
_

http://testbench.in/SV_10_ARRAY_METHODS.html[9/26/2012 2:02:34 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

_Bob_Abc_Henry_John_
_Bob_Abc_Henry_John_

Array Ordering Methods:

Array ordering methods can reorder the elements of one-dimensional arrays or


queues. The following ordering methods are supported:

reverse()

reverse() reverses all the elements of the packed or unpacked arrays.

sort()

sort() sorts the unpacked array in ascending order, optionally using the expression in
the with clause.

rsort()

rsort() sorts the unpacked array in descending order, optionally using the with clause
expression.

shuffle()

shuffle() randomizes the order of the elements in the array.

EXAMPLE:
   module arr_order; string s[] = '{ "one", "two", "three" };
   initial
   begin
       s.reverse;      
       for ( int j = 0; j < 3;j++ ) $write("%s",s[j] );
       s.sort;
       for ( int j = 0; j < 3;j++ ) $write("%s",s[j] );
       s.rsort;
       for ( int j = 0; j < 3;j++ ) $write("%s",s[j] );
       s.shuffle;
       for ( int j = 0; j < 3;j++ ) $write("%s",s[j] );
   end
   endmodule
RESULT:

three two one


one three two
two three one
three one two

Array Reduction Methods :

Array reduction methods can be applied to any unpacked array to reduce the array to
a single value. The expression within the optional "with" clause can be used to specify
the item to use in the reduction.  The following reduction methods are supported:

sum()

sum() returns the sum of all the array elements.

product()

product() returns the product of all the array elements

and()

and() returns the bit-wise AND ( & ) of all the array elements.

or()

or() returns the bit-wise OR ( | ) of all the array elements

xor()

http://testbench.in/SV_10_ARRAY_METHODS.html[9/26/2012 2:02:34 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

xor() returns the logical XOR ( ^ ) of all the array elements.

EXAMPLE:
    module array_redu();
       byte b[] = { 1, 2, 3, 4 };
       int sum,product,b_xor;
       initial
       begin
          sum = b.sum ; // y becomes 10 => 1 + 2 + 3 + 4
          product = b.product ; // y becomes 24 => 1 * 2 * 3 * 4
          b_xor = b.xor with ( item + 4 ); // y becomes 12 => 5 ^ 6 ^ 7 ^ 8
          $display(" Sum is %0d, product is %0d, xor is %0b ",sum,product,b_xor);
       end
    endmodule
RESULT

Sum is 10, product is 24, xor is 1100

Iterator Index Querying:

The expressions used by array manipulation methods sometimes need the actual array
indexes at each iteration, not just the array element. The index method of an iterator
returns the index value of the specified dimension.

   // find all items equal to their position (index)


   q = arr.find with ( item == item.index );
   // find all items in mem that are greater than corresponding item in mem2
   q = mem.find( x ) with ( x > mem2[x.index(1)][x.index(2)] );

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SV_10_ARRAY_METHODS.html[9/26/2012 2:02:34 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS DYNAMIC ARRAYS Index


Introduction
SystemVerilog Verilog does not allow changing the dimensions of the array once it is declared.  Most Data Types
Verification of the time in verification, we need arrays whose size varies based on the some Literals
behavior. For example Ethernet packet varies length from one packet to other packet. Strings
Constructs In verilog, for creating Ethernet packet, array with Maximum packet size is declared Userdefined Datatypes
Interface and only the number of elements which are require for small packets are used and Enumarations
unused elements are waste of memory.   Structures And Uniouns
OOPS Typedef
Randomization To overcome this deficiency, System Verilog provides Dynamic Array. A dynamic array Arrays
is unpacked array whose size can be set or changed at runtime unlike verilog which Array Methods
Functional Coverage Dynamic Arrays
needs size at compile time.  Dynamic arrays allocate storage for elements at run time
Assertion along with the option of changing the size. Associative Arrays
Queues
DPI Comparison Of Arrays
Declaration Of Dynmic Array:
UVM Tutorial Linked List
    integer dyna_arr_1[],dyn_arr_2[],multi_dime_dyn_arr[][]; Casting
VMM Tutorial Data Declaration
OVM Tutorial Allocating Elements: Reg And Logic
Operators 1
Easy Labs : SV
New[]:The built-in function new allocates the storage and initializes the newly Operators 2
Easy Labs : UVM allocated array elements either to their default initial value. Operator Precedency
Events
Easy Labs : OVM
   dyna_arr_1 = new[10] ;// Allocating 10 elements Control Statements
Easy Labs : VMM    multi_dime_dyn_arr = new[4];// subarrays remain unsized and uninitialized Program Block
AVM Switch TB Procedural Blocks
Initializing Dynamic Arrays: Fork Join
VMM Ethernet sample Fork Control
The size argument need not match the size of the initialization array. When the Subroutines
initialization array<92>s size is greater, it is truncated to match the size argument; Semaphore
Verilog when it is smaller, the initialized array is padded with default values to attain the Mailbox
specified size. Fine Grain Process
Verification
Control
Verilog Switch TB    dyna_arr_2 = new[4]('{4,5,6}); // elements are {4,5,6,0}
Basic Constructs Report a Bug or Comment
Resizing Dynamic Arrays: on This section - Your
input is what keeps
Using new[] constructor and its argument, we can increase the array size without Testbench.in improving
OpenVera losing the data content. with time!
Constructs
Switch TB Dyna_arr_1 = new[100] (dyna_arr_1); // Previous 10 data preserved
RVM Switch TB Copying Elements:
RVM Ethernet sample
Copy constructor of dynamic arrays is an easy and faster way of creating duplicate
copies of data.
Specman E    Dyna_arr_2 = new[100](dyna_arr_1);// allocating and copying 100 elements.
Interview Questions    Dyna_arr_1 = [1000]; // Previous data lost. 1000 elements are allocated.

http://testbench.in/SV_11_DYNAMIC_ARRAYS.html[9/26/2012 2:02:43 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

RESULT

          4
          8
          0

The information about the size of the dynamic array is with the array itself. It can be
obtained using .size() method. This will be very helpful when you are playing with
array. You don't need to pass the size information explicitly. We can also use system
task $size() method instead of .size() method. SystemVerilog also provides delete()
method clears all the elements yielding an empty array (zero size).

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SV_11_DYNAMIC_ARRAYS.html[9/26/2012 2:02:43 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS ASSOCIATIVE ARRAYS Index


Introduction
SystemVerilog Dynamic arrays are useful for dealing with contiguous collections of variables whose Data Types
Verification number changes dynamically. Associative arrays give you another way to store Literals
information. When the size of the collection is unknown or the data space is sparse, Strings
Constructs an associative array is a better option. In Associative arrays Elements Not Allocated Userdefined Datatypes
Interface until Used.  Index Can Be of Any Packed Type, String or Class. Associative elements Enumarations
are stored in an order that ensures fastest access. Structures And Uniouns
OOPS Typedef
Randomization In an associative array a key is associated with a value. If you wanted to store the Arrays
information of various transactions in an array, a numerically indexed array would not Array Methods
Functional Coverage Dynamic Arrays
be the best choice. Instead, we could use the transaction names as the keys in
Assertion associative array, and the value would be their respective information. Using Associative Arrays
associative arrays, you can call the array element you need using a string rather than Queues
DPI Comparison Of Arrays
a number, which is often easier to remember.
UVM Tutorial The syntax to declare an associative array is: Linked List
Casting
VMM Tutorial Data Declaration
data_type array_id [ key _type];
OVM Tutorial Reg And Logic
 data_type is the data type of the array elements. Operators 1
Easy Labs : SV
 array_id is the name of the array being declared. Operators 2
Easy Labs : UVM  key_type is the data-type to be used as an key. Operator Precedency
Events
Easy Labs : OVM
Examples of associative array declarations are: Control Statements
Easy Labs : VMM Program Block
AVM Switch TB    int array_name[*];//Wildcard index. can be indexed by any integral datatype. Procedural Blocks
   int array_name [ string ];// String index Fork Join
VMM Ethernet sample    int array_name [ some_Class ];// Class index Fork Control
   int array_name [ integer ];// Integer index Subroutines
   typedef bit signed [4:1] Nibble; Semaphore
Verilog    int array_name [ Nibble ];  // Signed packed array Mailbox
Fine Grain Process
Verification
Control
Verilog Switch TB Elements in associative array elements can be accessed like those of one dimensional
Basic Constructs arrays. Associative array literals use the '{index:value} syntax with an optional default Report a Bug or Comment
index. on This section - Your
input is what keeps
//associative array of 4-state integers indexed by strings, default is '1. Testbench.in improving
OpenVera    integer tab [string] = '{"Peter":20, "Paul":22, "Mary":23, default:-1 }; with time!
Constructs
Switch TB Associative Array Methods
RVM Switch TB SystemVerilog provides several methods which allow analyzing and manipulating
RVM Ethernet sample associative arrays. They are:

The num() or size() method returns the number of entries in the associative array.
The delete() method removes the entry at the specified index.
Specman E The exists() function checks whether an element exists at the specified index within
Interview Questions the given array.
The first() method assigns to the given index variable the value of the first (smallest)
index in the associative array. It returns 0 if the array is empty; otherwise, it returns
1.
The last() method assigns to the given index variable the value of the last (largest)
index in the associative array. It returns 0 if the array is empty; otherwise, it returns
1.
The next() method finds the entry whose index is greater than the given index. If
there is a next entry, the index variable is assigned the index of the next entry, and
the function returns 1. Otherwise, the index is unchanged, and the function returns 0.
The prev() function finds the entry whose index is smaller than the given index. If

http://testbench.in/SV_12_ASSOCIATIVE_ARRAYS.html[9/26/2012 2:02:55 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

there is a previous entry, the index variable is assigned the index of the previous
entry, and the function returns 1. Otherwise, the index is unchanged, and the
function returns 0.

EXAMPLE
    module assoc_arr;
       int temp,imem[*];
       initial
       begin
          imem[ 2'd3 ] = 1;
          imem[ 16'hffff ] = 2;
          imem[ 4'b1000 ] = 3;
          $display( "%0d entries", imem.num );
          if(imem.exists( 4'b1000) )
              $display("imem.exists( 4b'1000) ");
          imem.delete(4'b1000);
          if(imem.exists( 4'b1000) )
              $display(" imem.exists( 4b'1000) ");
          else
              $display(" ( 4b'1000) not existing");
          if(imem.first(temp))
              $display(" First entry is at index %0db ",temp);
          if(imem.next(temp))
              $display(" Next entry is at index %0h after the index 3",temp);
          // To print all the elements alone with its indexs
          if (imem.first(temp) )
          do
              $display( "%d : %d", temp, imem[temp] );
          while ( imem.next(temp) );
       end
    endmodule

RESULT

3 entries
imem.exists( 4b'1000)
 ( 4b'1000) not existing
 First entry is at index 3b
 Next entry is at index ffff after the index 3
          3 :           1
      65535 :           2

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/SV_12_ASSOCIATIVE_ARRAYS.html[9/26/2012 2:02:55 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SV_12_ASSOCIATIVE_ARRAYS.html[9/26/2012 2:02:55 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS QUEUES Index


Introduction
SystemVerilog Data Types
Verification A queue is a variable-size, ordered collection of homogeneous elements. A Queue is Literals
analogous to one dimensional unpacked array that grows and shrinks automatically. Strings
Constructs Queues can be used to model a last in, first out buffer or first in, first out buffer. Userdefined Datatypes
Interface Queues support insertion and deletion of elements from random locations using an Enumarations
index. Queues Can be passed to tasks / functions as ref or non-ref arguments. Type Structures And Uniouns
OOPS Typedef
checking is also done.
Randomization Arrays
Array Methods
Functional Coverage Dynamic Arrays
Queue Operators:
Assertion Associative Arrays
Queues and dynamic arrays have the same assignment and argument passing Queues
DPI Comparison Of Arrays
semantics. Also, queues support the same operations that can be performed on
UVM Tutorial unpacked arrays and use the same operators and rules except as defined below: Linked List
Casting
VMM Tutorial Data Declaration
     int q[$] = { 2, 4, 8 };
OVM Tutorial      int p[$]; Reg And Logic
     int e, pos; Operators 1
Easy Labs : SV
     e = q[0];              //  read the first (leftmost) item Operators 2
Easy Labs : UVM      e = q[$];              //  read the last (rightmost) item Operator Precedency
     q[0] = e;              //  write the first item Events
Easy Labs : OVM
     p = q;                 //  read and write entire queue (copy) Control Statements
Easy Labs : VMM      q = { q, 6 };          // insert '6' at the end (append 6) Program Block
AVM Switch TB      q = { e, q };          // insert 'e' at the beginning (prepend e) Procedural Blocks
     q = q[1:$];            // delete the first (leftmost) item Fork Join
VMM Ethernet sample      q = q[0:$-1];          // delete the last (rightmost) item Fork Control
     q = q[1:$-1];          // delete the first and last items Subroutines
     q = {};                // clear the queue (delete all items) Semaphore
Verilog      q = { q[0:pos-1], e, q[pos,$] };   // insert 'e' at position pos Mailbox
     q = { q[0:pos], e, q[pos+1,$] };   // insert 'e' after position pos Fine Grain Process
Verification
Control
Verilog Switch TB Queue Methods:
Basic Constructs Report a Bug or Comment
In addition to the array operators, queues provide several built-in methods. They are: on This section - Your
input is what keeps
The size() method returns the number of items in the queue. If the queue is empty, it Testbench.in improving
OpenVera returns 0. with time!
Constructs The insert() method inserts the given item at the specified index position.
Switch TB The delete() method deletes the item at the specified index.
The pop_front() method removes and returns the first element of the queue.
RVM Switch TB The pop_back() method removes and returns the last element of the queue.
RVM Ethernet sample The push_front() method inserts the given element at the front of the queue.
The push_back() method inserts the given element at the end of the queue.

Specman E
Interview Questions EXAMPLE
    module queues;
        byte qu [$] ;
        
        initial
        begin
            qu.push_front(2);
            qu.push_front(12);
            qu.push_front(22);
            qu.push_back(11);
            qu.push_back(99);

http://testbench.in/SV_13_QUEUES.html[9/26/2012 2:03:03 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

            $display(" %d ",qu.size() );
            $display(" %d ",qu.pop_front() );
            $display(" %d ",qu.pop_back() );
            qu.delete(3);
            $display(" %d ",qu.size() );
        end
    endmodule
RESULTS :
5
22
99

Dynamic Array Of Queues Queues Of Queues

EXAMPLE:
    module top;
       typedef int qint_t[$];
       // dynamic array of queues
       qint_t DAq[]; // same as int DAq[][$];
       // queue of queues
       qint_t Qq[$]; // same as int Qq[$][$];
       // associative array of queues
       qint_t AAq[string]; // same as int AAq[string][$];
       initial begin
          // Dynamic array of 4 queues
          DAq = new[4];
          // Push something onto one of the queues
          DAq[2].push_back(1);
          // initialize another queue with three entries
          DAq[0] = {1,2,3};
          $display("%p",DAq);
          // Queue of queues -two
          Qq= {{1,2},{3,4,5}};
          Qq.push_back(qint_t'{6,7});
          Qq[2].push_back(1);
          $display("%p",Qq);
          // Associative array of queues
          AAq["one"] = {};
          AAq["two"] = {1,2,3,4};
          AAq["one"].push_back(5);
          $display("%p",AAq);
       end
          
    endmodule : top

RESULTS:

 '{'{1, 2, 3}, '{}, '{1}, '{}}


 '{'{1, 2}, '{3, 4, 5}, '{6, 7, 1}}
 '{one:'{5}, two:'{1, 2, 3, 4} }

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/SV_13_QUEUES.html[9/26/2012 2:03:03 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SV_13_QUEUES.html[9/26/2012 2:03:03 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS COMPARISON OF ARRAYS Index


Introduction
SystemVerilog Data Types
Verification Static Array Literals
Strings
Constructs Size should be known at compilation time. Userdefined Datatypes
Interface Time require to access any element is less. Enumarations
if not all elements used by the application, then memory is wasted. Structures And Uniouns
OOPS Typedef
Not good for sparse memory or when the size changes.
Randomization Good for contagious data. Arrays
Array Methods
Functional Coverage Dynamic Arrays
Assertion Associativearray Associative Arrays
Queues
DPI Comparison Of Arrays
No need of size information at compile time.
UVM Tutorial Time require to access an element increases with size of the array. Linked List
Compact memory usage for sparse arrays. Casting
VMM Tutorial Data Declaration
User don't need to keep track of size. It is automatically resized.
OVM Tutorial Good inbuilt methods for Manipulating and analyzing the content. Reg And Logic
Operators 1
Easy Labs : SV
Operators 2
Easy Labs : UVM Dynamicarray Operator Precedency
Events
Easy Labs : OVM
No need of size information at compile time. Control Statements
Easy Labs : VMM To set the size or resize, the size should be provided at runtime. Program Block
AVM Switch TB Performance to access elements is same as Static arrays. Procedural Blocks
Good for contagious data. Fork Join
VMM Ethernet sample Memory usage is very good, as the size can be changed dynamically. Fork Control
Subroutines
Semaphore
Verilog Queues Mailbox
Fine Grain Process
Verification
No need of size information at compile time. Control
Verilog Switch TB Performance to access elements is same as Static arrays.
Basic Constructs User doesn't need to provide size information to change the size. It is automatically Report a Bug or Comment
resized. on This section - Your
Rich set of inbuilt methods for Manipulating and analyzing the content. input is what keeps
Useful in self-checking modules. Very easy to work with out of order transactions. Testbench.in improving
OpenVera Inbuilt methods for sum of elements, sorting all the elements. with time!
Constructs Searching for elements is very easy even with complex expressions.
Switch TB Useful to model FIFO or LIFO.
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/SV_14_COMPARISON_OF_ARRAYS.html[9/26/2012 2:03:12 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SV_14_COMPARISON_OF_ARRAYS.html[9/26/2012 2:03:12 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS LINKED LIST Index


Introduction
SystemVerilog The List package implements a classic list data-structure, and is analogous to the STL Data Types
Verification (Standard Template Library) List container that is popular with C++ programmers. The Literals
container is defined as a parameterized class, meaning that it can be customized to Strings
Constructs hold data of any type. The List package supports lists of any arbitrary predefined Userdefined Datatypes
Interface type, such as integer, string, or class object. First declare the Linked list type and Enumarations
then take instances of it. SystemVerilog has many methods to operate on these Structures And Uniouns
OOPS Typedef
instances.
Randomization A double linked list is a chain of data structures called nodes.  Each node has 3 Arrays
members, one points to the next item or points to a null value if it is last node, one Array Methods
Functional Coverage Dynamic Arrays
points to the previous item or points to a null value if it is first node and other has the
Assertion data.   Associative Arrays
Queues
DPI Comparison Of Arrays
UVM Tutorial Linked List
Casting
VMM Tutorial Data Declaration
OVM Tutorial Reg And Logic
Operators 1
Easy Labs : SV
Operators 2
Easy Labs : UVM The disadvantage of the linked list is that data can only be accessed sequentially and Operator Precedency
not in random order. To read the 1000th element of a linked list, you must read the Events
Easy Labs : OVM 999 elements that precede it. Control Statements
Easy Labs : VMM Program Block
AVM Switch TB Procedural Blocks
List Definitions: Fork Join
VMM Ethernet sample Fork Control
list :- A list is a doubly linked list, where every element has a predecessor and Subroutines
successor. It is a sequence that supports both forward and backward traversal, as well Semaphore
as amortized constant time insertion and removal of elements at the beginning, end, Mailbox
Verilog or middle. Fine Grain Process
Verification
Control
Verilog Switch TB container :- A container is a collection of objects of the same type .Containers are
objects that contain and manage other objects and provide iterators that allow the Report a Bug or Comment
Basic Constructs contained objects (elements) to be addressed. A container has methods for accessing on This section - Your
its elements. Every container has an associated iterator type that can be used to input is what keeps
iterate through the container´s elements. Testbench.in improving
OpenVera with time!
iterator :- Iterators provide the interface to containers. They also provide a means to
Constructs
traverse the container elements. Iterators are pointers to nodes within a list. If an
Switch TB iterator points to an object in a range of objects and the iterator is incremented, the
RVM Switch TB iterator then points to the next object in the range.

RVM Ethernet sample


Procedure To Create And Use List:

Specman E 1.      include the generic List class declaration


Interview Questions       `include <List.vh>

2.      Declare list variable

      List#(integer) il; // Object il is a list of integer

3.      Declaring list iterator

      List_Iterator#(integer) itor; //Object s is a list-of-integer iterator

List_iterator Methods

http://testbench.in/SV_15_LINKED_LIST.html[9/26/2012 2:03:22 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

The List_Iterator class provides methods to iterate over the elements of lists.

The next() method changes the iterator so that it refers to the next element in the
list.
The prev() method changes the iterator so that it refers to the previous element in
the list.
The eq() method compares two iterators and returns 1 if both iterators refer to the
same list element.
The neq() method is the negation of eq().
The data() method returns the data stored in the element at the given iterator
location.

List Methods

The List class provides methods to query the size of the list; obtain iterators to the
head or tail of the list;
retrieve the data stored in the list; and methods to add, remove, and reorder the
elements of the list.

The size() method returns the number of elements stored in the list.
The empty() method returns 1 if the number elements stored in the list is zero and 0
otherwise.
The push_front() method inserts the specified value at the front of the list.
The push_back() method inserts the specified value at the end of the list.
The front() method returns the data stored in the first element of the list.
The back() method returns the data stored in the last element of the list.
The pop_front() method removes the first element of the list.
The pop_back() method removes the last element of the list.
The start() method returns an iterator to the position of the first element in the list.
The finish() method returns an iterator to a position just past the last element in the
list.
The insert() method inserts the given data into the list at the position specified by the
iterator.
The insert_range() method inserts the elements contained in the list range specified
by the iterators first and last at the specified list position.
The erase() method removes from the list the element at the specified position.
The erase_range() method removes from a list the range of elements specified by the
first and last iterators.
The set() method assigns to the list object the elements that lie in the range specified
by the first and last iterators.
The swap() method exchanges the contents of two equal-size lists.
The clear() method removes all the elements from a list, but not the list itself.
The purge() method removes all the list elements (as in clear) and the list itself.

EXAMPLE
    module lists();
        List#(integer) List1;
        List_Iterator#(integer)  itor;
        initial begin
            List1 = new();
            $display (" size of list is %d \n",List1.size());
            List1.push_back(10);
            List1.push_front(22);
            $display (" size of list is %d \n",List1.size());
            $display (" poping from list : %d \n",List1.front());
            $display (" poping from list : %d \n",List1.front());

http://testbench.in/SV_15_LINKED_LIST.html[9/26/2012 2:03:22 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

            List1.pop_front();
            List1.pop_front();
            $display (" size of list is %d \n",List1.size());
            List1.push_back(5);
            List1.push_back(55);
            List1.push_back(555);
            List1.push_back(5555);
            $display (" size of list is %d \n",List1.size());
            
            itor = List1.start();
            $display (" startn of list %d \n",itor.data());
            itor.next();
            $display (" second element of list is %d \n",itor.data());
            itor.next();
            $display (" third element of list is %d \n",itor.data());
            itor.next();
            $display (" fourth element of list is %d \n",itor.data());
            
            itor = List1.erase(itor);
            $display (" after erasing element,the itor element of list is %d \n",itor.data());
            itor.prev();
            $display(" prevoious element is %d \n",itor.data());
        end
        
    endmodule
RESULT:

 size of list is 0
 size of list is 2
 poping from list : 22
 poping from list : 22
 size of list is 0
 size of list is 4
 startn of list 5
 second element of list is 55
 third element of list is 555
 fourth element of list is 5555
 after erasing element,the itor element of list is x
 prevoious element is 555

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SV_15_LINKED_LIST.html[9/26/2012 2:03:22 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS CASTING Index


Introduction
SystemVerilog Verilog is loosely typed . Assignments can be done from one data type to other data Data Types
Verification types based on predefined rules.The compiler only checks that the destination Literals
variable and source expression are scalars. Otherwise, no type checking is done at Strings
Constructs compile time. Systemverilog has complex data types than Verilog.  It's necessary for Userdefined Datatypes
Interface SystemVerilog to be much stricter about type conversions than Verilog, so Enumarations
Systemverilog provided the cast(`) operator, which specifies the type to use for a Structures And Uniouns
OOPS Typedef
specific expression. Using Casting one can assign values to variables that might not
Randomization ordinarily be valid because of differing data type. SystemVerilog adds 2 types of Arrays
casting. Static casting and dynamic casting. Array Methods
Functional Coverage Dynamic Arrays
Assertion Associative Arrays
Static Casting Queues
DPI Comparison Of Arrays
UVM Tutorial A data type can be changed by using a cast ( ' ) operation. In a static cast, the Linked List
expression to be cast shall be enclosed in parentheses that are prefixed with the Casting
VMM Tutorial Data Declaration
casting type and an apostrophe. If the expression is assignment compatible with the
OVM Tutorial casting type, then the cast shall return the value that a variable of the casting type Reg And Logic
would hold after being assigned the expression. Operators 1
Easy Labs : SV
Operators 2
Easy Labs : UVM EXAMPLE: Operator Precedency
    int'(2.0 * 3.0) Events
Easy Labs : OVM
    shortint'{{8'hFA,8'hCE}} Control Statements
Easy Labs : VMM     signed'(x) Program Block
AVM Switch TB     17'(x - 2) Procedural Blocks
Fork Join
VMM Ethernet sample Dynamic Casting Fork Control
Subroutines
SystemVerilog provides the $cast system task to assign values to variables that might Semaphore
Verilog not ordinarily be valid because of differing data type. $cast can be called as either a Mailbox
task or a function. Fine Grain Process
Verification
The syntax for $cast is as follows: Control
Verilog Switch TB function int $cast( singular dest_var, singular source_exp );
Basic Constructs or Report a Bug or Comment
task $cast( singular dest_var, singular source_exp ); on This section - Your
input is what keeps
The dest_var is the variable to which the assignment is made. The source_exp is the Testbench.in improving
OpenVera expression that is to be assigned to the destination variable. Use of $cast as either a with time!
Constructs task or a function determines how invalid assignments are handled. When called as a
Switch TB task, $cast attempts to assign the source expression to the destination variable. If the
assignment is invalid, a run-time error occurs, and the destination variable is left
RVM Switch TB unchanged.
RVM Ethernet sample
EXAMPLE:
typedef enum { red, green, blue, yellow, white, black } Colors;
Colors col;
Specman E $cast( col, 2 + 3 );
Interview Questions
Cast Errors

Following example shows the compilation error.

EXAMPLE:
    module enum_method;
        typedef enum {red,blue,green} colour;
        colour c,d;
        int i;
        initial

http://testbench.in/SV_16_CASTING.html[9/26/2012 2:03:29 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

        begin
           d = (c + 1); 
        end
    endmodule
RESULT

Illegal assignment

Following example shows the simulation error. This is compilation error free. In this
example , d is assigned c + 10 , which is out of bound in enum colour.

EXAMPLE:
    module enum_method;
        typedef enum {red,blue,green} colour;
        colour c,d;
        int i;
        initial
        begin
            $cast(d,c + 10); 
        end
    endmodule
RESULT

Dynamic cast failed

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SV_16_CASTING.html[9/26/2012 2:03:29 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS DATA DECLARATION Index


Introduction
SystemVerilog Scope And Lifetime: Data Types
Verification Literals
Global : Strings
Constructs Userdefined Datatypes
Interface SystemVerilog adds the concept of global scope. Any declarations and definitions Enumarations
which is declared outside a module, interface, task, or function, is global in scope. Structures And Uniouns
OOPS Typedef
Global variables have a static lifetime (exists for the whole elaboration and simulation
Randomization time). Datatypes, tasks,functions, class definitions can be in global scope. Global Arrays
members can be referenced explicitly via the $root . All these can be accessed from Array Methods
Functional Coverage Dynamic Arrays
any scope as this is the highest scope and any other scope will be below the global.
Assertion Associative Arrays
Local : Queues
DPI Comparison Of Arrays
UVM Tutorial Local declarations and definitions are accessible at the scope where they are defined Linked List
and below. By default they are static in life time. They can be made to automatic. To Casting
VMM Tutorial Data Declaration
access these local variables which are static, hierarchical pathname should be used.  
OVM Tutorial Reg And Logic
   int st0;             //Static. Global Variable. Declared outside module Operators 1
Easy Labs : SV
   task disp();         //Static. Global Task. Operators 2
Easy Labs : UVM Operator Precedency
   module msl; Events
Easy Labs : OVM
      int st0;             //static. Local to module Control Statements
Easy Labs : VMM Program Block
AVM Switch TB       initial begin Procedural Blocks
         int st1;             //static. Local to module Fork Join
VMM Ethernet sample          static int st2;      //static. Local to Module Fork Control
         automatic int auto1; //automatic. Subroutines
      end Semaphore
Verilog Mailbox
      task automatic t1(); //Local task definition. Fine Grain Process
Verification
         int auto2;           //automatic. Local to task Control
Verilog Switch TB          static int st3;      //static.Local to task. Hierarchical path access allowed
Basic Constructs          automatic int auto3; //automatic. Local to task Report a Bug or Comment
         on This section - Your
         $root.st0 = st0;     //$root.sto is global variable, st0 is local to module. input is what keeps
         Testbench.in improving
OpenVera       endtask with time!
Constructs    endmodule
Switch TB
Alias:
RVM Switch TB
RVM Ethernet sample The Verilog assign statement is a unidirectional assignment. To model a bidirectional
short-circuit connection it is necessary to use the alias statement.

This example strips out the least and most significant bytes from a four byte bus:
Specman E
Interview Questions    module byte_rip (inout wire [31:0] W, inout wire [7:0] LSB, MSB);
      alias W[7:0] = LSB;
      alias W[31:24] = MSB;
   endmodule

Data Types On Ports:

Verilog restricts the data types that can be connected to module ports. Only net types
are allowed on the receiving side and Nets, regs or integers on the driving side.
SystemVerilog removes all restrictions on port connections.  Any data type can be
used on either side of the port. Real numbers, Arrays, Structures can also be passed

http://testbench.in/SV_17_DATA_DECLARATION.html[9/26/2012 2:03:39 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

through ports.

Parameterized Data Types:

Verilog allowed only values to be parameterized.  SystemVerilog allows data types to


be "parameterized".  A data-type parameter can only be set to a data-type.

   module foo #(parameter type VAR_TYPE = integer);

   foo #(.VAR_TYPE(byte)) bar ();

Declaration And Initialization:

   integer i = 1;

In Verilog, an initialization value specified as part of the declaration is executed as if


the assignment were made from an initial block, after simulation has started.  This
creates an event at time 0 and it is same as if the assiginment is done in initial block.
In Systemverilog , setting the initial value of a static variable as part of the variable
declaration is done before initial block and so does not generate an event.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SV_17_DATA_DECLARATION.html[9/26/2012 2:03:39 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS REG AND LOGIC Index


Introduction
SystemVerilog Data Types
Verification Historically, Verilog used the terms wire and reg as a descriptive way to declare wires Literals
and registers. The original intent was soon lost in synthesis and verification coding Strings
Constructs styles, which soon gave way to using terns Nets and Variables in Verilog-2001. The Userdefined Datatypes
Interface keyword reg remained in SystemVerilog, but was now misleading its intent. Enumarations
SystemVerilog adds the keyword logic as a more descriptive term to remind users that Structures And Uniouns
OOPS Typedef
it is not a hardware register. logic and reg are equivalent types.
Randomization Arrays
SystemVerilog extended the variable type so that, it can be used to connect gates and Array Methods
Functional Coverage Dynamic Arrays
modules. All variables can be written either by one continuous assignment, or by one
Assertion or more procedural statements. It shall be an error to have multiple continuous Associative Arrays
assignments or a mixture of procedural and continuous assignments.   Queues
DPI Comparison Of Arrays
UVM Tutorial Now we saw logic and wire are closer. Wire (net) is used when driven by multiple Linked List
drivers, where as logic is used when it is driven by only one driver. logic just holds the Casting
VMM Tutorial Data Declaration
last value assigned to it, while a wire resolves its value based on all the drivers.
OVM Tutorial Reg And Logic
For example: Operators 1
Easy Labs : SV
Operators 2
Easy Labs : UVM logic abc; Operator Precedency
Events
Easy Labs : OVM
Control Statements
Easy Labs : VMM The following statements are legal assignments to logic abc: Program Block
AVM Switch TB Procedural Blocks
1)      assign abc = sel ? 1 : 0; Fork Join
VMM Ethernet sample 2)      not (abc,pqr), Fork Control
3)      always #10 abc = ~abc; Subroutines
Semaphore
Verilog Mailbox
Fine Grain Process
Verification
Control
Verilog Switch TB
Basic Constructs Report a Bug or Comment
on This section - Your
input is what keeps
Testbench.in improving
OpenVera with time!
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/SV_18_REG_AND_LOGIC.html[9/26/2012 2:03:52 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SV_18_REG_AND_LOGIC.html[9/26/2012 2:03:52 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS OPERATORS 1 Index


Introduction
SystemVerilog The SystemVerilog operators are a combination of Verilog and C operators. In both Data Types
Verification languages, the type and size of the operands is fixed, and hence the operator is of a Literals
fixed type and size. The fixed type and size of operators is preserved in Strings
Constructs SystemVerilog. This allows efficient code generation. Userdefined Datatypes
Interface Enumarations
Verilog does not have assignment operators or increment and decrement operators. Structures And Uniouns
OOPS Typedef
SystemVerilog includes the C assignment operators, such as +=, and the C increment
Randomization and decrement operators, ++ and --. Arrays
Array Methods
Functional Coverage Dynamic Arrays
Verilog-2001 added signed nets and reg variables, and signed based literals. There is a
Assertion difference in the rules for combining signed and unsigned integers between Verilog Associative Arrays
and C. SystemVerilog uses the Verilog rules. Queues
DPI Comparison Of Arrays
UVM Tutorial Linked List
Operators In Systemverilog Casting
VMM Tutorial Data Declaration
OVM Tutorial Reg And Logic
Following are the operators in systemverilog Operators 1
Easy Labs : SV
Operators 2
Easy Labs : UVM Operator Precedency
Events
Easy Labs : OVM
Control Statements
Easy Labs : VMM Program Block
AVM Switch TB Procedural Blocks
Fork Join
VMM Ethernet sample Fork Control
Subroutines
Semaphore
Verilog Mailbox
Fine Grain Process
Verification
Control
Verilog Switch TB
Basic Constructs Report a Bug or Comment
on This section - Your
input is what keeps
Testbench.in improving
OpenVera with time!
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/SV_19_OPERATORS_1.html[9/26/2012 2:04:02 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

Assignment Operators

In addition to the simple assignment operator, =, SystemVerilog includes the C


assignment operators and special bitwise assignment operators:

+=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=, <<<=,>>>=. 

An assignment operator is semantically equivalent to a blocking assignment, with the


exception that any left-hand side index expression is only evaluated once.

For example:

a[i]+=2; // same as a[i] = a[i] +2;

Following are the new SystemVerilog assignment operators and its equivalent in
verilog

http://testbench.in/SV_19_OPERATORS_1.html[9/26/2012 2:04:02 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

Assignments In Expression

In SystemVerilog, an expression can include a blocking assignment. such an


assignment must be enclosed in parentheses to avoid common mistakes such as using
a=b for a==b, or a|=b for a!=b.

   if ((a=b)) b = (a+=1); // assign b to a


   a = (b = (c = 5));// assign 5 to c
  
   if(a=b) // error in systemverilog

   (a=b) statement assigns b value to a and then returns a value.  


  
   if((a=b)) is equivalent to
  
   a=b;
   if(a)

EXAMPLE
    module assignment();
        int a,b,c;
        initial begin
            a = 1; b =2;c =3;
            if((a=b))
            $display(" a value is %d ",a);
            a = (b = (c = 5));
            $display(" a is %d b is %d c is %d ",a,b,c);
        end
        
    endmodule
RESULT

 a value is           2
 a is           5 b is           5 c is           5

Concatenation :

 {} concatenation right of assignment.


´{} concatenation left of assignment.

EXAMPLE :Concatenation                      
    program main ;

http://testbench.in/SV_19_OPERATORS_1.html[9/26/2012 2:04:02 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

        bit [4:0] a;
        reg b,c,d;
        initial begin
           b = 0;
           c = 1;
           d = 1;
           a = {b,c,0,0,d};
           {b,c,d} = 3'b111;
           $display(" a %b b %b c %b d %b ",a,b,c,d);
        end
    endprogram

 RESULTS            

a 00001 b 1 c 1 d 1  

Arithmetic:

 EXAMPLE :Arithmetic
    program main;
       integer a,b;
       initial
       begin
           b = 10;
           a = 22;
      
           $display(" -(nagetion)   is %0d  ",-(a) );
           $display(" a + b  is %0d    ",a+b);
           $display(" a - b  is %0d    ",a-b);
           $display(" a * b  is %0d    ",a*b);
           $display(" a / b  is %0d    ",a/b);
           $display(" a modulus b  is %0d    ",a%b);
        end
    endprogram

RESULTS                    

  -(nagetion)   is -22      
  a + b  is 32              
  a - b  is 12              
  a * b  is 220            
  a / b  is 2              
  a modules b is 2

Following tabel shows the opwer operator rules for calculating the result.

http://testbench.in/SV_19_OPERATORS_1.html[9/26/2012 2:04:02 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

program main;
 integer op1_neg,op1_n1,op1_0,op1_p1,op1_pos;
 integer op2_pos_odd,op2_pos_even,op2_zero,op2_neg_odd,op2_neg_even;
initial
begin
op1_neg = -10;op1_n1 = -1;op1_0 = 0;op1_p1 = 1;op1_pos = 10;
op2_pos_odd = 9;op2_pos_even =10;op2_zero=0;op2_neg_odd
=-9;op2_neg_even=-10;
$display("   |       -10        -1            0          1         10");
$display("---|--------------------------------------------------------");
$display("  9| %d %d %d %d
%d",op1_neg**op2_pos_odd,op1_n1**op2_pos_odd,op1_0**op2_pos_odd,op1_p1**op2_pos_odd,op1_pos**op2_pos_odd
);
$display(" 10| %d %d %d %d
%d",op1_neg**op2_pos_even,op1_n1**op2_pos_even,op1_0**op2_pos_even,op1_p1**op2_pos_even,op1_pos**op2_pos_even
);
$display("  0| %d %d %d %d
%d",op1_neg**op2_zero,op1_n1**op2_zero,op1_0**op2_zero,op1_p1**op2_zero,op1_pos**op2_zero
);
$display(" -9| %d %d %d %d
%d",op1_neg**op2_neg_odd,op1_n1**op2_neg_odd,op1_0**op2_neg_odd,op1_p1**op2_neg_odd,op1_pos**op2_neg_odd
);
$display("-10| %d %d %d %d
%d",op1_neg**op2_neg_even,op1_n1**op2_neg_even,op1_0**op2_neg_even,op1_p1**op2_neg_even,op1_pos**op2_neg_even
);
 end
endprogram
RESULT

   |       -10        -1            0          1         10
---|--------------------------------------------------------
  9| 3294967296 4294967295          0          1 1000000000
 10| 1410065408          1          0          1 1410065408
  0|          1          1          1          1          1
 -9|          0 4294967295          x          1          0
-10|          0          1          x          1          0

Relational:

# > >= < <=        relational

EXAMPLE :Relational
   program main ;
      integer a,b;
      initial
      begin
         b = 10;
         a = 22;
        
         $display(" a < b  is %0d    \n",a < b);
         $display(" a > b  is %0d    \n",a >b);
         $display(" a <= b  is %0d    \n",a <= b);
         $display(" a >= b  is %0d    \n",a >= b);
      end
   endprogram
RESULTS

 a < b  is 0
 a > b  is 1

http://testbench.in/SV_19_OPERATORS_1.html[9/26/2012 2:04:02 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

 a <= b  is 0
 a >= b  is 1

Equality:

The different types of equality (and inequality) operators in SystemVerilog behave


differently when their operands contain unknown values (X or Z). The == and !=
operators may result in X if any of their operands contains an X or Z. The === and !==
check the 4-state explicitly, therefore, X and Z values shall either match or mismatch,
never resulting in X. The ==? and !=? operators may result in X if the left operand
contains an X or Z that is not being compared with a wildcard in the right operand.

EXAMPLE : logical Equality


   program main;
       reg[3:0] a;
       reg[7:0] x, y, z;
       initial begin
          a = 4'b0101;
          x = 8'b1000_0101;
          y = 8'b0000_0101;
          z = 8'b0xx0_0101;
          if (x == a)
             $display("x equals a is TRUE.\n");
          if (y == a)
             $display("y equals a is TRUE.\n");
          if (z == a)
             $display("z equals a is TRUE.\n");
       end
   endprogram
RESULTS:

y equals a is TRUE.

EXAMPLE:case equality:
program main ;
    reg a_1,a_0,a_x,a_z;
    reg b_1,b_0,b_x,b_z;
    initial
    begin
       a_1 = 'b1;a_0 = 'b0;a_x = 'bx;a_z = 'bz;
       b_1 = 'b1;b_0 = 'b0;b_x = 'bx;b_z = 'bz;
       $display("--------------------------");
       $display (" ==    0    1    x    z  ");
       $display("--------------------------");
       $display (" 0     %b   %b   %b   %b ",a_0 == b_0,a_0 == b_1,a_0 == b_x,a_0 == b_z);
       $display (" 1     %b   %b   %b   %b ",a_1 == b_0,a_1 == b_1,a_1 == b_x,a_1 == b_z);
       $display (" x     %b   %b   %b   %b ",a_x == b_0,a_x == b_1,a_x == b_x,a_x == b_z);
       $display (" z     %b   %b   %b   %b ",a_z == b_0,a_z == b_1,a_z == b_x,a_z == b_z);
       $display("--------------------------");
       $display("--------------------------");
       $display (" ===   0    1    x    z  ");
       $display("--------------------------");
       $display (" 0     %b   %b   %b   %b ",a_0 === b_0,a_0 === b_1,a_0 === b_x,a_0
=== b_z);
       $display (" 1     %b   %b   %b   %b ",a_1 === b_0,a_1 === b_1,a_1 === b_x,a_1
=== b_z);
       $display (" x     %b   %b   %b   %b ",a_x === b_0,a_x === b_1,a_x === b_x,a_x

http://testbench.in/SV_19_OPERATORS_1.html[9/26/2012 2:04:02 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

=== b_z);
       $display (" z     %b   %b   %b   %b ",a_z === b_0,a_z === b_1,a_z === b_x,a_z
=== b_z);
       $display("--------------------------");
       $display("--------------------------");
       $display (" =?=   0    1    x    z  ");
       $display("--------------------------");
       $display (" 0     %b   %b   %b   %b ",a_0 =?= b_0,a_0 =?= b_1,a_0 =?= b_x,a_0 =?
= b_z);
       $display (" 1     %b   %b   %b   %b ",a_1 =?= b_0,a_1 =?= b_1,a_1 =?= b_x,a_1 =?
= b_z);
       $display (" x     %b   %b   %b   %b ",a_x =?= b_0,a_x =?= b_1,a_x =?= b_x,a_x =?
= b_z);
       $display (" z     %b   %b   %b   %b ",a_z =?= b_0,a_z =?= b_1,a_z =?= b_x,a_z =?
= b_z);
       $display("--------------------------");
       $display("--------------------------");
       $display (" !=    0    1    x    z  ");
       $display("--------------------------");
       $display (" 0     %b   %b   %b   %b ",a_0
!= b_0,a_0  != b_1,a_0  != b_x,a_0  != b_z);
       $display (" 1     %b   %b   %b   %b ",a_1
!= b_0,a_1  != b_1,a_1  != b_x,a_1  != b_z);
       $display (" x     %b   %b   %b   %b ",a_x != b_0,a_x  != b_1,a_x  != b_x,a_x  != b_z);
       $display (" z     %b   %b   %b   %b ",a_z != b_0,a_z  != b_1,a_z  != b_x,a_z  != b_z);
       $display("--------------------------");
       $display("--------------------------");
       $display (" !==   0    1    x    z  ");
       $display("--------------------------");
       $display (" 0     %b   %b   %b   %b ",a_0 !== b_0,a_0 !== b_1,a_0 !== b_x,a_0
!== b_z);
       $display (" 1     %b   %b   %b   %b ",a_1 !== b_0,a_1 !== b_1,a_1 !== b_x,a_1
!== b_z);
       $display (" x     %b   %b   %b   %b ",a_x !== b_0,a_x !== b_1,a_x !== b_x,a_x
!== b_z);
       $display (" z     %b   %b   %b   %b ",a_z !== b_0,a_z !== b_1,a_z !== b_x,a_z
!== b_z);
       $display("--------------------------");
       $display("--------------------------");
       $display (" !?=   0    1    x    z  ");
       $display("--------------------------");
       $display (" 0     %b   %b   %b   %b ",a_0 !?= b_0,a_0 !?= b_1,a_0 !?= b_x,a_0 !?
= b_z);
       $display (" 1     %b   %b   %b   %b ",a_1 !?= b_0,a_1 !?= b_1,a_1 !?= b_x,a_1 !?
= b_z);
       $display (" x     %b   %b   %b   %b ",a_x !?= b_0,a_x !?= b_1,a_x !?= b_x,a_x !?
= b_z);
       $display (" z     %b   %b   %b   %b ",a_z !?= b_0,a_z !?= b_1,a_z !?= b_x,a_z !?
= b_z);
       $display("--------------------------");
    end
endprogram
RESULTS

     --------------------------
     ==    0    1    x    z
     --------------------------
      0     1   0   x   x
      1     0   1   x   x
      x     x   x   x   x
      z     x   x   x   x
     --------------------------
     --------------------------
     ===   0    1    x    z
     --------------------------
      0     1   0   0   0
      1     0   1   0   0
      x     0   0   1   0
      z     0   0   0   1
     --------------------------
     --------------------------
     =?=   0    1    x    z
     --------------------------
      0     1   0   1   1
      1     0   1   1   1
      x     1   1   1   1
      z     1   1   1   1
     --------------------------

http://testbench.in/SV_19_OPERATORS_1.html[9/26/2012 2:04:02 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

     --------------------------
     !=    0    1    x    z
     --------------------------
      0     0   1   x   x
      1     1   0   x   x
      x     x   x   x   x
      z     x   x   x   x
     --------------------------
     --------------------------
     !==   0    1    x    z
     --------------------------
      0     0   1   1   1
      1     1   0   1   1
      x     1   1   0   1
      z     1   1   1   0
     --------------------------
     --------------------------
     !?=   0    1    x    z
     --------------------------
      0     0   1   0   0
      1     1   0   0   0
      x     0   0   0   0
      z     0   0   0   0
     --------------------------

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SV_19_OPERATORS_1.html[9/26/2012 2:04:02 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS OPERATORS 2 Index


Introduction
SystemVerilog Logical : Data Types
Verification Literals
Strings
Constructs Userdefined Datatypes
Interface Enumarations
Structures And Uniouns
OOPS Typedef
Randomization Arrays
Array Methods
Functional Coverage Dynamic Arrays
Assertion Associative Arrays
Queues
DPI Comparison Of Arrays
UVM Tutorial Linked List
Casting
VMM Tutorial Data Declaration
OVM Tutorial SystemVerilog added two new logical operators logical implication (->), and logical Reg And Logic
equivalence (<->). The logical implication expression1 -> expression2 is logically Operators 1
Easy Labs : SV
equivalent to (!expression1 || expression2), and the logical equivalence expression1 Operators 2
Easy Labs : UVM <-> expression2 is logically equivalent to ((expression1 -> expression2) && Operator Precedency
(expression2 -> expression1)). Events
Easy Labs : OVM
Control Statements
Easy Labs : VMM Program Block
AVM Switch TB Procedural Blocks
Fork Join
VMM Ethernet sample Fork Control
Subroutines
Semaphore
Verilog Mailbox
Fine Grain Process
Verification
Control
Verilog Switch TB
Basic Constructs EXAMPLE : Logical Report a Bug or Comment
   program main ; on This section - Your
      reg a_1,a_0,a_x,a_z; input is what keeps
      reg b_1,b_0,b_x,b_z; Testbench.in improving
OpenVera with time!
      initial begin
Constructs          a_1 = 'b1;a_0 = 'b0;a_x = 'bx;a_z = 'bz;
Switch TB          b_1 = 'b1;b_0 = 'b0;b_x = 'bx;b_z = 'bz;
         $display("--------------------------");
RVM Switch TB          $display (" &&   0   1   x   z  ");
RVM Ethernet sample          $display("--------------------------");
         $display (" 0     %b   %b   %b   %b ",a_0 && b_0,a_0 && b_1,a_0 && b_x,a_0
&& b_z);
         $display (" 1     %b   %b   %b   %b ",a_1 && b_0,a_1 && b_1,a_1 && b_x,a_1
Specman E && b_z);
Interview Questions          $display (" x     %b   %b   %b   %b ",a_x && b_0,a_x && b_1,a_x && b_x,a_x
&& b_z);
         $display (" z     %b   %b   %b   %b ",a_z && b_0,a_z && b_1,a_z && b_x,a_z
&& b_z);
         $display("--------------------------");
         $display("--------------------------");
         $display (" ||   0   1   x   z  ");
         $display("--------------------------");
         $display (" 0     %b   %b   %b   %b ",a_0 || b_0,a_0 || b_1,a_0 || b_x,a_0
|| b_z);
         $display (" 1     %b   %b   %b   %b ",a_1 || b_0,a_1 || b_1,a_1 || b_x,a_1

http://testbench.in/SV_20_OPERATORS_2.html[9/26/2012 2:04:13 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

|| b_z);
         $display (" x     %b   %b   %b   %b ",a_x || b_0,a_x || b_1,a_x || b_x,a_x
|| b_z);
         $display (" z     %b   %b   %b   %b ",a_z || b_0,a_z || b_1,a_z || b_x,a_z
|| b_z);
         $display("--------------------------");
         $display("--------------------------");
         $display (" !   0   1   x   z  ");
         $display("--------------------------");
         $display ("     %b   %b   %b   %b ",!b_0,!b_1,!b_x,!b_z);
         $display("--------------------------");
      end
   endprogram

RESULTS

--------------------------
 &&   0   1   x   z
--------------------------
 0     0   0   0   0
 1     0   1   x   x
 x     0   x   x   x
 z     0   x   x   x
--------------------------
--------------------------
 ||   0   1   x   z
--------------------------
 0     0   1   x   x
 1     1   1   1   1
 x     x   1   x   x
 z     x   1   x   x
--------------------------
--------------------------
 !   0   1   x   z
--------------------------
     1   0   x   x
--------------------------

Bitwise :

http://testbench.in/SV_20_OPERATORS_2.html[9/26/2012 2:04:13 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

In Systemverilog, bitwise exclusive nor has two notations (~^ and ^~).

EXAMPLE : Bitwise
program main ;
    
    reg a_1,a_0,a_x,a_z;
    reg b_1,b_0,b_x,b_z;
    initial begin
       a_1 = 'b1;a_0 = 'b0;a_x = 'bx;a_z = 'bz;
       b_1 = 'b1;b_0 = 'b0;b_x = 'bx;b_z = 'bz;
      
       $display("--------------------------");
       $display (" ~   0   1   x   z  ");
       $display("--------------------------");
       $display ("     %b   %b   %b   %b ",~b_0,~b_1,~b_x,~b_z);
       $display("--------------------------");
       $display("--------------------------");
       $display (" &   0   1   x   z  ");
       $display("--------------------------");
       $display (" 0     %b   %b   %b   %b ",a_0 & b_0,a_0 & b_1,a_0 & b_x,a_0 & b_z);
       $display (" 1     %b   %b   %b   %b ",a_1 & b_0,a_1 & b_1,a_1 & b_x,a_1 & b_z);
       $display (" x     %b   %b   %b   %b ",a_x & b_0,a_x & b_1,a_x & b_x,a_x & b_z);
       $display (" z     %b   %b   %b   %b ",a_z & b_0,a_z & b_1,a_z & b_x,a_z & b_z);
       $display("--------------------------");
       $display("--------------------------");
       $display (" &~   0   1   x   z  ");
       $display("--------------------------");
       $display (" 0     %b   %b   %b   %b ",a_0 &~ b_0,a_0 &~ b_1,a_0 &~ b_x,a_0
&~ b_z);
       $display (" 1     %b   %b   %b   %b ",a_1 &~ b_0,a_1 &~ b_1,a_1 &~ b_x,a_1
&~ b_z);
       $display (" x     %b   %b   %b   %b ",a_x &~ b_0,a_x &~ b_1,a_x &~ b_x,a_x
&~ b_z);
       $display (" z     %b   %b   %b   %b ",a_z &~ b_0,a_z &~ b_1,a_z &~ b_x,a_z
&~ b_z);
       $display("--------------------------");
       $display("--------------------------");
       $display (" |   0   1   x   z  ");
       $display("--------------------------");
       $display (" 0     %b   %b   %b   %b ",a_0 | b_0,a_0 | b_1,a_0 | b_x,a_0 | b_z);
       $display (" 1     %b   %b   %b   %b ",a_1 | b_0,a_1 | b_1,a_1 | b_x,a_1 | b_z);
       $display (" x     %b   %b   %b   %b ",a_x | b_0,a_x | b_1,a_x | b_x,a_x | b_z);
       $display (" z     %b   %b   %b   %b ",a_z | b_0,a_z | b_1,a_z | b_x,a_z | b_z);
       $display("--------------------------");
       $display (" |~   0   1   x   z  ");
       $display("--------------------------");
       $display (" 0     %b   %b   %b   %b ",a_0 |~ b_0,a_0 |~ b_1,a_0 |~ b_x,a_0 |~ b_z);
       $display (" 1     %b   %b   %b   %b ",a_1 |~ b_0,a_1 |~ b_1,a_1 |~ b_x,a_1 |~ b_z);
       $display (" x     %b   %b   %b   %b ",a_x |~ b_0,a_x |~ b_1,a_x |~ b_x,a_x |~ b_z);
       $display (" z     %b   %b   %b   %b ",a_z |~ b_0,a_z |~ b_1,a_z |~ b_x,a_z |~ b_z);
       $display("--------------------------");
       $display("--------------------------");
       $display (" ^   0   1   x   z  ");
       $display("--------------------------");
       $display (" 0     %b   %b   %b   %b ",a_0 ^ b_0,a_0 ^ b_1,a_0 ^ b_x,a_0 ^ b_z);
       $display (" 1     %b   %b   %b   %b ",a_1 ^ b_0,a_1 ^ b_1,a_1 ^ b_x,a_1 ^ b_z);

http://testbench.in/SV_20_OPERATORS_2.html[9/26/2012 2:04:13 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

       $display (" x     %b   %b   %b   %b ",a_x ^ b_0,a_x ^ b_1,a_x ^ b_x,a_x ^ b_z);
       $display (" z     %b   %b   %b   %b ",a_z ^ b_0,a_z ^ b_1,a_z ^ b_x,a_z ^ b_z);
       $display("--------------------------");
       $display (" ^~   0   1   x   z  ");
       $display("--------------------------");
       $display (" 0     %b   %b   %b   %b ",a_0 ^~ b_0,a_0 ^~ b_1,a_0 ^~ b_x,a_0 ^~ b_z);
       $display (" 1     %b   %b   %b   %b ",a_1 ^~ b_0,a_1 ^~ b_1,a_1 ^~ b_x,a_1 ^~ b_z);
       $display (" x     %b   %b   %b   %b ",a_x ^~ b_0,a_x ^~ b_1,a_x ^~ b_x,a_x ^~ b_z);
       $display (" z     %b   %b   %b   %b ",a_z ^~ b_0,a_z ^~ b_1,a_z ^~ b_x,a_z ^~ b_z);
       $display("--------------------------");
    end
endprogram

RESULTS

    --------------------------
     ~   0   1   x   z
    --------------------------
         1   0   x   x
    --------------------------
    --------------------------
     &   0   1   x   z
    --------------------------
     0     0   0   0   0
     1     0   1   x   x
     x     0   x   x   x
     z     0   x   x   x
    --------------------------
    --------------------------
     &~   0   1   x   z
    --------------------------
     0     0   0   0   0
     1     1   0   x   x
     x     x   0   x   x
     z     x   0   x   x
    --------------------------
    --------------------------
     |   0   1   x   z
    --------------------------
     0     0   1   x   x
     1     1   1   1   1
     x     x   1   x   x
     z     x   1   x   x
    --------------------------
     |~   0   1   x   z
    --------------------------
     0     1   0   x   x
     1     1   1   1   1
     x     1   x   x   x
     z     1   x   x   x
    --------------------------
    --------------------------
     ^   0   1   x   z
    --------------------------
     0     0   1   x   x
     1     1   0   x   x
     x     x   x   x   x
     z     x   x   x   x
    --------------------------
     ^~   0   1   x   z
    --------------------------
     0     1   0   x   x
     1     0   1   x   x
     x     x   x   x   x
     z     x   x   x   x
    --------------------------

Reduction :

http://testbench.in/SV_20_OPERATORS_2.html[9/26/2012 2:04:13 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

EXAMPLE : Reduction
    program main ;
       reg [3:0] a_1,a_0,a_01xz,a_1xz,a_0xz,a_0dd1,a_even1;
       initial
       begin
          a_1     =  4'b1111 ;  
          a_0     =  4'b0000 ;
          a_01xz  =  4'b01xz ;
          a_1xz   =  4'b11xz ;
          a_0xz   =  4'b00xz ; 
          a_0dd1  =  4'b1110 ;
          a_even1 =  4'b1100 ;
          
          $display("-------------------------------------------");
          $display("     a_1   a_0   a_01xz   a_1xz     a_0xz  ");
          $display("-------------------------------------------");
          $display("&     %b     %b     %b       %b      
%b    ",&a_1,&a_0,&a_01xz,&a_1xz,&a_0xz);
          $display("|     %b     %b     %b       %b      
%b    ",|a_1,|a_0,|a_01xz,|a_1xz,|a_0xz);
          $display("~&    %b     %b     %b       %b      
%b    ",~&a_1,~&a_0,~&a_01xz,~&a_1xz,~&a_0xz);
          $display("~|    %b     %b     %b       %b      
%b    ",~|a_1,~|a_0,~|a_01xz,~|a_1xz,~|a_0xz);
          $display("-------------------------------------------");
          $display("          a_ood1   a_even1  a_1xz");
          $display("-------------------------------------------");
          $display(" ^           %b       %b        %b      ",^a_0dd1,^a_even1,^a_1xz);
          $display(" ~^          %b       %b        %b      ",~^a_0dd1,~^a_even1,~^a_1xz);
          $display("-------------------------------------------");
       end
    endprogram

RESULTS

    -------------------------------------------
         a_1   a_0   a_01xz   a_1xz     a_0xz
    -------------------------------------------
    &      1      0      0        x        0
    |      1      0      1        1        x
    ~&     0      1      1        x        1
    ~|     0      1      0        0        x
    -------------------------------------------
              a_ood1   a_even1  a_1xz
    -------------------------------------------
     ^           1         0          x
     ~^          0         1          x
    -------------------------------------------
    

Shift :

http://testbench.in/SV_20_OPERATORS_2.html[9/26/2012 2:04:13 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

The left shift operators, << and <<<, shall shift their left operand to the left by the
number by the number of bit positions given by the right operand. In both cases, the
vacated bit positions shall be filled with zeros. The right shift operators, >> and >>>,
shall shift their left operand to the right by the number of bit positions given by the
right operand. The logical right shift shall fill the vacated bit positions with zeros.
The arithmetic right shift shall fill the vacated bit positions with zeros if the result
type is unsigned. It shall fill the vacated bit positions with the value of the most
significant (i.e., sign) bit of the left operand if the result type is signed. If the right
operand has an x or z value, then the result shall be unknown. The right operand is
always treated.

EXAMPLE :Shift
  program main ;
     integer a_1,a_0;
     initial begin
        a_1     =  4'b1100 ;  
        a_0     =  4'b0011 ;
        
        $display(" << by 1  a_1  is %b a_0 is %b  ",a_1 << 1,a_0 << 1);
        $display(" >> by 2  a_1  is %b a_0 is %b  ",a_1 >> 2,a_0 >> 2);
        $display(" <<< by 1  a_1  is %b a_0 is %b  ",a_1 <<< 1,a_0 <<< 1);
        $display(" >>> by 2  a_1  is %b a_0 is %b  ",a_1 >>> 2,a_0 >>> 2);
     end
  endprogram
RESULTS

 << by 1  a_1  is 1000 a_0 is 0110  


 >> by 2  a_1  is 0011 a_0 is 0000  
 <<< by 1  a_1  is 1000 a_0 is 0110  
 >>> by 2  a_1  is 1111 a_0 is 0000  

Increment And Decrement :

# ++               increment
# --               decrement

SystemVerilog includes the C increment and decrement assignment operators ++i, --i,
i++, and i--. These do not need parentheses when used in expressions. These
increment and decrement assignment operators behave as blocking assignments.
The ordering of assignment operations relative to any other operation within an
expression is undefined. An implementation can warn whenever a variable is both
written and read-or-written within an integral expression or in other contexts where
an implementation cannot guarantee order of evaluation.

For example:
i = 10;
j = i++ + (i = i - 1);

After execution, the value of j can be 18, 19, or 20 depending upon the relative
ordering of the increment and the assignment statements. The increment and
decrement operators, when applied to real operands, increment or decrement the
operand by 1.0.

EXAMPLE : Increment and Decrement


    program main ;
    integer a_1,a_0;
    initial begin
        a_1  = 20 ;  
        a_0  = 20 ;
        a_1 ++ ;

http://testbench.in/SV_20_OPERATORS_2.html[9/26/2012 2:04:13 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

        a_0 -- ;
        $display (" a_1 is %d a_0 is %d ",a_1,a_0);
    end
    endprogram
RESULTS

 a_1 is          21 a_0 is          19

Set :

# inside !inside dist

SystemVerilog supports singular value sets and set membership operators.

The syntax for the set membership operator is:


inside_expression ::= expression inside { open_range_list }

The expression on the left-hand side of the inside operator is any singular expression.
The set-membership open_range_list on the right-hand side of the inside operator is a
comma-separated list of expressions or ranges. If an expression in the list is an
aggregate array, its elements are traversed by descending into the array until
reaching a singular value. The members of the set are scanned until a match is found
and the operation returns 1'b1. Values can be repeated, so values and value ranges
can overlap. The order of evaluation of the expressions and ranges is non-
deterministic.
 

EXAMPLE : Set
    program main ;
    integer i;
    initial begin
       i = 20;
       if( i inside {10,20,30})
          $display(" I is in 10 20 30 ");
    end
    endprogram
RESULTS

 I is in 10 20 30

Streaming Operator
The streaming operators perform packing of bit-stream types into a sequence of bits
in a user-specified order.
When used in the left-hand side , the streaming operators perform the
reverse operation, i.e., unpack a stream of bits intoone or more variables.

Re-Ordering Of The Generic Stream

The stream_operator << or >> determines the order in which blocks of data are
streamed.

>> causes blocks of data to be streamed in left-to-right order


<< causes blocks of data to be streamed in right-to-left order

For Example

    int j = { "A", "B", "C", "D" };
    { >> {j}} // generates stream "A" "B" "C" "D"
    { << byte {j}} // generates stream "D" "C" "B" "A" (little endian)
    { << 16 {j}} // generates stream "C" "D" "A" "B"
    { << { 8'b0011_0101 }} // generates stream 'b1010_1100 (bit reverse)
    { << 4 { 6'b11_0101 }} // generates stream 'b0101_11
    { >> 4 { 6'b11_0101 }} // generates stream 'b1101_01 (same)
    { << 2 { { << { 4'b1101 }} }} // generates stream 'b1110

Packing Using Streaming Operator

 Packing is performed by using the streaming operator on thr RHS of the expression.
 For example:

http://testbench.in/SV_20_OPERATORS_2.html[9/26/2012 2:04:13 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

    int j = { "A", "B", "C", "D" };
    bit [7:0] arr;
    arr = { >> {j}} 
    arr = { << byte {j}}  
    arr = { << 16 {j}}  
    arr = { << { 8'b0011_0101 }}  
    arr = { << 4 { 6'b11_0101 }}  
    arr = { >> 4 { 6'b11_0101 }}  
    arr = { << 2 { { << { 4'b1101 }} }}  

Unpacking Using Streaming Operator

 UnPacking is performed by using the streaming operator on thr LHS of the expression.
 For example

    int a, b, c;
    logic [10:0] up [3:0];
    logic [11:1] p1, p2, p3, p4;
    bit [96:1] y = {>>{ a, b, c }}; // OK: pack a, b, c
    int j = {>>{ a, b, c }}; // error: j is 32 bits < 96 bits
    bit [99:0] d = {>>{ a, b, c }}; // OK: d is padded with 4 bits
    {>>{ a, b, c }} = 23'b1; // error: too few bits in stream
    {>>{ a, b, c }} = 96'b1; // OK: unpack a = 0, b = 0, c = 1
    {>>{ a, b, c }} = 100'b1; // OK: unpack as above (4 bits unread)
    { >> {p1, p2, p3, p4}} = up; // OK: unpack p1 = up[3], p2 = up[2],
    // p3 = up[1], p4 = up[0]
 
Streaming Dynamically Sized Data

    Stream = {<< byte{p.header, p.len, p.payload, p.crc}}; // packing


    Stream = {<<byte{p.header, p.len, p.payload with [0 +: p.len], p.crc}};
    {<< byte{ p.header, p.len, p.payload with [0 +: p.len], p.crc
}} = stream; //unpacking
    q = {<<byte{p}}; // packing all the contents of an object.( p is a object )

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SV_20_OPERATORS_2.html[9/26/2012 2:04:13 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS OPERATOR PRECEDENCY Index


Introduction
SystemVerilog Data Types
Verification Literals
  ()                            Highest precedence Strings
Constructs   ++ -- Userdefined Datatypes
Interface   & ~& | ~| ^ ~^ ~ >< - Enumarations
  (unary) Structures And Uniouns
OOPS Typedef
  * / %
Randomization   + - Arrays
  << >> Array Methods
Functional Coverage Dynamic Arrays
  < <= > >= in !in dist
Assertion   =?= !?= == != === !== Associative Arrays
  & &~ Queues
DPI Comparison Of Arrays
  ^ ^~
UVM Tutorial   | |~ Linked List
  && Casting
VMM Tutorial Data Declaration
  ||
OVM Tutorial   ?: Reg And Logic
  = += -= *= /= %= Operators 1
Easy Labs : SV
  <<= >>= &= |= ^= ~&= ~|= ~^=  Lowest precedence Operators 2
Easy Labs : UVM    Operator Precedency
Events
Easy Labs : OVM
Control Statements
Easy Labs : VMM Program Block
AVM Switch TB Procedural Blocks
Fork Join
VMM Ethernet sample Fork Control
Subroutines
Semaphore
Verilog Mailbox
Fine Grain Process
Verification
Control
Verilog Switch TB
Basic Constructs Report a Bug or Comment
on This section - Your
input is what keeps
Testbench.in improving
OpenVera with time!
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/SV_21_OPERATOR_PRECEDENCY.html[9/26/2012 2:04:23 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SV_21_OPERATOR_PRECEDENCY.html[9/26/2012 2:04:23 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS EVENTS Index


Introduction
SystemVerilog Data Types
Verification An identifier declared as an event data type is called a named event. Named event is Literals
a data type which has no storage. In verilog, a named event can be triggered Strings
Constructs explicitly using "->" . Verilog Named Event triggering occurrence can be recognized by Userdefined Datatypes
Interface using the event control "@" . Named events and event control give a powerful and Enumarations
efficient means of describing the communication between, and synchronization of, Structures And Uniouns
OOPS Typedef
two or more concurrently active processes.
Randomization Arrays
SystemVerilog named events support the same basic operations as verilog named Array Methods
Functional Coverage Dynamic Arrays
event, but enhance it in several ways.
Assertion Associative Arrays
Queues
DPI Comparison Of Arrays
Triggered
UVM Tutorial Linked List
Casting
VMM Tutorial Data Declaration
The "triggered" event property evaluates to true if the given event has been triggered
OVM Tutorial in the current time-step and false otherwise. If event_identifier is null, then the Reg And Logic
triggered event property evaluates to false. Using this mechanism, an event trigger Operators 1
Easy Labs : SV
shall unblock the waiting process whether the wait executes before or at the same Operators 2
Easy Labs : UVM simulation time as the trigger operation. Operator Precedency
Events
Easy Labs : OVM
In the following example, event "e" is triggered at time 20,40,60,80 . So the Value of Control Statements
Easy Labs : VMM "e.triggered" should be TRUE at time 20,40,60,80 and FALSE at rest of the time. Program Block
AVM Switch TB Procedural Blocks
Fork Join
VMM Ethernet sample EXAMPLE: Fork Control
   module main; Subroutines
      event e; Semaphore
Verilog        Mailbox
      initial Fine Grain Process
Verification
         repeat(4) Control
Verilog Switch TB             begin
Basic Constructs             #20; Report a Bug or Comment
            ->e ; on This section - Your
            $display(" e is triggered at %t ",$time); input is what keeps
            end Testbench.in improving
OpenVera        with time!
Constructs       initial
Switch TB         #100 $finish;
      
RVM Switch TB       always
RVM Ethernet sample       begin
         #10;
         if(e.triggered)
            $display(" e is TRUE at %t",$time);
Specman E          else
Interview Questions             $display(" e is FALSE at %t",$time);
      end
      
   endmodule

RESULT

 e is FALSE at                   10
 e is triggered at                   20
 e is TRUE at                   20
 e is FALSE at                   30

http://testbench.in/SV_22_EVENTS.html[9/26/2012 2:04:32 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

 e is triggered at                   40
 e is TRUE at                   40
 e is FALSE at                   50
 e is triggered at                   60
 e is TRUE at                   60
 e is FALSE at                   70
 e is triggered at                   80
 e is TRUE at                   80
 e is FALSE at                   90

Wait()

In SystemVerilog , Named Event triggering occurrence can also be recognized by using


the event control wait(). Wait() statement gets blocked until it evaluates to TRUE.  As
we have seen in the previous example, that "event_name.triggered" returns the
trigging status of the event in the current time step.

EXAMPLE:
   module event_m;
      event a;
      
      initial
          repeat(4) 
             #20 -> a;
      
      
      always
      begin
          @a;
          $display(" ONE  :: EVENT A is triggered ");
      end
      
      always
      begin
          wait(a.triggered);
          $display(" TWO  :: EVENT A is triggered ");
          #1;
      end
   endmodule

RESULT:

 ONE  :: EVENT A is triggered


 TWO  :: EVENT A is triggered
 ONE  :: EVENT A is triggered
 TWO  :: EVENT A is triggered
 ONE  :: EVENT A is triggered
 TWO  :: EVENT A is triggered
 ONE  :: EVENT A is triggered
 TWO  :: EVENT A is triggered

Race Condition

http://testbench.in/SV_22_EVENTS.html[9/26/2012 2:04:32 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

For a trigger to unblock a process waiting on an event, the waiting process must
execute the @ statement before the triggering process executes the trigger operator,
->. If the trigger executes first, then the waiting process remains blocked.

Using event_name.triggered statement, an event trigger shall unblock the waiting


process whether the wait executes before or at the same simulation time as the
trigger operation. The triggered event property, thus, helps eliminate a common race
condition that occurs when both the trigger and the wait (using @) happen at the
same time. A process that blocks waiting for an event might or might not unblock,
depending on the execution order of the waiting and triggering
processes (race condition) . However, a process that waits on the triggered state
always unblocks, regardless of the order of execution of the wait and trigger
operations.

In the following example, event "e1" is triggered and a process is waiting on "e1" in
the same time step. The process can never catch the triggering of "e1" as it occurs
after the event "e1" triggering. Event "e2" triggering occurrence can be recognized by
wait (e2.triggered) in spite of the above condition.

EXAMPLE:

   module main;
       event e1,e2;
      
       initial
          repeat(4)
          begin
             #20;
             ->e1 ;
             @(e1)
             $display(" e1 is triggered at %t ",$time);
          end
      
       initial
          repeat(4)
             begin
                #20;
                ->e2 ;
                wait(e2.triggered);
                $display(" e2 is triggered at %t ",$time);
             end
      
   endmodule

RESULT

 e2 is triggered at                   20


 e2 is triggered at                   40
 e2 is triggered at                   60
 e2 is triggered at                   80

Nonblocking Event Trigger

Nonblocking events are triggered using the ->> operator. The effect of the ->>
operator is that the statement executes without blocking and it creates a nonblocking
assign update event in the time in which the delay control expires, or the event-
control occurs. The effect of this update event shall be to trigger the referenced
event in the nonblocking assignment region of the simulation cycle.

Merging Events

An event variable can be assigned to another event variable. When a event variable is
assigned to other , both the events point to same synchronization object. In the
following example, Event "a" is assigned to event "b" and when event "a" is triggered,
event occurrence can be seen on event "b" also.

EXAMPLE:
    module events_ab;

http://testbench.in/SV_22_EVENTS.html[9/26/2012 2:04:32 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

    event a,b;

    initial begin
       #1 -> b; // trigger both always blocks
       -> a;
       #10 b = a; // merge events
       #20 -> a; // both will trigger , 3 trigger events but have 4 trigger responses.
    end

    always@(a) begin
       $display(" EVENT A is triggered ");
       #20;
    end

    always@(b) begin
       $display(" EVENT B is triggered ");
       #20;
    end

    endmodule

RESULTS:

  EVENT B is triggered
  EVENT A is triggered
  EVENT B is triggered
  EVENT A is triggered

When events are merged, the assignment only affects the execution of subsequent
event control or wait operations. If a process is blocked waiting for event1 when
another event is assigned to event1, the currently waiting process shall never unblock.
In the following example, "always@(b)" is waiting for the event on "b" before the
assignment "b = a" and this waiting always block was never unblocked.

EXAMPLE:
    module events_ab;
       event a,b; 
      
       initial 
       begin 
          #20 -> a; 
          b = a; 
          #20 -> a; 
       end 
      
       always@(a) 
          $display(" EVENT A is triggered "); 
      
       always@(b) 
          $display(" EVENT B is also triggered "); 
      
    endmodule 

RESULTS:

  EVENT A is triggered
  EVENT A is triggered

Null Events

SystemVerilog event variables can also be assigned a null object, when assigned null
to event variable, the association between the synchronization object and the event
variable is broken.

EXAMPLE:
    program main;
       event e;
      

http://testbench.in/SV_22_EVENTS.html[9/26/2012 2:04:32 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

       initial
       begin
          repeat(4)
             #($random()%10) -> e;
          e = null;
          repeat(4)
             #($random()%10) -> e;
       end
      
       initial
          forever
             begin
             @e ;
             $display(" e is triggered at %t",$time);
             end
      
    endprogram

RESULT:

e is triggered at            348
e is triggered at           4967
e is triggered at           9934
e is triggered at          14901

** ERROR **  Accessed Null object

Wait Sequence

The wait_order construct suspends the calling process until all of the specified events
are triggered in the given order (left to right) or any of the un-triggered events are
triggered out of order and thus causes the operation to fail. Wait_order() does not
consider time, only ordering in considered.

EXAMPLE:
   module main;
      event e1,e2,e3;
      
      initial
      begin
          #10;
          -> e1;
          -> e2;
          -> e3;
          #10;
          -> e3;
          -> e1;
          -> e2;
          #10;
          -> e3;
          -> e2;
          -> e3;
      end
      
      always
      begin
         wait_order(e1,e2,e3)
            $display(" Events are in order ");
         else
            $display(" Events are out of order ");
      end
      
   endmodule

RESULT:

Events are in order


Events are out of order
Events are out of order

http://testbench.in/SV_22_EVENTS.html[9/26/2012 2:04:32 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

Events Comparison

Event variables can be compared against other event variables or the special value
null. Only the following operators are allowed for comparing event variables:

-- Equality (==) with another event or with null.


-- Inequality (!=) with another event or with null.
-- Case equality (===) with another event or with null (same semantics as ==).
-- Case inequality (!==) with another event or with null (same semantics as !=).
-- Test for a Boolean value that shall be 0 if the event is null and 1 otherwise.

EXAMPLE:
    module main;
        event e1,e2,e3,e4;
        
        initial
        begin
            e1 = null;
            e2 = e3;
            if(e1)
               $display(" e1 is not null ");
            else
               $display(" e1 is null ");
            if(e2)
               $display(" e2 is not null");
            else
               $display(" e2 is null");
            if(e3 == e4)
               $display( " e3 and e4 are same events ");
            else
               $display( " e3 and e4 are not same events ");
            if(e3 == e2)
               $display( " e3 and e2 are same events ");
            else
               $display( " e3 and e2 are not same events ");
        end
        
    endmodule

RESULT:

 e1 is null
 e2 is not null
 e3 and e4 are not same events
 e3 and e2 are same events

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SV_22_EVENTS.html[9/26/2012 2:04:32 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS CONTROL STATEMENTS Index


Introduction
SystemVerilog Sequential Control: Data Types
Verification Literals
Statements inside sequential control constructs are executed Strings
Constructs sequentially. Userdefined Datatypes
Interface Enumarations
- if-else Statement Structures And Uniouns
OOPS Typedef
- case Statement
Randomization - repeat loop Arrays
- for loop Array Methods
Functional Coverage Dynamic Arrays
- while loop
Assertion - do-while Associative Arrays
- foreach Queues
DPI Comparison Of Arrays
- Loop Control
UVM Tutorial - randcase Statements Linked List
Casting
VMM Tutorial
 if-else Statement  :  The if-else statement is the general form of selection Data Declaration
OVM Tutorial statement. Reg And Logic
Operators 1
Easy Labs : SV
 case Statement     :  The case statement provides for multi-way branching. Operators 2
Easy Labs : UVM Operator Precedency
 repeat loop        :  Repeat statements can be used to repeat the execution of a Events
Easy Labs : OVM
statement or statement block a fixed number of times. Control Statements
Easy Labs : VMM Program Block
AVM Switch TB  for loop           :  The for construct can be used to create loops.   Procedural Blocks
Fork Join
VMM Ethernet sample  while loop         :  The loop iterates while the condition is true. Fork Control
Subroutines
 do-while           :  condition is checked after loop iteration.     Semaphore
Verilog Mailbox
 foreach            :  foreach construct specifies iteration over the elements of an single Fine Grain Process
Verification
dimensional fixed-size arrays, dynamic arrays and SmartQs.     Control
Verilog Switch TB
Basic Constructs  Loop Control       :  The break and continue statements are used for flow control Report a Bug or Comment
within loops.       on This section - Your
input is what keeps
Testbench.in improving
OpenVera with time!
Constructs
Switch TB EXAMPLE : if
    program main ;
RVM Switch TB        integer i;
RVM Ethernet sample        initial begin
          i = 20;
          if( i == 20)
             $display(" I is equal to %d ",i);
Specman E           else
Interview Questions              $display(" I is not equal to %d ",i);
       end 
    endprogram
RESULTS

I is equal to 20

EXAMPLE : case and repeat


   program main ;

http://testbench.in/SV_23_CONTROL_STATEMENTS.html[9/26/2012 2:04:42 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

      integer i;
      initial begin
          repeat(10)begin
             i = $random();
             case(1) begin
                (i<0)   :$display(" i is less than zero i==%d\n",i);
                (i>0)   :$display(" i is grater than zero i=%d\n",i);
                (i == 0):$display(" i is equal to zero i=%d\n",i);
             end
          end
      end
   endprogram

RESULTS

 i is grater than zero i=69120


 i is grater than zero i=475628600
 i is grater than zero i=1129920902
 i is grater than zero i=773000284
 i is grater than zero i=1730349006
 i is grater than zero i=1674352583
 i is grater than zero i=1662201030
 i is grater than zero i=2044158707
 i is grater than zero i=1641506755
 i is grater than zero i=797919327

EXAMPLE : forloop
   program for_loop;
      integer count, i;
      initial begin
         for(count = 0, i=0; i*count<50; i++, count++)
            $display("Value i = %0d\n", i);
      end
   endprogram

RESULTS

Value i = 0
Value i = 1
Value i = 2
Value i = 3
Value i = 4
Value i = 5
Value i = 6
Value i = 7

EXAMPLE : whileloop
    program while_loop;
       integer operator=0;
       initial begin
           while (operator<5)begin
              operator += 1;
              $display("Operator is %0d\n", operator);
           end
       end
    endprogram

http://testbench.in/SV_23_CONTROL_STATEMENTS.html[9/26/2012 2:04:42 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

RESULTS

Operator is 1
Operator is 2
Operator is 3
Operator is 4
Operator is 5

EXAMPLE : dowhile
    program test;
       integer i = 0;
       initial begin
           do
           begin
              $display("i = %0d \n", i);
              i++;
           end 
           while (i < 10);
       end
    endprogram

RESULTS

i= 0
i= 1
i= 2
i= 3
i= 4
i= 5
i= 6
i= 7
i= 8
i= 9

The foreach construct specifies iteration over the elements of an array. Its argument
is an identifier that designates any type of array (fixed-size, dynamic, or associative)
followed by a list of loop variables enclosed in square brackets. Each loop variable
corresponds to one of the dimensions of the array. The foreach construct is similar to
a repeat loop that uses the array bounds to specify the repeat count instead of an
expression.

The mapping of loop variables to array indexes is determined by the dimension


cardinality, as described in multidimentional topic.
The foreach arranges for higher cardinality indexes to change more rapidly.

//      1   2   3         3    4       1   2 -> Dimension numbers


int A [2][3][4]; bit [3:0][2:1] B [5:1][4];
foreach( A [ i, j, k ] ) ...
foreach( B [ q, r, , s ] ) ...

The first foreach causes i to iterate from 0 to 1, j from 0 to 2, and k from 0 to 3. The
second foreach causes q to iterate from 5 to 1, r from 0 to 3, and s from 2 to 1
(iteration over the third index is skipped).

EXAMPLE : foeach
   program example;
      string names[$]={"Hello", "SV"};
      int fxd_arr[2][3] = '{'{1,2,3},'{4,5,6}};
      initial begin
          foreach (names[i]) 
              $display("Value at index %0d is %0s\n", i, names[i]);
          foreach(fxd_arr[,j])
              $display(fxd_arr[1][j]);
      end
   endprogram

RESULTS

http://testbench.in/SV_23_CONTROL_STATEMENTS.html[9/26/2012 2:04:42 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

Value at index 0 is Hello

Value at index 1 is SV

          4
          5
          6

EXAMPLE : randcase
   program rand_case;
      integer i;

      initial begin
         repeat(10)begin
            randcase
            begin
               10: i=1;
               20: i=2;
               50: i=3;
            end
            $display(" i is %d \n",i);end
      end
   endprogram

RESULTS

 i is 3
 i is 2
 i is 3
 i is 3
 i is 3
 i is 3
 i is 1
 i is 1
 i is 1
 i is 2

Enhanced For Loop

In Verilog, the variable used to control a for loop must be declared prior to the loop.
If loops in two or more parallel procedures use the same loop control variable, there is
a potential of one loop modifying the variable while other loops are still using it.
SystemVerilog adds the ability to declare the for loop control variable within the for
loop. This creates a local variable within the loop. Other parallel loops cannot
inadvertently affect the loop control variable.

For example:

   module foo;
      initial begin
         for (int i = 0; i <= 255; i++)
            ...
      end

      initial begin
         loop2: for (int i = 15; i >= 0; i--)
                 ...
      end
   endmodule

Unique:

A unique if asserts that there is no overlap in a series of if...else...if conditions, i.e.,


they are mutually exclusive and hence it is safe for the expressions to be evaluated in
parallel. In a unique if, it shall be legal for a condition to be evaluated at any time
after entrance into the series and before the value of the condition is needed. A
unique if shall be illegal if, for any such interleaving of evaluation and use of the
conditions, more than one condition is true. For an illegal unique if, an
implementation shall be required to issue a warning, unless it can demonstrate a legal
interleaving so that no more than one condition is true.

http://testbench.in/SV_23_CONTROL_STATEMENTS.html[9/26/2012 2:04:42 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

EXAMPLE :
   module uniq;
      
      initial
      begin
         for (int a = 0;a< 6;a++)
            unique if ((a==0) || (a==1) ) $display("0 or 1");
            else if (a == 2) $display("2");
            else if (a == 4) $display("4"); // values 3,5,6 cause a warning
      end
   endmodule

RESULTS:

0 or 1
0 or 1
2
RT Warning: No condition matches in 'unique if' statement.
4
RT Warning: No condition matches in 'unique if' statement.

Priority:

A priority if indicates that a series of if...else...if conditions shall be evaluated in the


order listed. In the preceding example, if the variable a had a value of 0, it would
satisfy both the first and second conditions, requiring priority logic. An
implementation shall also issue a warning if it determines that no condition is true, or
it is possible that no condition is true, and the final if does not have a corresponding
else.

EXAMPLE:
   module prioriti;
      initial
         for(int a = 0;a<7;a++)
            priority if (a[2:1]==0) $display("0 or 1");
            else if (a[2] == 0) $display("2 or 3");
            else $display("4 to 7"); //covers all other possible values, so no warning
   endmodule

RESULTS:

0 or 1
0 or 1
2 or 3
2 or 3
4 to 7
4 to 7
4 to 7

If the case is qualified as priority or unique, the simulator shall issue a warning
message if no case item matches. These warnings can be issued at either compile time
or run time, as soon as it is possible to determine the illegal condition.

EXAMPLE:
   module casee;
  
      initial
      begin

        for(int a = 0;a<4;a++)
          unique case(a) // values 3,5,6,7 cause a warning
                0,1: $display("0 or 1");
                2: $display("2");
                4: $display("4");
          endcase

        for(int a = 0;a<4;a++)
           priority casez(a) // values 4,5,6,7 cause a warning
                 3'b00?: $display("0 or 1");

http://testbench.in/SV_23_CONTROL_STATEMENTS.html[9/26/2012 2:04:42 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

                 3'b0??: $display("2 or 3");


           endcase

      end
   endmodule

RESULTS:

   0 or 1
   0 or 1
   2
   Warning: No condition matches in 'unique case' statement.
   0 or 1
   0 or 1
   2 or 3
   2 or 3

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SV_23_CONTROL_STATEMENTS.html[9/26/2012 2:04:42 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PROGRAM BLOCK Index


Introduction
SystemVerilog Data Types
Verification The module is the basic building block in Verilog which works well for Design. Literals
However, for the testbench, a lot of effort is spent getting the environment properly Strings
Constructs initialized and synchronized, avoiding races between the design and the testbench, Userdefined Datatypes
Interface automating the generation of input stimuli, and reusing existing models and other Enumarations
infrastructure. Structures And Uniouns
OOPS Typedef
Randomization Systemverilog adds a new type of block called program block. It is declared using Arrays
program and endprogram keywords. Array Methods
Functional Coverage Dynamic Arrays
Assertion The program block serves these basic purposes: Associative Arrays
Queues
DPI Comparison Of Arrays
-> Separates the testbench from the DUT.
UVM Tutorial -> The program block helps ensure that test bench transitions do not have race Linked List
conditions with the design Casting
VMM Tutorial Data Declaration
-> It provides an entry point to the execution of testbenches.
OVM Tutorial -> It creates a scope that encapsulates program-wide data. Reg And Logic
-> It provides a syntactic context that specifies scheduling in the Reactive region Operators 1
Easy Labs : SV
which avoids races. Operators 2
Easy Labs : UVM -> It doesnot allow always block. Only initial and methods are allowed, which are Operator Precedency
more controllable. Events
Easy Labs : OVM
-> Each program can be explicitly exited by calling the $exit system task. Unlike Control Statements
Easy Labs : VMM $finish, which exits simulation immediately, even if there are pending events. Program Block
AVM Switch TB -> Just like a module, program block has ports. One or more program blocks can be Procedural Blocks
instantiated in a top-level netlist, and connected to the DUT. Fork Join
VMM Ethernet sample Fork Control
  Subroutines
Semaphore
Verilog The program construct serves as a clear separator between design and testbench, Mailbox
and, more importantly, it specifies specialized execution semantics in the Reactive Fine Grain Process
Verification
region for all elements declared within the program. Together with clocking blocks, Control
Verilog Switch TB the program construct provides for race-free interaction between the design and the
Basic Constructs testbench, and enables cycle and transaction level abstractions. Report a Bug or Comment
on This section - Your
input is what keeps
For example: Testbench.in improving
OpenVera with time!
Constructs program test (input clk, input [16:1] addr, inout [7:0] data);
Switch TB    initial ...
endprogram
RVM Switch TB
RVM Ethernet sample program test ( interface device_ifc );
   initial ...
endprogram
Specman E
Interview Questions

http://testbench.in/SV_24_PROGRAM_BLOCK.html[9/26/2012 2:04:53 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

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 note that simply
sampling input signals (or setting non-zero 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.

Following example demonstrates the difference between the module based testbench
and program based testbenchs.

   module DUT();
       reg q = 0;
       reg clk = 0;
       initial
          #10 clk = 1;
      
       always @(posedge clk)
            q <= 1;
        
   endmodule
  
  
   module Module_based_TB();
  
        always @ (posedge DUT.clk) $display("Module_based_TB : q = %b\n", DUT.q);
  
   endmodule
  
    
   program Program_based_TB();
  
   initial
      forever @(posedge DUT.clk) $display("Program_based_TB : q = %b\n", DUT.q);
  
   endprogram
RESULT:

http://testbench.in/SV_24_PROGRAM_BLOCK.html[9/26/2012 2:04:53 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

Module_based_TB : q = 0

program_based_TB : q = 1

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SV_24_PROGRAM_BLOCK.html[9/26/2012 2:04:53 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PROCEDURAL BLOCKS Index


Introduction
SystemVerilog Final: Data Types
Verification Literals
Verilog procedural statements are in initial or always blocks, tasks, or functions. Strings
Constructs SystemVerilog adds a final block that executes at the end of simulation.SystemVerilog Userdefined Datatypes
Interface final blocks execute in an arbitrary but deterministic sequential order. This is possible Enumarations
because final blocks are limited to the legal set of statements allowed for functions. Structures And Uniouns
OOPS Typedef
Randomization Arrays
EXAMPLE : Array Methods
Functional Coverage Dynamic Arrays
   module fini;
Assertion    Associative Arrays
      initial Queues
DPI Comparison Of Arrays
         #100 $finish;
UVM Tutorial        Linked List
      final Casting
VMM Tutorial Data Declaration
         $display(" END OF SIMULATION at %d ",$time);
OVM Tutorial    endmodule Reg And Logic
RESULTS: Operators 1
Easy Labs : SV
Operators 2
Easy Labs : UVM  END OF SIMULATION at                  100 Operator Precedency
Events
Easy Labs : OVM
Control Statements
Easy Labs : VMM Jump Statements: Program Block
AVM Switch TB Procedural Blocks
SystemVerilog has statements to control the loop statements. Fork Join
VMM Ethernet sample break  : to go out of loop as C Fork Control
continue : skip to end of loop as C Subroutines
return expression : exit from a function Semaphore
Verilog return            : exit from a task or void function Mailbox
Fine Grain Process
Verification
Control
Verilog Switch TB Event Control:
Basic Constructs Report a Bug or Comment
Any change in a variable or net can be detected using the @ event control, as in on This section - Your
Verilog. If the expression evaluates to a result of more than 1 bit, a change on any of input is what keeps
the bits of the result (including an x to z change) shall trigger the event control. Testbench.in improving
OpenVera with time!
Constructs SystemVerilog adds an iff qualifier to the @ event control.
Switch TB
EXAMPLE:
RVM Switch TB   module latch (output logic [31:0] y, input [31:0] a, input enable);
RVM Ethernet sample      always @(a iff enable == 1)
        y <= a; //latch is in transparent mode
  endmodule
Specman E Always:
Interview Questions
In an always block that is used to model combinational logic, forgetting an else leads
to an unintended latch. To avoid this mistake, SystemVerilog adds specialized
always_comb and always_latch blocks, which indicate design intent to simulation,
synthesis, and formal verification tools. SystemVerilog also adds an always_ff block to
indicate sequential logic.

EXAMPLE:
   always_comb
      a = b & c;
   always_latch

http://testbench.in/SV_25_PROCEDURAL_BLOCKS.html[9/26/2012 2:05:03 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

      if(ck) q <= d;
   always_ff @(posedge clock iff reset == 0 or posedge reset)
      r1 <= reset ? 0 : r2 + 1;

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SV_25_PROCEDURAL_BLOCKS.html[9/26/2012 2:05:03 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS FORK JOIN Index


Introduction
SystemVerilog Data Types
Verification A Verilog fork...join block always causes the process executing the fork statement to Literals
block until the termination of all forked processes. With the addition of the join_any Strings
Constructs and join_none keywords, SystemVerilog provides three choices for specifying when the Userdefined Datatypes
Interface parent (forking) process resumes execution. Enumarations
Structures And Uniouns
OOPS Typedef
Randomization Arrays
Array Methods
Functional Coverage Dynamic Arrays
Assertion Associative Arrays
Queues
DPI Comparison Of Arrays
UVM Tutorial Linked List
Casting
VMM Tutorial Data Declaration
OVM Tutorial Reg And Logic
Operators 1
Easy Labs : SV
Operators 2
Easy Labs : UVM Operator Precedency
Events
Easy Labs : OVM
Control Statements
Easy Labs : VMM Program Block
AVM Switch TB Procedural Blocks
Fork Join
VMM Ethernet sample Fork Control
Subroutines
Semaphore
Verilog Mailbox
Fine Grain Process
Verification
Control
Verilog Switch TB
Fork Join None Report a Bug or Comment
Basic Constructs
on This section - Your
The parent process continues to execute concurrently with all the processes spawned input is what keeps
by the fork. The spawned processes do not start executing until the parent thread Testbench.in improving
OpenVera executes a blocking statement. with time!
Constructs
Switch TB
RVM Switch TB EXAMPLE : fork/join none
   program main ;
RVM Ethernet sample    initial
   begin
    #10;
Specman E        $display(" BEFORE fork  time = %d ",$time );
       fork 
Interview Questions            begin
               # (20);
               $display("time = %d # 20  ",$time );
           end
           begin
               #(10);
               $display("time = %d # 10  ",$time );
           end
           begin
               #(5);
               $display("time = %d # 5  ",$time );

http://testbench.in/SV_26_FORK_JOIN.html[9/26/2012 2:05:13 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

           end
         join_none
    $display(" time = %d Outside the main fork ",$time );
   #(40);
   end 
   endprogram
RESULTS

 BEFORE fork  time =                   10


 time =                   10 Outside the main fork
time =                   15 # 5
time =                   20 # 10
time =                   30 # 20

Fork Join Any

The parent process blocks until any one of the processes spawned by this fork
completes.

EXAMPLE : fork/join any


   program main;
   initial begin
    #(10);
       $display(" BEFORE fork  time = %d ",$time ); 
       fork
           begin
               # (20);
               $display("time = %d # 20  ",$time );
           end
           begin
               #(10);
               $display("time = %d # 10  ",$time );
           end
           begin
               #(5);
               $display("time = %d # 5  ",$time );
           end
         join_any
    $display(" time = %d Outside the main fork ",$time );
   #(40);
   end 
   endprogram
RESULTS

BEFORE fork  time =                   10


time =                   15 # 5
 time =                   15 Outside the main fork
time =                   20 # 10
time =                   30 # 20

For Join All

The parent process blocks until all the processes spawned by this fork complete.

EXAMPLE : fork/join all


program main ;

http://testbench.in/SV_26_FORK_JOIN.html[9/26/2012 2:05:13 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

initial
begin
 #(10);
    $display(" BEFORE fork  time = %d ",$time );
    fork
        begin
            # (20);
            $display("time = %d # 20  ",$time );
        end
        begin
            #(10);
            $display("time = %d # 10  ",$time );
        end
        begin
            #(5);
            $display("time = %d # 5  ",$time );
        end
      join
 $display(" time = %d Outside the main fork ",$time );
#(40);
end
endprogram
RESULTS

 BEFORE fork  time =                   10


time =                   15 # 5
time =                   20 # 10
time =                   30 # 20
 time =                   30 Outside the main fork

When defining a fork/join block, encapsulating the entire fork inside begin..end,
results in the entire block being treated as a single thread, and the code executes
consecutively.

EXAMPLE : sequential statement in fork/join


program main ;
initial begin
 #(10);
    $display(" First fork  time = %d ",$time ); 
    fork 
        begin
            # (20);
            $display("time = %d # 20  ",$time);
        end
        begin
            #(10);
            $display("time = %d # 10  ",$time);
        end
        begin
            #(5);
            $display("time = %d # 5  ",$time);
            #(2);
            $display("time = %d # 2  ",$time);
        end
      join_any
  $display(" time = %d Outside the main fork ",$time );
#(40);
end 
endprogram
RESULTS:

First fork  time =                   10


time =                   15 # 5
time =                   17 # 2
 time =                   17 Outside the main fork
time =                   20 # 10
time =                   30 # 20

http://testbench.in/SV_26_FORK_JOIN.html[9/26/2012 2:05:13 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SV_26_FORK_JOIN.html[9/26/2012 2:05:13 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS FORK CONTROL Index


Introduction
SystemVerilog Wait Fork Statement Data Types
Verification Literals
The wait fork statement is used to ensure that all immediate child subprocesses Strings
Constructs (processes created by the current process, excluding their descendants) have Userdefined Datatypes
Interface completed their execution. Enumarations
Structures And Uniouns
OOPS Typedef
EXAMPLE
Randomization   program main(); Arrays
Array Methods
Functional Coverage Dynamic Arrays
   initial begin
Assertion     #(10); Associative Arrays
       $display(" BEFORE fork  time = %0d ",$time );  Queues
DPI Comparison Of Arrays
       fork
UVM Tutorial            begin Linked List
               # (20); Casting
VMM Tutorial Data Declaration
               $display(" time = %0d # 20  ",$time );
OVM Tutorial            end Reg And Logic
           begin Operators 1
Easy Labs : SV
               #(10); Operators 2
Easy Labs : UVM                $display(" time = %0d # 10  ",$time ); Operator Precedency
           end Events
Easy Labs : OVM
           begin Control Statements
Easy Labs : VMM                #(5); Program Block
AVM Switch TB                $display(" time = %0d # 5  ",$time ); Procedural Blocks
           end Fork Join
VMM Ethernet sample          join_any Fork Control
    $display(" time = %0d Outside the main fork ",$time ); Subroutines
   end  Semaphore
Verilog    endprogram Mailbox
Fine Grain Process
Verification
RESULTS Control
Verilog Switch TB
Basic Constructs  BEFORE fork  time = 10 Report a Bug or Comment
 time = 15 # 5   on This section - Your
 time = 15 Outside the main fork input is what keeps
Testbench.in improving
OpenVera with time!
Constructs  In the above example, Simulation ends before the #10 and #20 gets executed. In
Switch TB some situations, we need to wait until all the threads got finished to start the next
task. Using wait fork, will block the  till all the child processes complete.
RVM Switch TB
RVM Ethernet sample   
EXAMPLE:
   program main();
Specman E    initial begin
Interview Questions     #(10);
       $display(" BEFORE fork  time = %0d ",$time ); 
       fork
           begin
               # (20);
               $display(" time = %0d # 20  ",$time );
           end
           begin
               #(10);
               $display(" time = %0d # 10  ",$time );
           end

http://testbench.in/SV_27_FORK_CONTROL.html[9/26/2012 2:05:22 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

           begin
               #(5);
               $display(" time = %0d # 5  ",$time );
           end
         join_any
    $display(" time = %0d Outside the main fork ",$time );
    wait fork ;
    $display(" time = %0d  After wait fork ",$time );

   end 
   endprogram
RESULTS

 BEFORE fork  time = 10
 time = 15 # 5  
 time = 15 Outside the main fork
 time = 20 # 10  
 time = 30 # 20  
 time = 30  After wait fork

Disable Fork Statement

The disable fork statement terminates all active descendants (subprocesses) of the
calling process.

In other words, if any of the child processes have descendants of their own, the
disable fork statement shall terminate them as well. Sometimes, it is required to kill
the child processes after certain condition.

EXAMPLE
   program main();

   initial begin
    #(10);
       $display(" BEFORE fork  time = %0d ",$time ); 
       fork
           begin
               # (20);
               $display(" time = %0d # 20  ",$time );
           end
           begin
               #(10);
               $display(" time = %0d # 10  ",$time );
           end
           begin
               #(5);
               $display(" time = %0d # 5  ",$time );
           end
         join_any
    $display(" time = %0d Outside the main fork ",$time );
   end 

   initial
   #100 $finish;
   endprogram
RESULTS

http://testbench.in/SV_27_FORK_CONTROL.html[9/26/2012 2:05:22 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

 BEFORE fork  time = 10
 time = 15 # 5  
 time = 15 Outside the main fork
 time = 20 # 10  
 time = 30 # 20  

In the following example, disable for kills the threads #10 and #20.

EXAMPLE
   program main();

   initial begin
    #(10);
       $display(" BEFORE fork  time = %0d ",$time ); 
       fork
           begin
               # (20);
               $display(" time = %0d # 20  ",$time );
           end
           begin
               #(10);
               $display(" time = %0d # 10  ",$time );
           end
           begin
               #(5);
               $display(" time = %0d # 5  ",$time );
           end
         join_any
    $display(" time = %0d Outside the main fork ",$time );
    disable fork;
    $display(" Killed the child processes");
   end 

   initial
   #100 $finish;
   endprogram
RESULTS

 BEFORE fork  time = 10
 time = 15 # 5  
 time = 15 Outside the main fork
 Killed the child processes

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SV_27_FORK_CONTROL.html[9/26/2012 2:05:22 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS SUBROUTINES Index


Introduction
SystemVerilog Data Types
Verification Begin End Literals
Strings
Constructs With SystemVerilog, multiple statements can be written between the task declaration Userdefined Datatypes
Interface and endtask, which means that the begin .... end can be omitted. If begin .... end is Enumarations
omitted, statements are executed sequentially, the same as if they were enclosed in Structures And Uniouns
OOPS Typedef
a begin .... end group. It shall also be legal to have no statements at all.
Randomization Arrays
Array Methods
Functional Coverage Dynamic Arrays
Tasks:
Assertion Associative Arrays
A Verilog task declaration has the formal arguments either in parentheses or in Queues
DPI Comparison Of Arrays
declaration.
UVM Tutorial Linked List
    task mytask1 (output int x, input logic y); Casting
VMM Tutorial Data Declaration
OVM Tutorial With SystemVerilog, there is a default direction of input if no direction has been Reg And Logic
specified. Once a direction is given, subsequent formals default to the same direction. Operators 1
Easy Labs : SV
In the following example, the formal arguments a and b default to inputs, and u and v Operators 2
Easy Labs : UVM are both outputs. Operator Precedency
Events
Easy Labs : OVM
    task mytask3(a, b, output logic [15:0] u, v); Control Statements
Easy Labs : VMM Program Block
AVM Switch TB Procedural Blocks
Return In Tasks Fork Join
VMM Ethernet sample Fork Control
In Verilog, a task exits when the endtask is reached. With SystemVerilog, the return Subroutines
statement can be used to exit the task before the endtask keyword. Semaphore
Verilog Mailbox
In the following example, Message "Inside Task : After return statement" is not Fine Grain Process
Verification
executed because the task exited before return statement. Control
Verilog Switch TB
Basic Constructs Report a Bug or Comment
EXAMPLE on This section - Your
program main(); input is what keeps
Testbench.in improving
OpenVera     task task_return(); with time!
Constructs         $display("Inside Task : Before return statement");
Switch TB         return;
        $display("Inside Task : After return statement");
RVM Switch TB     endtask
RVM Ethernet sample
    initial
        task_return();
Specman E endprogram
Interview Questions
RESULT:

Inside Task : Before return statement

Functions:

     function logic [15:0] myfunc1(int x, int y);

http://testbench.in/SV_28_SUBROUTINES.html[9/26/2012 2:05:29 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

Function declarations default to the formal direction input if no direction has been
specified. Once a direction is given, subsequent formals default to the same direction.
In the following example, the formal arguments a and b default to inputs, and u and v
are both outputs:

     function logic [15:0] myfunc3(int a, int b, output logic [15:0] u, v);

Return Values And Void Functions::

SystemVerilog allows functions to be declared as type void, which do not have a


return value. For nonvoid functions, a value can be returned by assigning the function
name to a value, as in Verilog, or by using return with a value. The return statement
shall override any value assigned to the function name. When the return statement is
used, nonvoid functions must specify an expression with the return.

EXAMPLE:
   function [15:0] myfunc2 (input [7:0] x,y);
     return x * y - 1; //return value is specified using return statement
   endfunction
   // void functions
   function void myprint (int a);

Pass By Reference:

In verilog,method arguments takes as pass by value.The inputs are copyed when the
method is called and the outputs are assigned to outputs when exiting the method.In
SystemVerilog ,methods can have pass by reference.Arguments passed by reference
are not copied into the subroutine area, rather, a reference to the original argument
is passed to the subroutine. The subroutine can then access the argument data via the
reference.

In the following example, variable a is changed at time 10,20 and 30. The method
pass_by_val , copies only the value of the variable a, so the changes in variable a
which are occurred after the task pass_by_val call, are not visible to pass_by_val.
Method pass_by_ref is directly referring to the variable a. So the changes in variable a
are visible inside pass_by_ref.

EXAMPLE:

program main();
int a;

     initial
        begin
         #10 a = 10;
         #10 a = 20;
         #10 a = 30;
         #10 $finish;
        end

     task pass_by_val(int i);
       forever
            @i $display("pass_by_val: I is %0d",i);
     endtask

http://testbench.in/SV_28_SUBROUTINES.html[9/26/2012 2:05:29 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

     task pass_by_ref(ref int i);
       forever
            @i $display("pass_by_ref: I is %0d",i);
     endtask

     initial
        pass_by_val(a);

     initial
        pass_by_ref(a);

endprogram

RESULT

pass_by_ref: I is 10
pass_by_ref: I is 20
pass_by_ref: I is 30

Default Values To Arguments:

SystemVerilog allows to declare default values to arguments.When the subrotunies


are called,arguments those are omited,will take default value.

EXAMPLE:
 
    program main();
    
         task display(int a = 0,int b,int c = 1 );
            $display(" %0d %0d %0d ",a,b,c);
         endtask
        
        
         initial
         begin
            display( , 5 );     // is equivalent to display( 0, 5, 1 );
            display( 2, 5 );    // is equivalent to display( 2, 5, 1 );
            display( , 5, );    // is equivalent to display( 0, 5, 1 );
            display( , 5, 7 );  // is equivalent to display( 0, 5, 7 );
            display( 1, 5, 2 ); // is equivalent to display( 1, 5, 2 );
         end
    
     endprogram 
RESULT:

 0 5 1
 2 5 1
 0 5 1
 0 5 7
 1 5 2

Argument Binding By Name

SystemVerilog allows arguments to tasks and functions to be bound by name as well


as by position. This allows specifying non-consecutive default arguments and easily
specifying the argument to be passed at the call.

EXAMPLE:

program main();

     function void fun( int j = 1, string s = "no" );


         $display("j is %0d : s is %s ",j,s);
     endfunction

     initial
     begin
         fun( .j(2), .s("yes") ); // fun( 2, "yes" );
         fun( .s("yes") ); // fun( 1, "yes" );

http://testbench.in/SV_28_SUBROUTINES.html[9/26/2012 2:05:29 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

         fun( , "yes" ); // fun( 1, "yes" );


         fun( .j(2) ); // fun( 2, "no" );
         fun( .s("yes"), .j(2) ); // fun( 2, "yes" );
         fun( .s(), .j() ); // fun( 1, "no" );
         fun( 2 ); // fun( 2, "no" );
         fun( ); // fun( 1, "no" );
     end

endprogram

RESULT

j is 2 : s is yes
j is 1 : s is yes
j is 1 : s is yes
j is 2 : s is no
j is 2 : s is yes
j is 1 : s is no
j is 2 : s is no
j is 1 : s is no

Optional Argument List

When a task or function specifies no arguments, the empty parenthesis, (), following
the task/function name shall be optional. This is also true for tasks or functions that
require arguments, when all arguments have defaults
specified.

EXAMPLE
program main();

     function void fun( );
         $display("Inside function");
     endfunction

     initial
     begin
         fun( );
         fun;
     end

endprogram

RESULT

Inside function
Inside function

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SV_28_SUBROUTINES.html[9/26/2012 2:05:29 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS SEMAPHORE Index


Introduction
SystemVerilog Data Types
Verification Conceptually, a semaphore is a bucket. When a semaphore is allocated, a bucket that Literals
contains a fixed number of keys is created. Processes using semaphores must first Strings
Constructs procure a key from the bucket before they can continue to execute. If a specific Userdefined Datatypes
Interface process requires a key, only a fixed number of occurrences of that process can be in Enumarations
progress simultaneously. All others must wait until a sufficient number of keys is Structures And Uniouns
OOPS Typedef
returned to the bucket. Semaphores are typically used for mutual exclusion, access
Randomization control to shared resources, and basic synchronization. Arrays
Array Methods
Functional Coverage Dynamic Arrays
Semaphore is a built-in class that provides the following methods:
Assertion   --  Create a semaphore with a specified number of keys: new() Associative Arrays
  --  Obtain one or more keys from the bucket: get() Queues
DPI Comparison Of Arrays
  --  Return one or more keys into the bucket: put()
UVM Tutorial   --  Try to obtain one or more keys without blocking: try_get() Linked List
Casting
VMM Tutorial Data Declaration
OVM Tutorial EXAMPLE:semaphore Reg And Logic
program main ; Operators 1
Easy Labs : SV
semaphore sema = new(1); Operators 2
Easy Labs : UVM initial begin Operator Precedency
   repeat(3) begin Events
Easy Labs : OVM
        fork Control Statements
Easy Labs : VMM             ////////// PROCESS 1 //////////////// Program Block
AVM Switch TB              begin Procedural Blocks
                $display("1: Waiting for key"); Fork Join
VMM Ethernet sample                 sema.get(1); Fork Control
                $display("1: Got the Key"); Subroutines
                #(10);// Do some work             Semaphore
Verilog                 sema.put(1); Mailbox
                $display("1: Returning back key "); Fine Grain Process
Verification
                #(10); Control
Verilog Switch TB              end 
Basic Constructs             ////////// PROCESS 2 //////////////// Report a Bug or Comment
             begin on This section - Your
                $display("2: Waiting for Key"); input is what keeps
                 sema.get(1); Testbench.in improving
OpenVera                  $display("2: Got the Key"); with time!
Constructs                  #(10);//Do some work
Switch TB                  sema.put(1);
                $display("2: Returning back key ");
RVM Switch TB                  #(10);
RVM Ethernet sample              end 
        join
    end
     #1000; 
Specman E end      
Interview Questions endprogram

RESULTS:

1: Waiting for key


1: Got the Key
2: Waiting for Key
1: Returning back key
2: Got the Key
2: Returning back key
1: Waiting for key

http://testbench.in/SV_29_SEMAPHORE.html[9/26/2012 2:05:38 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

1: Got the Key


2: Waiting for Key
1: Returning back key
2: Got the Key
2: Returning back key
1: Waiting for key
1: Got the Key
2: Waiting for Key
1: Returning back key
2: Got the Key
2: Returning back key

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SV_29_SEMAPHORE.html[9/26/2012 2:05:38 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS MAILBOX Index


Introduction
SystemVerilog Data Types
Verification A mailbox is a communication mechanism that allows messages to be exchanged Literals
between processes. Data can be sent to a mailbox by one process and retrieved by Strings
Constructs another. Userdefined Datatypes
Interface Enumarations
Mailbox is a built-in class that provides the following methods: Structures And Uniouns
OOPS Typedef
--Create a mailbox: new()
Randomization --Place a message in a mailbox: put() Arrays
--Try to place a message in a mailbox without blocking: try_put() Array Methods
Functional Coverage Dynamic Arrays
--Retrieve a message from a mailbox: get() or peek()
Assertion --Try to retrieve a message from a mailbox without blocking: try_get() or try_peek() Associative Arrays
--Retrieve the number of messages in the mailbox: num() Queues
DPI Comparison Of Arrays
UVM Tutorial EXAMPLE: Linked List
   program meain ; Casting
VMM Tutorial Data Declaration
   mailbox my_mailbox;
OVM Tutorial    initial begin Reg And Logic
       my_mailbox = new(); Operators 1
Easy Labs : SV
       if (my_mailbox) Operators 2
Easy Labs : UVM        begin Operator Precedency
           fork Events
Easy Labs : OVM
               put_packets(); Control Statements
Easy Labs : VMM                get_packets(); Program Block
AVM Switch TB                #10000; Procedural Blocks
           join_any Fork Join
VMM Ethernet sample        end Fork Control
   Subroutines
       #(1000); Semaphore
Verilog       $display("END of Program"); Mailbox
   end Fine Grain Process
Verification
   Control
Verilog Switch TB    task put_packets();
Basic Constructs    integer i; Report a Bug or Comment
   begin  on This section - Your
       for (i=0; i<10; i++) input is what keeps
       begin Testbench.in improving
OpenVera            #(10); with time!
Constructs            my_mailbox.put(i);
Switch TB                $display("Done putting packet %d @time %d",i, $time);
          
RVM Switch TB        end
RVM Ethernet sample    end
   endtask
  
   task get_packets();
Specman E    integer i,packet;
Interview Questions    begin
       for (int i=0; i<10; i++)
       begin
           my_mailbox.get(packet);
           $display("Got packet %d @time %d", packet, $time);
       end
   end
   endtask
   endprogram

RESULTS:

http://testbench.in/SV_30_MAILBOX.html[9/26/2012 2:05:47 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

   Done putting packet           0 @time                   10


   Got packet                    0 @time                   10
   Done putting packet           1 @time                   20
   Got packet                    1 @time                   20
   Done putting packet           2 @time                   30
   Got packet                    2 @time                   30
   Done putting packet           3 @time                   40
   Got packet                    3 @time                   40
   Done putting packet           4 @time                   50
   Got packet                    4 @time                   50
   Done putting packet           5 @time                   60
   Got packet                    5 @time                   60
   Done putting packet           6 @time                   70
   Got packet                    6 @time                   70
   Done putting packet           7 @time                   80
   Got packet                    7 @time                   80
   Done putting packet           8 @time                   90
   Got packet                    8 @time                   90
   Done putting packet           9 @time                  100
   Got packet                    9 @time                  100
   END of Program

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SV_30_MAILBOX.html[9/26/2012 2:05:47 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS FINE GRAIN PROCESS CONTROL Index


Introduction
SystemVerilog A process is a built-in class that allows one process to access and control another Data Types
Verification process once it has started.Users can declare variables of type process and safely pass Literals
them through tasks or incorporate them into other objects. The prototype for the Strings
Constructs process class is: Userdefined Datatypes
Interface Enumarations
  class process; Structures And Uniouns
OOPS Typedef
     enum state { FINISHED, RUNNING, WAITING, SUSPENDED, KILLED };
Randomization Arrays
     static function process self(); Array Methods
Functional Coverage Dynamic Arrays
     function state status();
Assertion      task kill(); Associative Arrays
     task await(); Queues
DPI Comparison Of Arrays
     task suspend();
UVM Tutorial      task resume(); Linked List
  endclass Casting
VMM Tutorial Data Declaration
OVM Tutorial Reg And Logic
Objects of type process are created internally when processes are spawned. Users Operators 1
Easy Labs : SV
cannot create objects of type process; attempts to call new shall not create a new Operators 2
Easy Labs : UVM process, and instead result in an error. The process class cannot be extended. Operator Precedency
Attempts to extend it shall result in a compilation error. Objects of type process are Events
Easy Labs : OVM
unique; they become available for reuse once the underlying process terminates and Control Statements
Easy Labs : VMM all references to the object are discarded. The self() function returns a handle to the Program Block
AVM Switch TB current process, that is, a handle to the process making the call. Procedural Blocks
Fork Join
VMM Ethernet sample The status() function returns the process status, as defined by the state enumeration: Fork Control
Subroutines
FINISHED Process terminated normally. Semaphore
Verilog Mailbox
RUNNING Process is currently running (not in a blocking statement). Fine Grain Process
Verification WAITING Process is waiting in a blocking statement. Control
Verilog Switch TB SUSPENDED Process is stopped awaiting a resume.
KILLED Process was forcibly killed (via kill or disable). Report a Bug or Comment
Basic Constructs
on This section - Your
input is what keeps
Kill Testbench.in improving
OpenVera with time!
Constructs The kill() task terminates the given process and all its sub-processes, that is,
processes spawned using fork statements by the process being killed. If the process to
Switch TB be terminated is not blocked waiting on some other condition, such as an event, wait
RVM Switch TB expression, or a delay then the process shall be terminated at some unspecified time
in the current time step.
RVM Ethernet sample
await

Specman E The await() task allows one process to wait for the completion of another process. It
shall be an error to call this task on the current process, i.e., a process cannot wait
Interview Questions for its own completion.

suspend

The suspend() task allows a process to suspend either its own execution or that of
another process. If the process to be suspended is not blocked waiting on some other
condition, such as an event, wait expression, or a delay then the process shall be
suspended at some unspecified time in the current time step. Calling this method
more than once, on the same (suspended) process, has no effect.

resume

http://testbench.in/SV_31_FINE_GRAIN_PROCESS_CONTROL.html[9/26/2012 2:05:57 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

The resume() task restarts a previously suspended process. Calling resume on a


process that was suspended while blocked on another condition shall re-sensitize the
process to the event expression, or wait for the wait condition to become true, or for
the delay to expire. If the wait condition is now true or the original delay has
transpired, the process is scheduled onto the Active or Reactive region, so as to
continue its execution in the current time step. Calling resume on a process that
suspends itself causes the process to continue to execute at the statement following
the call to suspend.

The example below starts an arbitrary number of processes, as specified by the task
argument N. Next, the task waits for the last process to start executing, and then
waits for the first process to terminate. At that point the parent process forcibly
terminates all forked processes that have not completed yet.

  task do_n_way( int N );  
    process job[1:N];

   for ( int j = 1; j <= N; j++ )


      fork
         automatic int k = j;
         begin job[j] = process::self(); ... ; end
      join_none

   for( int j = 1; j <= N; j++ ) // wait for all processes to start


      wait( job[j] != null );
      job[1].await(); // wait for first process to finish

   for ( int k = 1; k <= N; k++ ) begin


      if ( job[k].status != process::FINISHED )
          job[k].kill();
   end

endtask

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/SV_31_FINE_GRAIN_PROCESS_CONTROL.html[9/26/2012 2:05:57 PM]


WWW.TESTBENCH.IN - SystemVerilog Constructs

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SV_31_FINE_GRAIN_PROCESS_CONTROL.html[9/26/2012 2:05:57 PM]


WWW.TESTBENCH.IN

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS

SystemVerilog Advertise on Testbench


Verification Testbench, founded in 2007, is one of the primary source for HVL's(particularly SV) on
the web with more than 100k page visits per month(source: Site Meter). Testbench is
Constructs dedicated to Verification tutorials with loads of examples.
Interface
OOPS How to Advertise
This screenshot will guide you through a range of advertising opportunities currently
Randomization available on Testbench.
Functional Coverage
Assertion
DPI
UVM Tutorial
VMM Tutorial
OVM Tutorial
Easy Labs : SV
Easy Labs : UVM
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

Verilog
Verification
Verilog Switch TB
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB Ad Requirements & Guidelines:
* You can submit ads in either JPG, GIF, Flash or HTML formats.
RVM Ethernet sample * Ads may not contain nudity or content that is not family safe.
* Ad placement locations shown in the picture are only approximate. Actual
placement location can change due to editorial content length.
Specman E
Interview Questions
For more information, please contact

gopi@testbench.in
naresh@testbench.in

http://testbench.in/adds.html[9/26/2012 2:06:05 PM]


WWW.TESTBENCH.IN

copyright © 2007 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/adds.html[9/26/2012 2:06:05 PM]


WWW.TESTBENCH.IN - Systemverilog Interface

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INTERFACE Index


Interface
SystemVerilog Ports
Verification The communication between blocks of a digital system is a critical area. In Verilog, Interface Methods
modules are connected using module ports. For large modules, this is not productive Clocking Block
Constructs as it involves Virtual Interface
Interface Svtb N Verilog Dut
OOPS Manually connecting hundreds of ports may lead to errors.
Report a Bug or Comment
Detailed knowledge of all the port is required.
Randomization on This section - Your
Difficult to change if the design changes. input is what keeps
Functional Coverage More time consuming. Testbench.in improving
Assertion Most port declaration work is duplicated in many modules. with time!
DPI Let us see a verilog example:
UVM Tutorial
   module Dut (input clk, read, enable,
VMM Tutorial                Input [7:0] addr, 
OVM Tutorial                output [7:0] data);
      ....
Easy Labs : SV       assign data = temp1 ? temp2 : temp3 ;
Easy Labs : UVM       always @(posedge clk)
      ....
Easy Labs : OVM
   endmodule
Easy Labs : VMM   
AVM Switch TB
   module Testbench(input clk, 
               Output read, enable,
VMM Ethernet sample                output [7:0] addr, 
               input [7:0] data );
   endmodule
Verilog
Verification Integrating the above two modules in top module.
Verilog Switch TB
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

1  module top();
2      reg clk; 
3      wire read, enable; 
4      wire [7:0] addr; 
5      wire [7:0] data;
6

http://testbench.in/IF_01_INTERFACE.html[9/26/2012 2:06:13 PM]


WWW.TESTBENCH.IN - Systemverilog Interface

7      Dut D (clk,read,enable,Addr,data); 
8
9      Testbench TB(clk,read,enable,Addr,data); 
10    
11 endmodule

All the connection clk, read, enable, addr, data are done manually.  Line 7 and 9 has
same code structure which is duplicating work. If a new port is added, it needs
changes in DUT ports, TestBench Ports, and in 7, 10 lines of Top module.  This is time-
consuming and maintaining it is complex as the port lists increases.

To resolve the above issues, SystemVerilog added a new powerful features called
interface. Interface encapsulates the interconnection and communication between
blocks.

Interface declaration for the above example:

   interface intf #(parameter BW = 8)(input clk);
      logic read, enable;
      logic [BW -1 :0] addr,data;
   endinterface :intf

Here the signals read, enable, addr, data are grouped in to "intf".  Interfaces can have
direction as input, output and inout also. In the above example, clk signal is used as
input to interface. Interfaces can also have parameters like modules. Interface
declaration is just like a module declaration. Uses keywords interface, endinterface
for defining. Inside a module, use hierarchical names for signals in an interface.

TIP: Use wire type in case of multiple drivers.   Use logic type in case of a single
driver.

Let use see the DUT and Testbench modules using the above declared interface.

   module Dut (intf dut_if); // declaring the interface


  
      always @(posedge dut_if.clk)
         if(dut_if.read) // sampling the signal
            $display(" Read is asserted");

   endmodule
      
   module Testbench(intf tb_if);

      initial
      begin
         tb_if.read = 0;
         repeat(3) #20 tb_if.read = ~tb_if.read;// driving a signal
         $finish;
      end

   endmodule

Integrating the above two modules in top module.

http://testbench.in/IF_01_INTERFACE.html[9/26/2012 2:06:13 PM]


WWW.TESTBENCH.IN - Systemverilog Interface

    module top();
       bit clk;

       initial
           forever #5 clk = ~clk;

       intf bus_if(clk); // interface instantiation


       Dut d(bus_if); // use interface for connecting D and TB
       Testbench TB (bus_if);

    endmodule
    

See, how much code we got reduced in this small example itself. In the above
example, I demonstrated the connectivity between DUT and TestBench. Interfaces can
also be used for connectivity between the DUT sub modules also.

Advantages Of Using Inteface:

An interface can be passed as single item.


It allows structured information flow between blocks.
It can contain anything that could be in a module except other module definitions
or instance.
Port definitions are independent from modules.
Increases the reusability.
It Interface can be declared in a separate file and can be compiled separately.
Interfaces can contain tasks and functions; with this methods shared by all modules
connecting to this information can be in one place.
Interface can contain protocol checking using assertions and functional coverage
blocks.
Reduces errors which can cause during module connections.
Easy to add or remove a signal. Easy maintainability.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/IF_01_INTERFACE.html[9/26/2012 2:06:13 PM]


WWW.TESTBENCH.IN - Systemverilog Interface

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PORTS Index


Interface
SystemVerilog Interface Ports Ports
Verification Interface Methods
Clocking Block
Constructs In the previous example, signal clk is declared as port to the interface. Interface Ports Virtual Interface
Interface work similar to the module ports. Members of port list can be connected externally by Svtb N Verilog Dut
name or position when the interface is instantiated as shown in line 3 of module top
OOPS Report a Bug or Comment
code.  
Randomization on This section - Your
input is what keeps
Functional Coverage Testbench.in improving
Modports
Assertion with time!
DPI In the above example, we did not mention the direction of signals. The direction of
the clk signal in input for both the  Dut and Testbench modules. But for the rest of
UVM Tutorial the signals, the direction is not same.  To specify the direction of the signal w.r.t
VMM Tutorial module which uses interface instead of port list, modports are used. Modport restrict
interface access within a module based on the direction declared. Directions of
OVM Tutorial signals are specified as seen from the module. In the modeport list, only signal names
Easy Labs : SV are used.
Easy Labs : UVM Let us see the modport usage with the previous example.  2 mod port definitions are
Easy Labs : OVM needed, one for DUT and other for TestBench.
Easy Labs : VMM Interface declaration for the above example:
AVM Switch TB
    interface intf (input clk);
VMM Ethernet sample         logic read, enable,
        logic [7:0] addr,data;
        
Verilog         modport dut (input read,enable,addr,output data);
Verification         modport tb (output read,enable,addr,input data);
    endinterface :intf
Verilog Switch TB
Basic Constructs
In this example, the modport name selects the appropriate directional information for
the interface signals accessed in the module header.  Modport selection can be done
in two ways. One at Module declaration , other at instantication.
OpenVera
Constructs
Switch TB Modport Selection Duing Module Definition.
RVM Switch TB     module Dut (intf.dut dut_if); // declaring the interface with modport
RVM Ethernet sample          ....
         assign dut_if.data = temp1 ? temp2 : temp3 ; // using the signal in interface
         always @(posedge intf.clk)
         ....
Specman E     endmodule
Interview Questions     
    module Testbench(intf.tb tb_if);
          .....
          .....
    endmodule
    
    1 module top();
    2     logic clk;
    3     intf bus_if(clk); // interface instantiation
    4     Dut d(bus_if); // Pass the interface
    5     Testbench TB (Bus_if); // Pass the interface

http://testbench.in/IF_02_PORTS.html[9/26/2012 2:06:22 PM]


WWW.TESTBENCH.IN - Systemverilog Interface

    6 endmodule 

Modport Selection Duing Module Instance.

     module Dut (intf dut_if); // declaring the interface


         ....
         assign dut_if.data = temp1 ? temp2 : temp3 ; // using the signal in interface
         always @(posedge intf.clk)
         ....
     endmodule
    
     module Testbench(intf tb_if);
         .....
         .....
     endmodule
    
     1 module top();
     2      logic clk;
     3      intf bus_if(clk); // interface instantiation
     4      Dut d(bus_if.dut); // Pass the modport into the module
     5      Testbench TB (Bus_if.tb); // Pass the modport into the module
     6 endmodule 

A mod port can also define expressions. They can also define their own names. Module
can use the modport declared name. For example

    modport dut (input read,enable,.addr(2),output .d(data[1:5]);
    
    module dut(intf.dut  dut_if);
    assign  dut_if.d = temp; // using the signal name declared by modport.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/IF_02_PORTS.html[9/26/2012 2:06:22 PM]


WWW.TESTBENCH.IN - Systemverilog Interface

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INTERFACE METHODS Index


Interface
SystemVerilog Methods In Interfaces Ports
Verification Interface Methods
Interfaces can include task and function definitions. This allows a more abstract level Clocking Block
Constructs of modeling. Virtual Interface
Interface Svtb N Verilog Dut
OOPS Report a Bug or Comment
     interface intf (input clk);
Randomization          logic read, enable, on This section - Your
         logic [7:0] addr,data; input is what keeps
Functional Coverage Testbench.in improving
        
Assertion          task masterRead(input logic [7:0] raddr); // masterRead method with time!
DPI             ...
         endtask: masterRead
UVM Tutorial         
VMM Tutorial          task slaveRead; // slaveRead method
          ...
OVM Tutorial          endtask: slaveRead
Easy Labs : SV
     endinterface :intf
Easy Labs : UVM
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

Verilog
Verification
Verilog Switch TB
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/IF_03_INTERFACE_METHODS.html[9/26/2012 2:06:29 PM]


WWW.TESTBENCH.IN - Systemverilog Interface

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/IF_03_INTERFACE_METHODS.html[9/26/2012 2:06:29 PM]


WWW.TESTBENCH.IN - Systemverilog Interface

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS CLOCKING BLOCK Index


Interface
SystemVerilog Clocking Blocks Ports
Verification Interface Methods
SystemVerilog adds the clocking block that identifies clock signals, and captures the Clocking Block
Constructs timing and synchronization requirements of the blocks being modeled. A clocking Virtual Interface
Interface block assembles signals that are synchronous to a particular clock, and makes their Svtb N Verilog Dut
timing explicit. The clocking block is a key element in a cycle-based methodology,
OOPS
which enables users to write testbenches at a higher level of abstraction. Simulation Report a Bug or Comment
Randomization is faster with cycle based methodology. on This section - Your
input is what keeps
Functional Coverage
Depending on the environment, a testbench can contain one or more clocking blocks, Testbench.in improving
Assertion each containing its own clock plus an arbitrary number of signals. These operations with time!
DPI are as follows:

UVM Tutorial    Synchronous events


VMM Tutorial    Input sampling
OVM Tutorial    Synchronous drives
 
Easy Labs : SV
Easy Labs : UVM
    clocking cb @(posedge clk);
Easy Labs : OVM         default input #10ns output #2ns;
Easy Labs : VMM
        output read,enable,addr;
AVM Switch TB         input negedge data;
VMM Ethernet sample     endclocking

In the above example, the first line declares a clocking block called cb that is to be
Verilog clocked on the positive edge of the signal clk. The second line specifies that by
Verification default all signals in the clocking block shall use a 10ns input skew and a 2ns output
Verilog Switch TB skew by default. The next line adds three output signals to the clocking block: read,
enable and addr. The fourth line adds the signal data to the clocking block as input.
Basic Constructs Fourth line also contains negedge which overrides the  skew ,so that data is sampled
on the negedge of the clk.

OpenVera
Constructs
Skew

Switch TB If an input skew is specified then the signal is sampled at skew time units before the
RVM Switch TB clock event. If output skew is specified, then output (or inout) signals are driven skew
time units after the corresponding clock event. A skew must be a constant expression,
RVM Ethernet sample and can be specified as a parameter.

Specman E
Interview Questions

http://testbench.in/IF_04_CLOCKING_BLOCK.html[9/26/2012 2:06:38 PM]


WWW.TESTBENCH.IN - Systemverilog Interface

Skew can be specified in 3 ways.


  #d : The skew is d time units. The time unit depends on the timescale of the block.
  #dns : The skew is d nano seconds.
  #1step :  Sampling is done in the preponed region of current time stamp.

If skew is not specified, default input skew is 1step and output skew is 0.

Specifying a clocking block using a SystemVerilog interface can significantly reduce


the amount of code needed to connect the TestBench without race condition.
Clocking blocks add an extra level of signal hierarchy while accessing signals.

Interface declaration with clocking block:

     interface intf (input clk);


          logic read, enable,
          logic [7:0] addr,data;
          
          clocking cb @(posedge clock); // clocking block for testbench
              default input #10ns output #2ns;

              output read,enable,addr;
              input data;
          endclocking
          
          modport dut (input read,enable,addr,output data);
          modport tb (clocking cb); // synchronous testbench modport

     endinterface :intf
    
     module testbench(intf.tb tb_if);
          ......
          initial
          tb_if.cb.read <= 1; //writing to synchronous signal read
          ...
     endmodule

Cycle Delay

The ## operator can be used to delay execution by a specified number of clocking


events, or clock cycles. What constitutes a cycle is determined by the default clocking
in effect of module, interface, or program.

## <integer_expression>; 
##3; // wait 3 cycles
##1 tb_if.addr <= 8'h00;// waits for 1 cycle and then writes address.

Using clocking blocks,cycle delays syntax gets reduced.


Insted of writing

   repeat(3) @(posedge clock); sync_block.a <= 1;

Just use

   ##3 sync_block.a <= 1;

To schedule the assignment after 3 clocks,Just use,

   sync_block.a <= ##3 1;

To simply wait for 3 clock cycles,

   ##3; can be used.

But there may be more than one clocking block is defined in a project.

http://testbench.in/IF_04_CLOCKING_BLOCK.html[9/26/2012 2:06:38 PM]


WWW.TESTBENCH.IN - Systemverilog Interface

##3 waits for 3 clocks cycles,of the block which is defined as default.

   default clocking sync_block @(posedge clock);

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/IF_04_CLOCKING_BLOCK.html[9/26/2012 2:06:38 PM]


WWW.TESTBENCH.IN - Systemverilog Interface

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS VIRTUAL INTERFACE Index


Interface
SystemVerilog Virtual Interfaces Ports
Verification Interface Methods
Virtual interfaces provide a mechanism for separating abstract models and test Clocking Block
Constructs programs from the actual signals that make up the design.  A virtual interface allows Virtual Interface
Interface the same subprogram to operate on different portions of a design, and to dynamically Svtb N Verilog Dut
control the set of signals associated with the subprogram. Instead of referring to the
OOPS Report a Bug or Comment
actual set of signals directly, users are able to manipulate a set of virtual signals.
Randomization on This section - Your
input is what keeps
Functional Coverage Testbench.in improving
    1 module testbench(intf.tb tb_if);
Assertion     2     virtual interface intf.tb local_if; // virtual interface. with time!
DPI     3       ....
    4     task read(virtual interface intf.tb l_if) // As argument to task
UVM Tutorial     5       ....
VMM Tutorial     6     initial
    7     begin
OVM Tutorial     8         Local_if = tb_if; // initializing virtual interface.
Easy Labs : SV     9         Local_if.cb.read <= 1; //writing to synchronous signal read
    10        read(Local_if); // passing interface to task.
Easy Labs : UVM     11    end
Easy Labs : OVM     12 endmodule
Easy Labs : VMM
AVM Switch TB In the above program, local_if is just like a pointer. It represents an interface
instance. Using keyword "virtual" , virtual interfaces instance is created. It does not
VMM Ethernet sample have any signal. But it can hold physical interface. Tb_if is the physical interface
which is allocated during compilation time. You can drive and sample the signals in
physical interface. In line 8, the physical interface tb_if is assigned to local_if. With
Verilog this , we can drive and sample the physical signals. In line 9, read signal of tb_if is
Verification accessed using local_if.
Verilog Switch TB
Basic Constructs Advantages Of Virtual Interface

1)      Virtual interface can be used to make the TestBench independent of the


physical interface. It allows developing the test component independent of the DUT
OpenVera port while working with multi port protocol.
Constructs 2)      With virtual interface, we can change references to physical interface
Switch TB dynamically. Without virtual interfaces, all the connectivity is determined during
compilation time, and therefore can't be randomized or reconfigured.
RVM Switch TB 3)      In multi port environment, it allows to access the physical interfaces using array
RVM Ethernet sample index.
4)      Physical interfaces are not allowed in object oriented programming, as physical
interface is allocated at compilation time itself. Virtual interface which are set at run
time allows to do object oriented programming with signals rather than just with
Specman E variables.
Interview Questions 5)      Virtual interface variables can be passed as arguments to tasks, functions, or
methods.
6)      Allows to use Equality ( == ) and inequality ( != ) .
 
A virtual interface must be initialized before it can be used, by default, it points to
null. Attempting to use an uninitialized virtual interface will result in a run-time
error.

Multi Bus Interface

http://testbench.in/IF_05_VIRTUAL_INTERFACE.html[9/26/2012 2:06:47 PM]


WWW.TESTBENCH.IN - Systemverilog Interface

If you are working on protocol which has multiple sub bus protocol, there are several
ways to create interfaces.  

    One Big single interface with all the sub protocol signals inside it. With single
interface, it is easy to pass around the whole system. You have to name all the signals
with the sub protocol prefix like pcie_enable, Eth_enable etc. Restrict the access
using clocking blocks else all signals can be accessed by all the modules using this
interface. Reusability will be very less as all the sub protocols are in one interface.

    Using multiple interfaces, one for each sub protocol, each interface for each sub
bus will increase the complexity while passing around the system.  No need to prefix
the sub protocol name as the sub protocol name is reflected in the interface name
itself. With this you can only pass the sub interfaces required by other modules. All
the interfaces will be reusable as each interface represents an individual protocol.

    Using one big interface with sub multiple interfaces will be easy for passing
around the system. With this the sub interfaces can be reused for other components
and other designs.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/IF_05_VIRTUAL_INTERFACE.html[9/26/2012 2:06:47 PM]


WWW.TESTBENCH.IN - Systemverilog Interface

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS SVTB N VERILOG DUT Index


Interface
SystemVerilog Working With Verilog Dut: Ports
Verification Interface Methods
There are several ways to connect the Verilog DUT to SystemVerilog TestBench. Clocking Block
Constructs Verilog DUT has port list where as SystemVerilog testbenchs uses interfaces.  We will Virtual Interface
Interface discuss 2 ways of connecting Verilog DUT to SystemVerilog TestBench. Svtb N Verilog Dut
OOPS Report a Bug or Comment
Randomization Connecting In Top: on This section - Your
input is what keeps
Functional Coverage
Verilog port list can be connected during DUT instantiation using interface hibachi Testbench.in improving
Assertion signal names as shown in following code. with time!
DPI
    // DUT in Verilog
UVM Tutorial     module Dut (input clk, read, enable,
VMM Tutorial                 Input [7:0] addr, 
                output [7:0] data);
OVM Tutorial          ....
Easy Labs : SV          assign data = temp1 ? temp2 : temp3 ;
         always @(posedge clk)
Easy Labs : UVM          ....
Easy Labs : OVM     endmodule
    
Easy Labs : VMM     // SystemVerilog Code
AVM Switch TB   //  interface declaration with clocking block:
    interface intf (input clk);
VMM Ethernet sample          logic read, enable,
         logic [7:0] addr,data;
    endinterface
Verilog     
Verification     module testbench(intf.tb tb_if);
    .....
Verilog Switch TB     endmodule
Basic Constructs     
    // integrating in top module.
    
    module top();
OpenVera         logic clk;
Constructs
Switch TB         intf bus_if(clk); // interface instantiation
        Testbench TB (bus_if); // Pass the modport into the module
RVM Switch TB         Dut d(.clk(clk),          // connect the verilog
RVM Ethernet sample               .read(bus_if.read), // RTL port using interface hierarchy signal name.
              .enable(bus_if.enable),
              .addr(bus_if.addr),
              .data(bus_if.data);  
Specman E
Interview Questions     endmodule 

Connecting Using A Wrapper

We can also convert the verilog module with port list in to SystemVerilog module with
interface by creating wrapper around the verilog module.

    //wrapper for verilog DUT


    module w_dut(intf wif);
        Dut d(.clk(wif.clk),          // connect the verilog

http://testbench.in/IF_06_SVTB_N_VERILOG_DUT.html[9/26/2012 2:06:56 PM]


WWW.TESTBENCH.IN - Systemverilog Interface

               .read(wif.read), // RTL port using interface hierarchy signal name.


               .enable(wif.enable),
               .addr(wif.addr),
               .data(wif.data);  
    endmodule
    //connecting the dut wrapper and testbench in top.
    module top();
        logic clk;
        intf bus_if(clk); // interface instantiation
        w_dut d(bus_if); // instance of dut wrapper
        Testbench TB (Bus_if); 
    endmodule 

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/IF_06_SVTB_N_VERILOG_DUT.html[9/26/2012 2:06:56 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INTRODUCTION Index


Introduction
SystemVerilog Brief Introduction To Oop Class
Verification Object
Unlike procedural programming, here in the OOP programming model programs are This
Constructs organized around objects and data rather than actions and logic. Objects represent Inheritance
Interface some concepts or things and like any other objects in the real Objects in programming Encapsulation
language have certain behavior, properties, type, and identity. In OOP based language Polymorphism
OOPS Abstract Classes
the principal aim is to find out the objects to manipulate and their relation between
Randomization each other. OOP offers greater flexibility and compatibility then procedural language Parameterised Class
like verilog. Nested Classes
Functional Coverage Constant
Assertion Objects are key to understanding object-oriented technology. Look around right now Static
and you'll find many examples of real-world objects: your system, your desk, your Casting
DPI Copy
chair.
UVM Tutorial Scope Resolution
Real-world objects share two characteristics: They all have state and behavior. Operator
VMM Tutorial Null
System have state (name, color) and behavior (playing music,switch off). Identifying
OVM Tutorial the state and behavior for real-world objects is a great way to begin thinking in terms External Declaration
of object-oriented programming. Classes And Structures
Easy Labs : SV
Typedef Class
Easy Labs : UVM SystemVerilog is a object oriented programming  and to understand the functionality Pure
of OOP in SystemVerilog, we first need to understand several fundamentals related to Other Oops Features
Easy Labs : OVM
objects. These include class, method, inheritance, encapsulation, abstraction, Misc
Easy Labs : VMM polymorphism etc.
AVM Switch TB Report a Bug or Comment
Class on This section - Your
VMM Ethernet sample input is what keeps
 It is the central point of OOP and that contains data and codes with behavior. In Testbench.in improving
SystemVerilog OOPS , everything happens within class and it describes a set of objects with time!
Verilog with common behavior. The class definition describes all the properties, behavior, and
Verification identity of objects present within that class.    
Verilog Switch TB
Basic Constructs Object

 Objects are the basic unit of object orientation with behavior, identity. As we
mentioned above, these are part of a class but are not the same. An object is
OpenVera expressed by the variable and methods within the objects. Again these variables and
Constructs methods are distinguished from each other as instant variables, instant methods and
Switch TB class variable and class methods.
RVM Switch TB
RVM Ethernet sample Methods

 We know that a class can define both attributes and behaviors. Again attributes are
defined by variables and behaviors are represented by methods. In other words,
Specman E methods define the abilities of an object.
Interview Questions

Inheritance

 This is the mechanism of organizing and structuring program. Though objects are
distinguished from each other by some additional features but there are objects that
share certain things common. In object oriented programming classes can inherit some
common behavior and state from others. Inheritance in OOP allows to define a general
class and later to organize some other classes simply adding some details with the old
class definition. This saves work as the special class inherits all the properties of the
old general class and as a programmer you only require the new features. This helps

http://testbench.in/CL_01_INTRODUCTION.html[9/26/2012 2:07:04 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

in a better data analysis, accurate coding and reduces development time. In Verilog ,
to write a new definition using the exesisting definitioan is done inserting `ifdef
conpilation controls into the exesisting code.  

Abstraction

 The process of abstraction in SystemVerilog is used to hide certain details and only
show the essential features of the object. In other words, it deals with the outside
view of an object.

Encapsulation

 This is an important programming concept that assists in separating an object's state


from its behavior. This helps in hiding an object's data describing its state from any
further modification by external component. In SystemVerilog there are three
different terms used for hiding data constructs and these are public, private and
protected . As we know an object can associated with data with predefined classes
and in any application an object can know about the data it needs to know about. So
any unnecessary data are not required by an object can be hidden by this process. It
can also be termed as information hiding that prohibits outsiders in seeing the inside
of an object in which abstraction is implemented.  

Polymorphism

 It describes the ability of the object in belonging to different types with specific
behavior of each type. So by using this, one object can be treated like another and in
this way it can create and define multiple level of interface. Here the programmers
need not have to know the exact type of object in advance and this is being
implemented at runtime.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CL_01_INTRODUCTION.html[9/26/2012 2:07:04 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS CLASS Index


Introduction
SystemVerilog Class
Verification A class is an actual representation of an Abstrace data type. It therefore provides Object
implementation details for the data structure used and operations. This
Constructs Inheritance
Interface EXAMPLE: Encapsulation
  class A ; Polymorphism
OOPS Abstract Classes
      // attributes:
Randomization       int i Parameterised Class
Nested Classes
Functional Coverage Constant
      // methods:
Assertion       task print     Static
  endclass Casting
DPI Copy
UVM Tutorial Definition (Class) : A class is the implementation of an abstract data type . It defines Scope Resolution
attributes and methods which implement the data structure and operations of the Operator
VMM Tutorial Null
abstract data type, respectively. Instances of classes are called objects.
OVM Tutorial Consequently, classes define properties and behaviour of sets of objects. External Declaration
Classes And Structures
Easy Labs : SV
In SV classes also contain Constraints for randomization control. Typedef Class
Easy Labs : UVM Pure
Other Oops Features
Easy Labs : OVM
Class Properties: Misc
Easy Labs : VMM
AVM Switch TB Instance Variables (Non-Static Fields) : Report a Bug or Comment
Technically speaking, objects store their individual states in "non-static fields", that on This section - Your
VMM Ethernet sample input is what keeps
is, fields declared without the static keyword. Non-static fields are also known as
instance variables because their values are unique to each instance of a class (to each Testbench.in improving
object, in other words); with time!
Verilog
Verification Class Variables (Static Fields) :
A class variable is any field declared with the static modifier; this tells the compiler
Verilog Switch TB
that there is exactly one copy of this variable in existence, regardless of how many
Basic Constructs times the class has been instantiated.

Local Variables :
OpenVera Local Variables Similar to how an object stores its state in fields, a method will often
store its temporary state in local variables. The syntax for declaring a local variable is
Constructs
similar to declaring a field (for example, int count = 0;). There is no special keyword
Switch TB designating a variable as local; that determination comes entirely from the location in
RVM Switch TB which the variable is declared , which is between the opening and closing braces of a
method. As such, local variables are only visible to the methods in which they are
RVM Ethernet sample declared; they are not accessible from the rest of the class.

Parameters :
Specman E The important thing to remember is that parameters are always classified as
"variables" not "fields".
Interview Questions
Constants :
Class properties can be made read-only by a const declaration like any other
SystemVerilog variable.

http://testbench.in/CL_02_CLASS.html[9/26/2012 2:07:12 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CL_02_CLASS.html[9/26/2012 2:07:12 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS OBJECT Index


Introduction
SystemVerilog Class
Verification Objects are uniquely identifiable by a name. Therefore you could have two Object
distinguishable objects with the same set of values. This is similar to traditional This
Constructs programming languages like verilog where you could have, say two integers i and j Inheritance
Interface both of which equal to 2. Please notice the use of i and j in the last sentence to name Encapsulation
the two integers. We refer to the set of values at a particular time as the state of the Polymorphism
OOPS Abstract Classes
object.
Randomization Parameterised Class
Nested Classes
Functional Coverage Constant
EXAMPLE:
Assertion    class simple ; Static
       int i; Casting
DPI Copy
       int j;
UVM Tutorial Scope Resolution
       task printf(); Operator
VMM Tutorial Null
          $display( i , j );
OVM Tutorial        endtask External Declaration
   endclass Classes And Structures
Easy Labs : SV
   Typedef Class
Easy Labs : UVM    program main; Pure
       initial Other Oops Features
Easy Labs : OVM
       begin Misc
Easy Labs : VMM            simple obj_1;
AVM Switch TB            simple obj_2; Report a Bug or Comment
           obj_1 = new(); on This section - Your
VMM Ethernet sample            obj_2 = new(); input is what keeps
           obj_1.i = 2; Testbench.in improving
           obj_2.i = 4; with time!
Verilog            obj_1.printf();
Verification            obj_2.printf();
       end
Verilog Switch TB    endprogram
Basic Constructs
RESULT

          2          0
OpenVera           4          0
Constructs
Switch TB
RVM Switch TB Definition (Object) An object is an instance of a class. It can be uniquely identified by
RVM Ethernet sample its name and it defines a state which is represented by the values of its attributes at a
particular time.

The state of the object changes according to the methods which are applied to it. We
Specman E refer to these possible sequence of state changes as the behaviour of the object.
Interview Questions
Definition (Behaviour) The behaviour of an object is defined by the set of methods
which can be applied on it.

We now have two main concepts of object-orientation introduced, class and object.
Object-oriented programming is therefore the implementation of abstract data types
or, in more simple words, the writing of classes. At runtime instances of these
classes, the objects, achieve the goal of the program by changing their states.
Consequently, you can think of your running program as a collection of objects.

http://testbench.in/CL_03_OBJECT.html[9/26/2012 2:07:19 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

Creating Objects

As you know, a class provides the blueprint for objects; you create an object from a
class. In the following statements ,program creates an object and assigns it to a
variable:

        packet pkt = new(23, 94);


        driver drvr = new(pkt,intf);

    The first line creates an object of the packet class, and the second create an
object of the driver class.

    Each of these statements has three parts (discussed in detail below):

       1. Declaration: The code set in bold are all variable declarations that associate
a variable name with an object type.
       2. Instantiation: The new keyword is a SV operator that creates the object.
       3. Initialization: The new operator is followed by a call to a constructor, which
initializes the new object.

Declaration:

Declaring a Variable to Refer to an Object


Previously, you learned that to declare a variable, you write:

    type name;

This notifies the compiler that you will use name to refer to data whose type is type.
With a primitive variable, this declaration also reserves the proper amount of memory
for the variable.

You can also declare a reference variable on its own line. For example:

    packet pkt;

If you declare pkt like this, its value will be undetermined until an object is actually
created and assigned to it using the new method. Simply declaring a reference
variable does not create an object. For that, you need to use the new operator. You
must assign an object to pkt before you use it in your code. Otherwise, you will get a
compiler error.

A variable in this state, which currently references no object, can be illustrated as


follows (the variable name, pkt, plus a reference pointing to nothing): . During
simulation, the tool will not allocate memory for this object and error is reported.
There will not be any compilation error.

EXAMPLE:
    class packet ;
        int length = 0;
       function new (int l);
        length = l;
       endfunction
    endclass

    program main;
    
        initial
        begin
            packet pkt;
            pkt.length = 10;
        end
    
    endprogram

RESULT

Error: null object access

http://testbench.in/CL_03_OBJECT.html[9/26/2012 2:07:19 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

Instantiating A Class:

The new operator instantiates a class by allocating memory for a new object and
returning a reference to that memory. The new operator also invokes the object
constructor.

The new operator returns a reference to the object it created. This reference is
usually assigned to a variable of the appropriate type, like:

    packet pkt = new(10);

Initializing An Object

Here's the code for the packet class:

EXAMPLE
    class packet ;
       int length = 0;
       //constructor
       function new (int l);
            length = l;
       endfunction
    endclass

This class contains a single constructor. You can recognize a constructor because its
declaration uses the same name as the class and it has no return type. The
constructor in the packet class takes one integer arguments, as declared by the code
(int l). The following statement provides 10 as value for those arguments:

    packet pkt = new(10);

If a class does not explicitly declare any, the SV compiler automatically provides a no-
argument constructor, called the default constructor. This default constructor calls
the class parent's no-argument constructor, or the Object constructor if the class has
no other parent.

Constructor

SystemVerilog does not require the complex memory allocation and deallocation of
C++. Construction of an object is straightforward; and garbage collection, as in Java,
is implicit and automatic. There can be no memory leaks or other subtle behavior that
is so often the bane of C++ programmers.  

The new operation is defined as a function with no return type, and like any other
function, it must be nonblocking. Even though new does not specify a return type, the
left-hand side of the assignment determines the return type.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CL_03_OBJECT.html[9/26/2012 2:07:19 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS THIS Index


Introduction
SystemVerilog Using The This Keyword Class
Verification Object
    Within an instance method or a constructor, this is a reference to the current This
Constructs object , the object whose method or constructor is being called. You can refer to any Inheritance
Interface member of the current object from within an instance method or a constructor by Encapsulation
using this. Polymorphism
OOPS Abstract Classes
    
Randomization     The most common reason for using the this keyword is because a field is shadowed Parameterised Class
by a method or constructor parameter. Nested Classes
Functional Coverage Constant
Assertion     For example, in the packet class was written like this Static
Casting
DPI Copy
EXAMPLE
UVM Tutorial    class packet ; Scope Resolution
        int length = 0; Operator
VMM Tutorial Null
        //constructor
OVM Tutorial        function new (int l); External Declaration
        length = l; Classes And Structures
Easy Labs : SV
       endfunction Typedef Class
Easy Labs : UVM     endclass Pure
Other Oops Features
Easy Labs : OVM
Misc
Easy Labs : VMM     but it could have been written like this:
AVM Switch TB Report a Bug or Comment
EXAMPLE: on This section - Your
VMM Ethernet sample    class packet ; input is what keeps
       int length = 0; Testbench.in improving
        //constructor with time!
Verilog        function new (int length);
Verification            this.length = length;
       endfunction
Verilog Switch TB     endclass
Basic Constructs
    
    program main;
    
OpenVera         initial
Constructs         begin
Switch TB             packet pkt;
            pkt =new(10);
RVM Switch TB             $display(pkt.length);
RVM Ethernet sample         end
    
    endprogram
Specman E RESULT
Interview Questions
  10

    Each argument to the second constructor shadows one of the object's fields inside
the constructor "length" is a local copy of the constructor's first argument. To refer to
the legnth field inside the object , the constructor must use "this.length".

http://testbench.in/CL_04_THIS.html[9/26/2012 2:07:28 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CL_04_THIS.html[9/26/2012 2:07:28 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INHERITANCE Index


Introduction
SystemVerilog Class
Verification Object-oriented programming allows classes to inherit commonly used state and Object
behavior from other classes.   This
Constructs Inheritance
Interface Definition (Inheritance) Inheritance is the mechanism which allows a class A to inherit Encapsulation
properties of a class B. We say ``A inherits from B''. Objects of class A thus have Polymorphism
OOPS Abstract Classes
access to attributes and methods of class B without the need to redefine them. The
Randomization following definition defines two terms with which we are able to refer to participating Parameterised Class
classes when they use inheritance. Nested Classes
Functional Coverage Constant
Assertion Definition (Superclass) If class A inherits from class B, then B is called superclass of Static
A.   Casting
DPI Copy
UVM Tutorial Definition (Subclass)   If class A inherits from class B, then A is called subclass of B. Scope Resolution
Operator
VMM Tutorial Null
OVM Tutorial Objects of a subclass can be used where objects of the corresponding superclass are External Declaration
expected. This is due to the fact that objects of the subclass share the same Classes And Structures
Easy Labs : SV
behaviour as objects of the superclass. Superclasses are also called parent classes. Typedef Class
Easy Labs : UVM Subclasses may also be called child classes or extended classes or just derived classes Pure
.  Of course, you can again inherit from a subclass, making this class the superclass of Other Oops Features
Easy Labs : OVM
the new subclass. This leads to a hierarchy of superclass/subclass relationships. Misc
Easy Labs : VMM
AVM Switch TB The idea of inheritance is simple but powerful: When you want to create a new class Report a Bug or Comment
and there is already a class that includes some of the code that you want, you can on This section - Your
VMM Ethernet sample derive your new class from the existing class. In doing this, you can reuse the fields input is what keeps
and methods of the existing class without having to write (and debug!) them yourself. Testbench.in improving
with time!
Verilog A subclass inherits all the members (fields, methods, and nested classes) from its
Verification superclass. Constructors are not members, so they are not inherited by subclasses, but
the constructor of the superclass can be invoked from the subclass.
Verilog Switch TB
Basic Constructs
What You Can Do In A Subclass:

A subclass inherits all of the public and protected members of its parent. You can use
OpenVera the inherited members as is, replace them, hide them, or supplement them with new
Constructs members:
Switch TB
The inherited fields can be used directly, just like any other fields.
RVM Switch TB   You can declare a field in the subclass with the same name as the one in the
RVM Ethernet sample superclass, thus hiding it (not recommended).

  You can declare new fields in the subclass that are not in the superclass.
Specman E
  The inherited methods can be used directly as they are.
Interview Questions
  You can write a new instance method in the subclass that has the same signature
as the one in the superclass, thus overriding it.

  You can write a new static method in the subclass that has the same signature as
the one in the superclass, thus hiding it.

  You can declare new methods in the subclass that are not in the superclass.

  You can write a subclass constructor that invokes the constructor of the

http://testbench.in/CL_05_INHERITANCE.html[9/26/2012 2:07:36 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

superclass, either implicitly or by using the keyword super.

Overriding

Following example shows, adding new varibles, new methods, redefining existing
methods.

EXAMPLE:
    class parent;
         task printf();
             $display(" THIS IS PARENT CLASS ");
         endtask
    endclass
    
    class subclass extends parent;
        task printf();
             $display(" THIS IS SUBCLASS ");
        endtask
    endclass
    
    program main;
    
         initial
         begin
             parent p;
             subclass s;
             p = new();
             s = new();
             p.printf();
             s.printf();
         end
    endprogram

RESULT

 THIS IS PARENT CLASS


 THIS IS SUBCLASS

Super

The super keyword is used from within a derived class to refer to members of the
parent class. It is necessary to use super to access members of a parent class when
those members are overridden by the derived class.

EXAMPLE:
    class parent;
        task printf();
            $display(" THIS IS PARENT CLASS ");
        endtask
    endclass
    
    class subclass extends parent;
        task printf();
            super.printf();
        endtask
    endclass
    
    program main;
    
        initial
        begin
            subclass s;
            s = new();
            s.printf();
        end

http://testbench.in/CL_05_INHERITANCE.html[9/26/2012 2:07:36 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

    endprogram

RESULT

 THIS IS PARENT CLASS

The member can be a member declared a level up or be inherited by the class one
level up. There is no way to reach higher (for example, super.super.count is not
allowed).

Subclasses (or derived classes) are classes that are extensions of the current class
whereas superclasses (parent classes or base classes) are classes from which the
current class is extended, beginning with the original base class.

NOTE: When using the super within new, super.new shall be the first statement
executed in the constructor. This is because the superclass must be initialized before
the current class and, if the user code does not provide an initialization, the compiler
shall insert a call to super.new automatically.

Is Only Method

Programmers can  override the existing code/functionality before existing code and


replaces with new code as shown in below example.

EXAMPLE:
     class parent;
         task printf();
             $display(" THIS IS PARENT CLASS ");
         endtask
     endclass
    
     class subclass extends parent;
          task printf();
              $display(" THIS IS SUBCLASS ");
          endtask
     endclass
    
     program main;
    
         initial
         begin
             subclass s;
             s = new();
             s.printf();
         end
     endprogram

RESULT:

 THIS IS SUBCLASS

Is First Method

Programmers can  add new lines of code/functionality before existing code as shown


in below example.

EXAMPLE:
    class parent;
        task printf();
            $display(" THIS IS PARENT CLASS ");
        endtask
    endclass
    
    class subclass extends parent;
         task printf();
             $display(" THIS IS SUBCLASS ");
             super.printf();
         endtask
    endclass

http://testbench.in/CL_05_INHERITANCE.html[9/26/2012 2:07:36 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

    
    program main;
    
         initial
         begin
             subclass s;
             s = new();
             s.printf();
         end
    endprogram

RESULT:

 THIS IS SUBCLASS
 THIS IS PARENT CLASS

Is Also Method

Programmers can  add new lines of code/functionality after the existing code as


shown in below example.

EXAMPLE:
     class parent;
         task printf();
             $display(" THIS IS PARENT CLASS ");
         endtask
     endclass
    
     class subclass extends parent;
          task printf();
              super.printf();
              $display(" THIS IS SUBCLASS ");
          endtask
     endclass
    
     program main;
    
           initial
           begin
                subclass s;
                s = new();
                s.printf();
           end
     endprogram

RESULT:

 THIS IS PARENT CLASS


 THIS IS SUBCLASS

Overriding Constraints.

Programmers can  override the existing constraint and replaces with new constraint as
shown in below example.

EXAMPLE:
     class Base;
         rand integer Var;
         constraint range { Var < 100 ; Var > 0 ;}
     endclass
    
     class Extended extends Base;
         constraint range { Var < 100 ; Var > 50 ;} // Overrighting the Base class
constraints.
     endclass
    
     program inhe_31;
          Extended obj;

          initial
          begin
              obj = new();

http://testbench.in/CL_05_INHERITANCE.html[9/26/2012 2:07:36 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

              for(int i=0 ; i < 100 ; i++)
                  if(obj.randomize())
                       $display(" Randomization sucsessfull : Var = %0d ",obj.Var);
                  else
                       $display("Randomization failed");
          end
     endprogram

RESULT:

Randomization sucsessfull : Var = 77


Randomization sucsessfull : Var = 86
Randomization sucsessfull : Var = 76
Randomization sucsessfull : Var = 89
Randomization sucsessfull : Var = 86
Randomization sucsessfull : Var = 76
Randomization sucsessfull : Var = 96

Overriding Datamembers

Only virtual methods truly override methods in base classes. All other methods and
properties do not override but provide name hiding.

EXAMPLE
     class base;
         int N = 3;

         function int get_N(); 
              return N; 
         endfunction
     endclass

     class ext extends base;


         int N = 4;

         function int get_N(); 
             return N; 
         endfunction

         function int get_N1(); 
             return super.N; 
         endfunction
     endclass
    
     program main;
         initial
         begin
             ext e = new;
             base b = e;                // Note same object!
             $display(b.get_N());  // "3"
             $display(e.get_N());  // "4"
             $display(e.get_N1()); // "3"  - super.N
         end
     endprogram
    
RESULT

3
4
3

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/CL_05_INHERITANCE.html[9/26/2012 2:07:36 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CL_05_INHERITANCE.html[9/26/2012 2:07:36 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS ENCAPSULATION Index


Introduction
SystemVerilog Class
Verification Encapsulation is a technique for minimizing interdependencies among modules by Object
defining a strict external communication. This way, internal coding can be changed This
Constructs without affecting the communication, so long as the new implementation supports the Inheritance
Interface same (or upwards compatible) external communication. Encapsulation
Polymorphism
OOPS Abstract Classes
Encapsulation prevents a program from becoming so interdependent that a small
Randomization change has massive ripple effects. Parameterised Class
Nested Classes
Functional Coverage Constant
The implementation of an object can be changed without affecting the application
Assertion that uses it for: Static
Casting
DPI Copy
Improving performance, fix a bug, consolidate code or for porting.
UVM Tutorial Scope Resolution
Access Specifiers: Operator
VMM Tutorial Null
OVM Tutorial In SystemVerilog, unqualified class properties and methods are public, available to External Declaration
anyone who has access to the object¿s name. Classes And Structures
Easy Labs : SV
Typedef Class
Easy Labs : UVM A member identified as local is available only to methods inside the class. Further, Pure
these local members are not visible within subclasses. Of course, nonlocal methods Other Oops Features
Easy Labs : OVM
that access local class properties or methods can be inherited and work properly as Misc
Easy Labs : VMM methods of the subclass.
AVM Switch TB Report a Bug or Comment
EXAMPLE: local variblg error on This section - Your
VMM Ethernet sample     class base; input is what keeps
        local int i; Testbench.in improving
    endclass with time!
Verilog     
Verification     program main;
        initial
Verilog Switch TB         begin
Basic Constructs             base b = new();    
            b.i = 123;
        end
    endprogram
OpenVera
Constructs RESULT:
Switch TB
Local member 'i' of class 'base' is not accessible from scope 'main'
RVM Switch TB
RVM Ethernet sample
The above examples gives compilation error.

EXAMPLE:  local varible access using method


Specman E     class base;
Interview Questions          local int i;

         task set(int j);
             i = j;
             $display(i);
         endtask
    endclass
    
    program main;
        initial
        begin

http://testbench.in/CL_06_ENCAPSULATION.html[9/26/2012 2:07:44 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

            base b = new();    
            b.set(123);
        end
    endprogram

RESULT

123

EXAMPLE:  local varible access in subclass


     class base;
         local int i;
     endclass
    
     class ext extends base;
         function new();
             i = 10;
         endfunction
     endclass
RESULT

Local member 'i' of class 'base' is not accessible from scope 'ext'

A protected class property or method has all of the characteristics of a local member,
except that it can be inherited; it is visible to subclasses.

EXAMPLE: protected varible


    class base;
        protected int i;
    endclass
    
    class ext extends base;
        function new();
            i = 10;
        endfunction
    endclass

EXAMPLE: protected varible in 2 level of inheritence


    class base;
        local int i;
    endclass
    
    class ext extends base;
        protected int i;
    endclass
    
    class ext2 extends ext;
         function new();
              i =10;
         endfunction
    endclass

In the above example, the varible i is overloaded in subclass with different qualifier.

EXAMPLE: Error access to protected varible.


     class base;
          protected int i;
     endclass
    
     program main;
         initial
         begin
             base b = new();    
             b.i = 123;

http://testbench.in/CL_06_ENCAPSULATION.html[9/26/2012 2:07:44 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

         end
     endprogram

RESULT

Protected member 'i' of class 'base' is not accessible from scope 'main'

Within a class, a local method or class property of the same class can be referenced,
even if it is in a different instance of the same class.

EXAMPLE
    class Packet;
        local integer i;

        function integer compare (Packet other);
             compare = (this.i == other.i);
        endfunction
    endclass

A strict interpretation of encapsulation might say that other.i should not be visible
inside of this packet because it is a local class property being referenced from outside
its instance. Within the same class, however, these references are allowed. In this
case, this.i shall be compared to other.i and the result of the logical comparison
returned.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CL_06_ENCAPSULATION.html[9/26/2012 2:07:44 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS POLYMORPHISM Index


Introduction
SystemVerilog Class
Verification Polymorphism allows an entity to take a variety of representations. Polymorphism Object
means the ability to request that the same  Operations  be performed by a wide range This
Constructs of different types of things. Effectively, this means that you can ask many different Inheritance
Interface objects to perform the same action.  Override polymorphism is an override of existing Encapsulation
code. Subclasses of existing classes are given a "replacement method" for methods in Polymorphism
OOPS Abstract Classes
the superclass. Superclass objects may also use the replacement methods when
Randomization dealing with objects of the subtype. The replacement method that a subclass provides Parameterised Class
has exactly the same signature as the original method in the superclass. Nested Classes
Functional Coverage Constant
Assertion Polymorphism allows the redefining of methods for derived classes while enforcing a Static
common interface.To achieve polymorphism the 'virtual' identifier must be used when Casting
DPI Copy
defining the base class and method(s) within that class.
UVM Tutorial Scope Resolution
Operator
VMM Tutorial Null
EXAMPLE: without virtual
OVM Tutorial       class A ; External Declaration
           task disp (); Classes And Structures
Easy Labs : SV
                $display(" This is class A "); Typedef Class
Easy Labs : UVM            endtask Pure
      endclass Other Oops Features
Easy Labs : OVM
       Misc
Easy Labs : VMM       class EA extends A ;
AVM Switch TB             task disp (); Report a Bug or Comment
                $display(" This is Extended class A "); on This section - Your
VMM Ethernet sample             endtask input is what keeps
      endclass Testbench.in improving
       with time!
Verilog       program main ;
Verification            EA my_ea;
           A my_a;
Verilog Switch TB           
Basic Constructs            initial
           begin
                my_a = new();
                my_a.disp();
OpenVera                 
Constructs                 my_ea = new();
Switch TB                 my_a = my_ea;
                my_a.disp();
RVM Switch TB            end
RVM Ethernet sample       endprogram
RESULTS

This is class A
Specman E This is class A
Interview Questions
EXAMPLE: with virtual
      class A ;
      virtual  task disp ();
                $display(" This is class A ");
           endtask
      endclass
      
      class EA extends A ;
            task disp ();

http://testbench.in/CL_07_POLYMORPHISM.html[9/26/2012 2:07:51 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

                $display(" This is Extended class A ");


            endtask
      endclass
      
      program main ;
           EA my_ea;
           A my_a;
          
           initial
           begin
                my_a = new();
                my_a.disp();
                
                my_ea = new();
                my_a = my_ea;
                my_a.disp();
           end
      endprogram

RESULTS

 This is class A
 This is Extended class A

Observe the above two outputs. Methods which are declared as virtual are executing
the code in the object which is created.

The methods which are added in the subclasses which are not in the parent class
canot be acessed using the parent class handle. This will result in a compilation error.
The compiler check whether the method is exesting the parent class definition or not.

EXAMPLE:
      class A ;
      endclass
      
      class EA extends A ;
           task disp ();
                $display(" This is Extended class A ");
           endtask
      endclass
      
      program main ;
          EA my_ea;
          A my_a;
          
          initial
          begin
              my_ea = new();
              my_a = my_ea;
              my_ea.disp();
              my_a.disp();
          end
      endprogram

RESULT:

Member disp not found in class A

To access the varible or method which are only in the subclass and not in the parent
class, revert back the object to the subclass handle.

EXAMPLE:
     class A ;
     endclass

http://testbench.in/CL_07_POLYMORPHISM.html[9/26/2012 2:07:51 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

    
     class EA extends A ;
          task disp ();
               $display(" This is Extended class A ");
          endtask
     endclass
    
     program main ;
         EA my_ea;
         A my_a;
        
         initial
         begin
              my_ea = new();
              my_a = my_ea;
              just(my_a);
         end
     endprogram
    
     task just(A my_a);
         EA loc;
         $cast(loc,my_a);
         loc.disp();
     endtask

RESULT

This is Extended class A

Let us see one more example, A parent class is extended and virtual method is
redefined in the subclass as non virtual method. Now if furthur extention is done to
the class, then the method is still considered as virtual method and Polymorphism can
be achived still. It is advised to declare a method as virtual in all its subclass, if it is
declared as virtual in baseclass , to avoid confusion to the end user who is extend the
class.

EXAMPLE:
     class A ;
         virtual task disp ();
             $display(" This is class A ");
         endtask
     endclass
    
     class EA_1 extends A ;
          task disp ();
              $display(" This is Extended  1 class A ");
          endtask
     endclass
    
     class EA_2 extends EA_1 ;
         task disp ();
             $display(" This is Extended  2 class A ");
         endtask
     endclass
    
     program main ;
         EA_2 my_ea;
         EA_1 my_a;
        
         initial
         begin
             my_ea = new();
             my_a = my_ea;
             my_a.disp();
             just(my_a);
         end
     endprogram
    
     task just(A my_a);
         EA_1 loc;
         $cast(loc,my_a);
         loc.disp();

http://testbench.in/CL_07_POLYMORPHISM.html[9/26/2012 2:07:51 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

     endtask

RESULT

 This is Extended  2 class A


 This is Extended  2 class A

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CL_07_POLYMORPHISM.html[9/26/2012 2:07:51 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS ABSTRACT CLASSES Index


Introduction
SystemVerilog With inheritance we are able to force a subclass to offer the same properties like Class
Verification their superclasses. Consequently, objects of a subclass behave like objects of their Object
superclasses. This
Constructs Inheritance
Interface Sometimes it make sense to only describe the properties of a set of objects without Encapsulation
knowing the actual behaviour beforehand Polymorphism
OOPS Abstract Classes
Randomization Abstract classes are those which can be used for creation of handles. However their Parameterised Class
methods and constructors can be used by the child or extended class. The need for Nested Classes
Functional Coverage Constant
abstract classes is that you can generalize the super class from which child classes can
Assertion share its methods. The subclass of an abstract class which can create an object is Static
called as "concrete class". Casting
DPI Copy
UVM Tutorial EXAMPLE: useing abstract class Scope Resolution
     virtual class A ; Operator
VMM Tutorial Null
         virtual task disp ();
OVM Tutorial               $display(" This is class A "); External Declaration
         endtask Classes And Structures
Easy Labs : SV
     endclass Typedef Class
Easy Labs : UVM      Pure
     class EA extends A ; Other Oops Features
Easy Labs : OVM
         task disp (); Misc
Easy Labs : VMM              $display(" This is Extended class A ");
AVM Switch TB          endtask Report a Bug or Comment
     endclass on This section - Your
VMM Ethernet sample      input is what keeps
     program main ; Testbench.in improving
         EA my_ea; with time!
Verilog          A my_a;
Verification         
         initial
Verilog Switch TB          begin
Basic Constructs              my_ea = new();
             my_a = my_ea;
             my_ea.disp();
             my_a.disp();
OpenVera          end
Constructs      endprogram
Switch TB
RESULT
RVM Switch TB
RVM Ethernet sample This is Extended class A
This is Extended class A

Specman E EXAMPLE: creating object of virtual class


Interview Questions     virtual class A ;
        virtual task disp ();
             $display(" This is class A ");
        endtask
    endclass
    
    program main ;
         A my_a;
        
         initial
         begin

http://testbench.in/CL_08_ABSTRACT_CLASSES.html[9/26/2012 2:07:59 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

             my_a = new();


             my_a.disp();
         end
    endprogram

RESULT

Abstract class A cannot be instantiated

Virtual keyword is used to express the fact that derived classes must redefine the
properties to fulfill the desired functionality. Thus from the abstract class point of
view, the properties are only specified but not fully defined. The full definition
including the semantics of the properties must be provided by derived classes.

Definition (Abstract Class) A class A is called abstract class if it is only used as a


superclass for other classes. Class A only specifies properties. It is not used to create
objects. Derived classes must define the properties of A.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CL_08_ABSTRACT_CLASSES.html[9/26/2012 2:07:59 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PARAMETERISED CLASS Index


Introduction
SystemVerilog Type Parameterised Class Class
Verification Object
At the time, when we write down a class definition, we must be able to say that this This
Constructs class should define a generic type. However, if we don't know with which types the Inheritance
Interface class will be used. Consequently, we must be able to define the class with help of a Encapsulation
placeholder to which we refer as if it is the type on which the class operates. Thus, Polymorphism
OOPS Abstract Classes
the class definition provides us with a template of an actual class. The actual class
Randomization definition is created once we declare a particular object. Let's illustrate this with the Parameterised Class
following example. Suppose, you want to define a list class which should be a generic Nested Classes
Functional Coverage Constant
type. Thus, it should be possible to declare list objects for integers, bits,objects or
Assertion any other type. Static
Casting
DPI Copy
EXAMPLE
UVM Tutorial   class List #(type T = int); Scope Resolution
    //attributes: Operator
VMM Tutorial Null
      T data_node;
OVM Tutorial       ...... External Declaration
      ......           Classes And Structures
Easy Labs : SV
  // methods: Typedef Class
Easy Labs : UVM       task append(T element); Pure
      function T getFirst(); Other Oops Features
Easy Labs : OVM
      function T getNext(); Misc
Easy Labs : VMM       ...... 
AVM Switch TB       ...... Report a Bug or Comment
  endclass on This section - Your
VMM Ethernet sample input is what keeps
Testbench.in improving
The above template class List looks like any other class definition. However, the first with time!
Verilog line declares List to be a template for various types. The identifier T is used as a
Verification placeholder for an actual type. For example, append() takes one element as an
argument. The type of this element will be the data type with which an actual list
Verilog Switch TB object is created. For example, we can declare a list object for "packet" if a
Basic Constructs definition fot the type "packet" exists:

EXAMPLE
  List#(packet) pl; // Object pl is a list of packet
OpenVera   List#(string) sl; // Object sl is a list of strings
Constructs
Switch TB The first line declares List#(packet) to be a list for packets. At this time, the compiler
uses the template definition, substitutes every occurrence of T with "packet" and
RVM Switch TB creates an actual class definition for it. This leads to a class definition similar to the
RVM Ethernet sample one that follows:

EXAMPLE
Specman E   class List {
Interview Questions      //attributes:
      packet data_node;
      ......
      ......          
  // methods:
      task append(packet element);
      function packet getFirst();
      function packet getNext();
      ...... 
      ......
   }

http://testbench.in/CL_09_PARAMETERISED_CLASS.html[9/26/2012 2:08:07 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

This is not exactly, what the compiler generates. The compiler must ensure that we
can create multiple lists for different types at any time. For example, if we need
another list for, say "strings", we can write:

EXAMPLE
  List#(packet) pl; // Object pl is a list of packet
  List#(string) sl; // Object sl is a list of strings

In both cases the compiler generates an actual class definition. The reason why both
do not conflict by their name is that the compiler generates unique names. However,
since this is not viewable to us, we don't go in more detail here. In any case, if you
declare just another list of "strings", the compiler can figure out if there already is an
actual class definition and use it or if it has to be created. Thus,

EXAMPLE
  List#(packet) rcv_pkt;  // Object rcv_pkt is a list of packet
  List#(packet) sent_pkt; // Object sent_pkt is a list of packet

will create the actual class definition for packet List and will reuse it for another List.
Consequently, both are of the same type. We summarize this in the following
definition:

Definition (Parameterized Class) If a class A is parameterized with a data type B, A is


called template class. Once an object of A is created, B is replaced by an actual data
type. This allows the definition of an actual class based on the template specified for
A and the actual data type.

We are able to define template classes with more than one parameter. For example,
directories are collections of objects where each object can be referenced by a key.
Of course, a directory should be able to store any type of object. But there are also
various possibilities for keys. For instance, they might be strings or numbers.
Consequently, we would define a template class Directory which is based on two type
parameters, one for the key and one for the stored objects.

Value Parameterised Class

The normal Verilog parameter mechanism is also used to parameterize a class.

EXAMPLE
     class Base#(int size = 3);
         bit [size:0] a;

         task disp();
              $display(" Size of the vector a is %d ",$size(a));
         endtask
     endclass
    
     program main();
    
         initial
         begin
             Base B1;
             Base#(4) B2;
             Base#(5) B3;
             B1  = new();
             B2  = new();
             B3  = new();
             B1.disp();
             B2.disp();
             B3.disp();
         end
     endprogram

RESULT

 Size of the vector a is           4


 Size of the vector a is           5

http://testbench.in/CL_09_PARAMETERISED_CLASS.html[9/26/2012 2:08:07 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

 Size of the vector a is           6

Instances of this class can then be instantiated like modules or interfaces:

EXAMPLE
    vector #(10) vten; // object with vector of size 10
    vector #(.size(2)) vtwo; // object with vector of size 2
    typedef vector#(4) Vfour; // Class with vector of size 4

Generic Parameterised Class

A specialization is the combination of a specific generic class with a unique set of


parameters. Two sets of parameters shall be unique unless all parameters are the
same as defined by the following rules:
a) A parameter is a type parameter and the two types are matching types.
b) A parameter is a value parameter and both their type and their value are the
same.

All matching specializations of a particular generic class shall represent the same
type. The set of matching specializations of a generic class is defined by the context
of the class declaration. Because generic classes in a package are visible throughout
the system, all matching specializations of a package generic class are the same type.
In other contexts, such as modules or programs, each instance of the scope containing
the generic class declaration creates a unique generic class, thus, defining a new set
of matching specializations.

A generic class is not a type; only a concrete specialization represents a type. In the
example above, the class vector becomes a concrete type only when it has had
parameters applied to it, for example:
typedef vector my_vector; // use default size of 1

EXAMPLE
vector#(6) vx; // use size 6

To avoid having to repeat the specialization either in the declaration or to create


parameters of that type, a typedef should be used:

EXAMPLE
typedef vector#(4) Vfour;
typedef stack#(Vfour) Stack4;
Stack4 s1, s2; // declare objects of type Stack4

Extending Parameterised Class

A parameterized class can extend another parameterized class. For example:

EXAMPLE
    class C #(type T = bit); 
     ... 
    endclass // base class
    
    class D1 #(type P = real) extends C; // T is bit (the default)

Class D1 extends the base class C using the base class¿s default type (bit) parameter.

    class D2 #(type P = real) extends C #(integer); // T is integer

Class D2 extends the base class C using an integer parameter.

    class D3 #(type P = real) extends C #(P); // T is P

Class D3 extends the base class C using the parameterized type (P) with which the
extended class is parameterized.

http://testbench.in/CL_09_PARAMETERISED_CLASS.html[9/26/2012 2:08:07 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CL_09_PARAMETERISED_CLASS.html[9/26/2012 2:08:07 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS NESTED CLASSES Index


Introduction
SystemVerilog   A nested class is a class whose definition appears inside the definition of another Class
Verification class, as if it were a member of the other class.   The SystemVerilog programming Object
language allows you to define a class within another class.     This
Constructs Inheritance
Interface EXAMPLE Encapsulation
    class StringList; Polymorphism
OOPS Abstract Classes
Randomization         class Node; // Nested class for a node in a linked list. Parameterised Class
            string name; Nested Classes
Functional Coverage Constant
            Node link;
Assertion         endclass Static
Casting
DPI Copy
    endclass
UVM Tutorial Scope Resolution
    class StringTree; Operator
VMM Tutorial Null
OVM Tutorial         class Node; // Nested class for a node in a binary tree. External Declaration
           string name; Classes And Structures
Easy Labs : SV
           Node left, right; Typedef Class
Easy Labs : UVM         endclass Pure
Other Oops Features
Easy Labs : OVM
    endclass Misc
Easy Labs : VMM     // StringList::Node is different from StringTree::Node
AVM Switch TB Report a Bug or Comment
Nesting allows hiding of local names and local allocation of resources. This is often on This section - Your
VMM Ethernet sample desirable when a new type is needed as part of the implementation of a class. input is what keeps
Declaring types within a class helps prevent name collisions and the cluttering of the Testbench.in improving
outer scope with symbols that are used only by that class. Type declarations nested with time!
Verilog inside a class scope are public and can be accessed outside the class
Verification
Why Use Nested Classes
Verilog Switch TB
Basic Constructs There are several compelling reasons for using nested classes, among them:

It is a way of logically grouping classes that are only used in one place.
OpenVera It increases encapsulation.
Constructs
Nested classes can lead to more readable and maintainable code.

Switch TB Logical grouping of classes : If a class is useful to only one other class, then it is
RVM Switch TB logical to embed it in that class and keep the two together. Nesting such "helper
classes" makes their package more streamlined.
RVM Ethernet sample
Increased encapsulation : Consider two top-level classes, A and B, where B needs
access to members of A that would otherwise be declared private. By hiding class B
Specman E within class A, A's members can be declared private and B can access them. In
addition, B itself can be hidden from the outside world.
Interview Questions
More readable, maintainable code:Nesting small classes within top-level classes
places the code closer to where it is used.

http://testbench.in/CL_10_NESTED_CLASSES.html[9/26/2012 2:08:16 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CL_10_NESTED_CLASSES.html[9/26/2012 2:08:16 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS CONSTANT Index


Introduction
SystemVerilog Class
Verification SystemVerilog adds another form of a local constant, const. A const form of constant Object
differs from a localparam constant in that the localparam must be set during This
Constructs elaboration, whereas a const can be set during simulation, such as in an automatic Inheritance
Interface task. Encapsulation
Polymorphism
OOPS Abstract Classes
Randomization Constant Class Parameterised Class
Nested Classes
Functional Coverage Constant
An instance of a class (an object handle) can also be declared with the const keyword.
Assertion Static
Casting
DPI Copy
EXAMPLE
UVM Tutorial       const class_name object = new(3,3,4); Scope Resolution
Operator
VMM Tutorial Null
OVM Tutorial External Declaration
In other words, the object acts like a variable that cannot be written. The arguments Classes And Structures
Easy Labs : SV
to the new method must be constant expressions. The members of the object can be Typedef Class
Easy Labs : UVM written (except for those members that are declared const). Pure
Other Oops Features
Easy Labs : OVM
Misc
Easy Labs : VMM Global Constant
AVM Switch TB Report a Bug or Comment
Global constant class properties include an initial value as part of their declaration. on This section - Your
VMM Ethernet sample They are similar to other const variables in that they cannot be assigned a value input is what keeps
anywhere other than in the declaration. Testbench.in improving
with time!
Verilog
Verification EXAMPLE
    class Jumbo_Packet;
Verilog Switch TB         const int max_size = 9 * 1024; // global constant
Basic Constructs         byte payload [];

        function new( int size );
             payload = new[ size > max_size ? max_size : size ];
OpenVera         endfunction
Constructs     endclass
Switch TB
EXAMPLE: error : chaning const varible
RVM Switch TB     class A ;
RVM Ethernet sample         const int i = 10;
    endclass
    
    program main ;
Specman E          A my_a;
Interview Questions         
         initial
         begin
             my_a = new();
             my_a.i = 55;
         end
    endprogram

RESULT

Error : Variable 'i' declared as 'const' .

http://testbench.in/CL_11_CONSTANT.html[9/26/2012 2:08:24 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

Instance Constants

Instance constants do not include an initial value in their declaration, only the const
qualifier. This type of constant can be assigned a value at run time, but the
assignment can only be done once in the corresponding class constructor not from
outside or any other method.

EXAMPLE
     class A ;
         const int i;

         function new();
             i = 20;
         endfunction
     endclass
    
     program main ;
         A my_a;
        
         initial
         begin
             my_a = new();
             $display(my_a.i);
         end
     endprogram

RESULT

20

EXAMPLE: error : assignment done twice


    class A ;
        const int i;
    
        function new();
            i = 20;
            i++;
        endfunction
    endclass
    
RESULT

Instance constants assignment can only be done once

EXAMPLE: error : assignment in other method


    class A ;
        const int i;

        task set();
           i = 20;
        endtask
    endclass

RESULT

Instance constants assignment allowed only in class constructor.

Typically, global constants are also declared static because they are the same for all
instances of the class. However, an instance constant cannot be declared static
because that would disallow all assignments in the constructor

http://testbench.in/CL_11_CONSTANT.html[9/26/2012 2:08:24 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CL_11_CONSTANT.html[9/26/2012 2:08:24 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS STATIC Index


Introduction
SystemVerilog Static Class Properties Class
Verification Object
This
Constructs A static property is a class variable that is associated with the class, rather than with Inheritance
Interface an instance of the class (a.k.a., an object). This means that when it is changed, its Encapsulation
change is reflected in all instances of the class. Static properties are declared with Polymorphism
OOPS Abstract Classes
the static keyword. If you need to access a static property inside a class, you can also
Randomization use the magic keywords "this" and  "super", which resolve to the current class and the Parameterised Class
parent of the current class, respectively. Using "this" and "super" allows you to avoid Nested Classes
Functional Coverage Constant
having to explicitly reference the class by name.
Assertion Static
Casting
DPI Copy
EXAMPLE: Using object name
UVM Tutorial      class A ; Scope Resolution
         static int i; Operator
VMM Tutorial Null
     endclass
OVM Tutorial      External Declaration
     program main ; Classes And Structures
Easy Labs : SV
          A obj_1; Typedef Class
Easy Labs : UVM           A obj_2; Pure
           Other Oops Features
Easy Labs : OVM
          initial Misc
Easy Labs : VMM           begin
AVM Switch TB               obj_1 = new(); Report a Bug or Comment
              obj_2 = new(); on This section - Your
VMM Ethernet sample               obj_1.i = 123; input is what keeps
              $display(obj_2.i); Testbench.in improving
          end with time!
Verilog      endprogram
Verification     
RESULT
Verilog Switch TB
Basic Constructs 123

OpenVera
Constructs The static class properties can be accessed using class name.
Switch TB
EXAMPLE: using class name
RVM Switch TB      class A ;
RVM Ethernet sample           static int i;
     endclass
    
     program main ;
Specman E           A obj_1;
Interview Questions           
          initial
          begin
              obj_1 = new();
              obj_1.i = 123;
              $display(A::i);
          end
     endprogram

RESULT

http://testbench.in/CL_12_STATIC.html[9/26/2012 2:08:32 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

123

The static class properties can be used without creating an object of that type.

EXAMPLE: without creating object


      class A ;
           static int i;
      endclass
      
      program main ;
          A obj_1;
          A obj_2;
          
          initial
          begin
              obj_1.i = 123;
              $display(obj_2.i);
          end
      endprogram

RESULT

123

EXAMPLE: using the object name, without creating object


     class A ;
         static int i;
     endclass
    
     program main ;
         A obj_1;
        
         initial
         begin
             obj_1.i = 123;
             $display(A::i);
         end
     endprogram
    
RESULT

123

Static Methods

Methods can be declared as static. A static method is subject to all the class scoping
and access rules, but behaves like a regular subroutine that can be called outside the
class.

EXAMPLE
class A ;
     static task incr();
         int j; //automatic variable
         j++;
         $display("J is %d",j);
     endtask
endclass
    
program main ;
     A obj_1;
     A obj_2;
    
     initial

http://testbench.in/CL_12_STATIC.html[9/26/2012 2:08:32 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

     begin
         $display("Static task - static task with automatic variables"); 
         obj_1  =  new();
         obj_2  =  new();
         obj_1.incr();
         obj_2.incr();
         obj_1.incr();
         obj_2.incr();
         obj_1.incr();
         $display("Static task - Each call to task will create a separate copy of 'j' and
increment it");

     end
endprogram

RESULT

Static task - static task with automatic variables


J is           1
J is           1
J is           1
J is           1
J is           1
Static task - Each call to task will create a separate copy of 'j' and increment it

A static method has no access to nonstatic members (class properties or methods),


but it can directly access static class properties or call static methods of the same
class. Access to nonstatic members or to the special this handle within the body of a
static method is illegal and results in a compiler error.

EXAMPLE
     class A ;
         int j;

         static task incr();
             j++;
             $display("J is %d",j);
         endtask
     endclass
    
     program main ;
         A obj_1;
         A obj_2;
        
         initial
         begin
             obj_1  =  new();
             obj_2  =  new();
             obj_1.incr();
             obj_2.incr();
         end
     endprogram

RESULT

A static method has no access to nonstatic members (class properties or methods).

Static methods cannot be virtual.

EXAMPLE
    class A ;
        int j;

        virtual static task incr();
             $display("J is %d",j);
        endtask
    endclass
RESULT

http://testbench.in/CL_12_STATIC.html[9/26/2012 2:08:32 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

Error : Static methods cannot be virtual.

The static methods can be accessed using class name.

EXAMPLE: using class name


     class A ;
          static task who();
               $display(" Im static method ");
          endtask
     endclass
    
     program main;
        initial
            A.who();
     endprogram

RESULT

Im static method.

The static methods can be used without creating an object of that type.

EXAMPLE: without creating object


     class A ;
          static task who();
               $display(" Im static method ");
          endtask
     endclass
    
     program main;
         A a;

         initial
            a.who();
     endprogram

RESULT

Im static method.

Static Lifetime Method.

By default, class methods have automatic lifetime for their arguments and
variables.    
All variables of a static lifetime method shall be static in that there shall be a single
variable corresponding to each declared local variable in a class  , regardless of the
number of concurrent activations of the method.

EXAMPLE
class A ;
  
    task static incr();
        int i; //static variable
        $display(" i is %d ",i);
        i++;
    endtask
endclass
    
program main;
    A a;
    A b;
 
    initial
    begin
      $display("Static lifetime - non static task with static variables"); 

http://testbench.in/CL_12_STATIC.html[9/26/2012 2:08:32 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

      a = new();
      b = new();
      a.incr();
      b.incr();
      a.incr();
      b.incr();
      a.incr();
      $display("Static lifetime - Each call to task will use a single value of 'j' and
increment it");
    end
endprogram

RESULT

Static lifetime - non static task with static variables


 i is           0
 i is           1
 i is           2
 i is           3
 i is           4
Static lifetime - Each call to task will use a single value of 'j' and increment it

Verilog-2001 allows tasks to be declared as automatic, so that all formal arguments


and local variables are stored on the stack. SystemVerilog extends this capability by
allowing specific formal arguments and local variables to be declared as automatic
within a static task, or by declaring specific formal arguments and local variables as
static within an automatic task.

By default, class methods have  automatic lifetime for their arguments  and variables.

EXAMPLE
class packet;
    static int id;
    //----static task using automatic fields ---//
    static task packet_id();
       int count;   // by default static task fields are automatic
       id=count;    // writing in to static variable
       $display("id=%d count=%d",id,count);
       count++;    
    endtask 

    function new();
       int pckt_type;
       pckt_type++;
       $display("pckt_type=%d",pckt_type);
    endfunction 

endclass
    
program stic_1;
    packet jumbo,pause,taggd;

    initial
    begin

       jumbo=new();
       jumbo.packt_id();
       pause=new();
       pause.packt_id();
       taggd=new();
       taggd.packt_id();
    
    end 
endprogram
  
RESULTS

 pckt_type=  1; id=  0;  count=          0
 pckt_type=  1; id=  0 ; count=          0
 pckt_type=  1; id=  0;  count=          0

http://testbench.in/CL_12_STATIC.html[9/26/2012 2:08:32 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

    

SystemVerilog   allows specific formal arguments and local variables to be declared as


automatic within a static task, or by declaring specific formal arguments and local
variables as static within an automatic task.

EXAMPLE
class packet;
    static int id,pckt_type;
    //---static task with static field----//
    static task packt_id();
        static int count;  //explicit declaration of fields as static
        id=count;         //writing in to static variable
        $display("id=%d count=%d",id,count);
         count++;  
    endtask  

    function new();
        pckt_type++;
        $display("pckt_type=%d",pckt_type);
    endfunction

endclass 
    
program stic_2;
    packet jumbo,pause,taggd;

    initial
    begin
        jumbo=new();
        jumbo.packt_id();
        pause=new();
        pause.packt_id();
        taggd=new();
        taggd.packt_id();
    
    end  
endprogram
  
RESULTS

 pckt_type=  1;  id=  0 count=  0;
 pckt_type=  2;  id=  1 count=  1;
 pckt_type=  3 ; id=  2 count=  2;

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CL_12_STATIC.html[9/26/2012 2:08:32 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS CASTING Index


Introduction
SystemVerilog Class
Verification It is always legal to assign a subclass variable to a variable of a class higher in the Object
inheritance tree. This
Constructs Inheritance
Interface EXAMPLE Encapsulation
     class parent; Polymorphism
OOPS Abstract Classes
          int i = 10;
Randomization      endclass Parameterised Class
     Nested Classes
Functional Coverage Constant
     class subclass extends parent;
Assertion           int j; Static
Casting
DPI Copy
          function new();
UVM Tutorial               j = super.i; Scope Resolution
              $display("J is %d",j); Operator
VMM Tutorial Null
          endfunction
OVM Tutorial      endclass External Declaration
     Classes And Structures
Easy Labs : SV
     program main; Typedef Class
Easy Labs : UVM          initial Pure
         begin Other Oops Features
Easy Labs : OVM
             subclass s; Misc
Easy Labs : VMM              s = new();
AVM Switch TB          end Report a Bug or Comment
     endprogram on This section - Your
VMM Ethernet sample RESULT input is what keeps
Testbench.in improving
J is          10 with time!
Verilog
Verification
Verilog Switch TB It is never legal to directly assign a superclass variable to a variable of one of its
Basic Constructs subclasses.

However, it is legal to assign a superclass handle to a subclass variable if the


superclass handle refers to an object of the given subclass.
OpenVera
Constructs SystemVerilog provides the $cast system task to assign values to variables that might
Switch TB not ordinarily be valid because of differing data type. To check whether the
assignment is legal, the dynamic cast function $cast() is used . The syntax for $cast()
RVM Switch TB is as follows:
RVM Ethernet sample
task $cast( singular dest_handle, singular source_handle );
or
function int $cast( singular dest_handle, singular source_handle );
Specman E
Interview Questions When called as a task, $cast attempts to assign the source expression to the
destination variable. If the assignment is invalid, a run-time error occurs, and the
destination variable is left unchanged.

EXAMPLE : $cast as task


     class B;
         virtual task print();
              $display(" CLASS B ");
         endtask
     endclass
    

http://testbench.in/CL_13_CASTING.html[9/26/2012 2:08:41 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

     class E_1 extends B;
          virtual task print();
              $display(" CLASS E_1 ");
          endtask
     endclass
    
     class E_2 extends B;
          virtual task print();
              $display(" CLASS E_2 ");
          endtask
     endclass
    
     program main;
         initial
         begin
             B b;
             E_1 e1;
             E_2 e2;
            
             e1 = new();
             $cast(b,e1);
             b.print();
            
         end
     endprogram
RESULT

 CLASS E_1

EXAMPLE : $cast as task with error


     class B;
         virtual task print();
              $display(" CLASS B ");
         endtask
     endclass
    
     class E_1 extends B;
          virtual task print();
              $display(" CLASS E_1 ");
          endtask
     endclass
    
     class E_2 extends B;
          virtual task print();
              $display(" CLASS E_2 ");
          endtask
     endclass
    
     program main;
          initial
          begin
              B b;
              E_1 e1;
              E_2 e2;
              
              e1 = new();
              $cast(e2,e1);
          
          end
     endprogram
RESULT

Error: Dynamic cast failed

When called as a function, $cast attempts to assign the source expression to the
destination variable and returns 1 if the cast is legal. If the cast fails, the function

http://testbench.in/CL_13_CASTING.html[9/26/2012 2:08:41 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

does not make the assignment and returns 0. When called as a function, no run-time
error occurs, and the destination variable is left unchanged. It is important to note
that $cast performs a run-time check. No type checking is done by the compiler,
except to check that the destination variable and source expression are singulars.

EXAMPLE : $cast as function


     class B;
          virtual task print();
               $display(" CLASS B ");
          endtask
     endclass
    
     class E_1 extends B;
          virtual task print();
               $display(" CLASS E_1 ");
          endtask
     endclass
    
     class E_2 extends B;
          virtual task print();
               $display(" CLASS E_2 ");
          endtask
     endclass
    
     program main;
          initial
          begin
               B b;
               E_1 e1;
               E_2 e2;
              
               e1 = new();
//calling $cast like a task
//Return value is not considered
               $cast(b,e1);
               which_class(b);
              
               e2 = new();
//calling $cast like a task
//Return value is not considered
               $cast(b,e2);
               which_class(b);
              
          end
     endprogram

     task which_class(B b);


          E_1 e1;
          E_2 e2;
//calling $cast like a function
//Return value is considered for action
          if($cast(e1,b))
               $display(" CLASS E_1 ");
          if($cast(e2,b))
               $display(" CLASS E_2 ");
     endtask
RESULT

 CLASS E_1
 CLASS E_2

When used with object handles, $cast() checks the hierarchy tree (super and
subclasses) of the source_expr to see whether it contains the class of dest_handle. If
it does, $cast() does the assignment. Otherwise, the error is issued.

Assignment of Extended class object to Base class object is allowed. It is Illegal to


assign Base class object to Extended class.

http://testbench.in/CL_13_CASTING.html[9/26/2012 2:08:41 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

EXAMPLE
      class Base;
      endclass
      
      class Exten extends Base;
      endclass
      
      program main;
      
           initial
           begin
               Base B;
               Exten E;
               B = new();
               if(!$cast(E,B))
                    $display(" Base class object B canot be assigned to Extended class
Handle.");
               // Deallocate object B
               B = null;
               E = new();
               if(!$cast(B,E))
                    $display(" Extended class object E canot be assigned to Base class
Handle.");
           end
      endprogram

RESULT

Base class object B canot be assigned to Extended class Handle.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CL_13_CASTING.html[9/26/2012 2:08:41 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS COPY Index


Introduction
SystemVerilog The terms "deep copy" and "shallow copy" refer to the way objects are Class
Verification copied, for example, during the invocation of a copy constructor or assignment Object
operator.  This
Constructs Inheritance
Interface EXAMPLE: Encapsulation
     class B; Polymorphism
OOPS Abstract Classes
         int i;
Randomization      endclass Parameterised Class
     Nested Classes
Functional Coverage Constant
     program main;
Assertion          initial Static
         begin Casting
DPI Copy
             B b1;
UVM Tutorial              B b2; Scope Resolution
             b1 = new(); Operator
VMM Tutorial Null
             b1.i = 123;
OVM Tutorial              b2 = b1; External Declaration
             $display( b2.i ); Classes And Structures
Easy Labs : SV
         end Typedef Class
Easy Labs : UVM      endprogram Pure
RESULTS: Other Oops Features
Easy Labs : OVM
Misc
Easy Labs : VMM 123
AVM Switch TB Report a Bug or Comment
on This section - Your
VMM Ethernet sample input is what keeps
In the above example, both objects are pointing to same memory. The properties did Testbench.in improving
not get copied. Only the handle is copied. with time!
Verilog
Verification Shallow Copy
Verilog Switch TB A shallow copy of an object copies all of the member field values.
Basic Constructs
EXAMPLE:
     class B;
         int i;
OpenVera      endclass
Constructs     
Switch TB      program main;
          initial
RVM Switch TB           begin
RVM Ethernet sample               B b1;
              B b2;
              b1 = new();
              b1.i = 123;
Specman E               b2 = new b1;
Interview Questions               b2.i = 321;
              $display( b1.i );
              $display( b2.i );
          end
     endprogram
    
RESULTS:

        123
        321

http://testbench.in/CL_14_COPY.html[9/26/2012 2:08:49 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

This works well if the fields are values, but may not be what you want for fields that
point to dynamically allocated memory. The pointer will be copied. but the memory it
points to will not be copied -- the field in both the original object and the copy will
then point to the same dynamically allocated memory, which is not usually what you
want. The assignment operator make shallow copies.

EXAMPLE:
     class A;
         int i;
     endclass
    
     class B;
          A a;
     endclass
    
     program main;
         initial
         begin
              B b1;
              B b2;
              b1 = new();
              b1.a = new();
              b1.a.i = 123;
              b2 = new b1;
              $display( b1.a.i );
              $display( b2.a.i );
              b1.a.i = 321;
              $display( b1.a.i );
              $display( b2.a.i );
        
         end
     endprogram
RESULT

        123
        123
        321
        321

In the above example, the varible i is changed to which is inside the object of .  This
changes in seen in also because both the objects are pointing to same memory
location.

Deep Copy

A deep copy copies all fields, and makes copies of dynamically allocated memory
pointed to by the fields. To make a deep copy, you must write a copy constructor and
overload the assignment operator, otherwise the copy will point to the original, with
disasterous consequences.

EXAMPLE:
    class A;
        int i;
    endclass
    
    class B;
        A a;

        task copy(A a);
            this.a = new a;
        endtask

    endclass

http://testbench.in/CL_14_COPY.html[9/26/2012 2:08:49 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

    
    program main;
        initial
        begin
            B b1;
            B b2;
            b1 = new();
            b1.a = new();
            b1.a.i = 123;
            b2 = new b1;
            b2.copy(b1.a);
            $display( b1.a.i );
            $display( b2.a.i );
            b1.a.i = 321;
            $display( b1.a.i );
            $display( b2.a.i );
            
        end
    endprogram

RESULTS:

        123
        123
        321
        123

Clone

A clone method returns a new object whose initial state is a copy of the current state
of the object on which clone was invoked. Subsequent changes to the clone will not
affect the state of the original. Copying is usually performed by a clone() method
method of a class which is user defined. This method usually, in turn, calls the clone()
method of its parent class to obtain a copy, and then does any custom copying
procedures. Eventually this gets to the clone() method of Object (the uppermost
class), which creates a new instance of the same class as the object and copies all the
fields to the new instance (a "shallow copy"). After obtaining a copy from the parent
class, a class's own clone() method may then provide custom cloning capability, like
deep copying (i.e. duplicate some of the structures referred to by the object) .

One disadvantage is that the return type of clone() is Object, and needs to be
explicitly cast back into the appropriate type (technically a custom clone() method
could return another type of object; but that is generally inadvisable).

One advantage of using clone() is that since it is an overridable method, we can call
clone() on any object, and it will use the clone() method of its actual class, without
the calling code needing to know what that class is (which would be necessary with a
copy constructor).

EXAMPLE:
????

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CL_14_COPY.html[9/26/2012 2:08:49 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS SCOPE RESOLUTION OPERATOR Index


Introduction
SystemVerilog Class
Verification Object
EXAMPLE: This
Constructs      class Base; Inheritance
Interface          typedef enum {bin,oct,dec,hex} radix; Encapsulation
Polymorphism
OOPS Abstract Classes
         task print( radix r, integer n ); 
Randomization               $display(" Enum is %s ",r.name()); Parameterised Class
              $display(" Val is %d",n); Nested Classes
Functional Coverage Constant
         endtask
Assertion      endclass Static
     Casting
DPI Copy
     program main;
UVM Tutorial          initial Scope Resolution
         begin Operator
VMM Tutorial Null
             Base b = new;
OVM Tutorial              int bin = 123; External Declaration
             b.print( Base::bin, bin ); // Base::bin and bin are different Classes And Structures
Easy Labs : SV
         end Typedef Class
Easy Labs : UVM      endprogram Pure
     Other Oops Features
Easy Labs : OVM
RESULT: Misc
Easy Labs : VMM
AVM Switch TB Enum is bin Report a Bug or Comment
Val is  123 on This section - Your
VMM Ethernet sample input is what keeps
Testbench.in improving
with time!
Verilog In addition, to disambiguating class scope identifiers, the :: operator also allows
Verification access to static members (class properties and methods) from outside the class,
Verilog Switch TB
Basic Constructs EXAMPLE:
     class Base;
          typedef enum {bin,oct,dec,hex} radix;
OpenVera           task print( radix r, integer n ); 
Constructs                $display(" Enum is %s ",r.name());
Switch TB                $display(" Val is %d",n);
          endtask
RVM Switch TB      endclass
RVM Ethernet sample     
     program main;

         initial
Specman E          begin
Interview Questions              int bin = 123;
             Base::print( Base::bin, bin ); // Base::bin and bin are different
         end
     endprogram
    
RESULT:

Enum is bin
Val is  123

http://testbench.in/CL_15_SCOPE_RESOLUTION_OPERATOR.html[9/26/2012 2:08:56 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

Scope resolution operator ::  can be used to access to public or protected elements of


a superclass from within the derived classes.

EXAMPLE:
    class Base;
        typedef enum {bin,oct,dec,hex} radix;
    endclass
    
    class Ext extends Base;
        typedef enum {dec,hex,bin,oct} radix;
        
        task print(); 
            $display(" Ext  classs :: enum values %d %d %d %d ",bin,oct,dec,hex);
            $display(" Base classs :: enum values %d %d %d %d
",Base::bin,Base::oct,Base::dec,Base::hex);
        endtask
    
    endclass
    
    program main;
        initial
        begin
            Ext e;
            e = new();
            e.print();
        end
    endprogram
RESULT:

 Ext  classs :: enum values           2           3           0           1


 Base classs :: enum values           0           1           2           3

In SystemVerilog, the class scope resolution operator applies to all static elements of
a class: static class properties, static methods, typedefs, enumerations, structures,
unions, and nested class declarations. Class scope resolved expressions can be read (in
expressions), written (in assignments or subroutines calls), or triggered off (in event
expressions). They can also be used as the name of a type or a method call.

The class scope resolution operator enables the following:


Access to static public members (methods and class properties) from outside the
class hierarchy.
Access to public or protected class members of a superclass from within the
derived classes.
Access to type declarations and enumeration named constants declared inside the
class from outside the class hierarchy or from within derived classes.

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/CL_15_SCOPE_RESOLUTION_OPERATOR.html[9/26/2012 2:08:56 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CL_15_SCOPE_RESOLUTION_OPERATOR.html[9/26/2012 2:08:56 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS NULL Index


Introduction
SystemVerilog The Null is perhaps the most "intelligent" pattern of all. It knows exactly what to do Class
Verification all the time, every time. Its does nothing. The Null is somewhat difficult to describe, Object
since it resides in an abstract hierarchy tree, having no particular place at all, but This
Constructs occupying many roles. It is somewhat like the mathematical concept of zero: it is a Inheritance
Interface placeholder, but is in itself nothing, and has no value. Null Object is a behavioral Encapsulation
pattern designed to act as a default value of an object in most OOPs tools. These Polymorphism
OOPS Abstract Classes
references need to be checked to ensure they are not null before invoking any
Randomization methods, because one can't invoke anything on a null reference; this tends to make Parameterised Class
code less readable. If you forgot to creat an object ane passed it to method, where Nested Classes
Functional Coverage Constant
the method has some operation on the object, the simulation fails.  So , If the method
Assertion is expecting an object , then check weathe the object is created or not else take Static
nessesary action.  The advantage of this approach over a working default Casting
DPI Copy
implementation is that a Null Object is very predictable and has no side effects.
UVM Tutorial Scope Resolution
Operator
VMM Tutorial Null
EXAMPLE
OVM Tutorial      class B; External Declaration
Classes And Structures
Easy Labs : SV
          task printf(); Typedef Class
Easy Labs : UVM                $display(" Hi "); Pure
          endtask Other Oops Features
Easy Labs : OVM
     endclass Misc
Easy Labs : VMM     
AVM Switch TB      program main; Report a Bug or Comment
         initial on This section - Your
VMM Ethernet sample          begin input is what keeps
             B b; Testbench.in improving
             print(b); with time!
Verilog          end
Verification      endprogram
    
Verilog Switch TB      task print(B b);
Basic Constructs          if(b == null)
             $display(" b Object is not created ");
         else
             b.printf();
OpenVera      endtask
Constructs
Switch TB
RESULT:
RVM Switch TB
RVM Ethernet sample b Object is not created

Specman E
Interview Questions

http://testbench.in/CL_16_NULL.html[9/26/2012 2:09:04 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CL_16_NULL.html[9/26/2012 2:09:04 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS EXTERNAL DECLARATION Index


Introduction
SystemVerilog Class methods and Constraints can be defined in the following places: Class
Verification inside a class. Object
This
Constructs outside a class in the same file. Inheritance
outside a class in a separate file. Encapsulation
Interface
Polymorphism
OOPS The process of declaring an out of block method involves: Abstract Classes
Randomization
declaring the method prototype or constraint within the class declaration with Parameterised Class
extern qualifier. Nested Classes
Functional Coverage declaring the full method or constraint outside the class body. Constant
Assertion Static
The extern qualifier indicates that the body of the method (its implementation) or Casting
DPI constraint block is to be found outside the declaration. Copy
UVM Tutorial Scope Resolution
NOTE :  class scope resolution operator :: should be used while defining. Operator
VMM Tutorial Null
OVM Tutorial External Declaration
EXAMPLE: Classes And Structures
Easy Labs : SV     class B; Typedef Class
Easy Labs : UVM         extern task printf(); Pure
    endclass Other Oops Features
Easy Labs : OVM
     Misc
Easy Labs : VMM     task B::printf();
AVM Switch TB
        $display(" Hi "); Report a Bug or Comment
    endtask on This section - Your
VMM Ethernet sample      input is what keeps
    program main; Testbench.in improving
        initial with time!
Verilog         begin
            B b;
Verification             b = new();
Verilog Switch TB             b.printf();
        end
Basic Constructs
    endprogram

OpenVera RESULT:
Constructs
Hi
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/CL_17_EXTERNAL_DECLARATION.html[9/26/2012 2:09:11 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CL_17_EXTERNAL_DECLARATION.html[9/26/2012 2:09:11 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS CLASSES AND STRUCTURES Index


Introduction
SystemVerilog class differs from struct in three fundamental ways: Class
Verification Object
SystemVerilog structs are strictly static objects; they are created either in a static This
Constructs Inheritance
memory location (global or module scope) or on the stack of an automatic task.
Interface Conversely, SystemVerilog objects (i.e., class instances) are exclusively dynamic; Encapsulation
their declaration does not create the object. Creating an object is done by calling Polymorphism
OOPS Abstract Classes
new.
Randomization Parameterised Class
Nested Classes
Functional Coverage SystemVerilog objects are implemented using handles, thereby providing C-like Constant
pointer functionality. But, SystemVerilog disallows casting handles onto other data Static
Assertion types; thus, unlike C, SystemVerilog handles are guaranteed to be safe. Casting
DPI Copy
UVM Tutorial
SystemVerilog objects form the basis of an Object-Oriented data abstraction that Scope Resolution
provides true polymorphism. Class inheritance, abstract classes, and dynamic casting Operator
VMM Tutorial are powerful mechanisms that go way beyond the mere encapsulation mechanism Null
OVM Tutorial provided by structs. External Declaration
Classes And Structures
Easy Labs : SV
Typedef Class
Easy Labs : UVM Pure
Other Oops Features
Easy Labs : OVM
Misc
Easy Labs : VMM
AVM Switch TB Report a Bug or Comment
on This section - Your
VMM Ethernet sample input is what keeps
Testbench.in improving
with time!
Verilog
Verification
Verilog Switch TB
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/CL_18_CLASSES_AND_STRUCTURES.html[9/26/2012 2:09:19 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CL_18_CLASSES_AND_STRUCTURES.html[9/26/2012 2:09:19 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS TYPEDEF CLASS Index


Introduction
SystemVerilog Forward Reference Class
Verification Object
A forward declaration is a declaration of a object which the programmer has not yet This
Constructs given a complete definition. The term forward reference is sometimes used as a Inheritance
Interface synonym of forward declaration. However, more often it is taken to refer to the Encapsulation
actual use of an entity before any declaration. The SystemVerilog language supports Polymorphism
OOPS Abstract Classes
the typedef class construct for forward referencing of a class declaration. This allows
Randomization for the compiler to read a file from beginning to end without concern for the Parameterised Class
positioning of the class declaration. Nested Classes
Functional Coverage Constant
Assertion EXAMPLE: Static
    class Y ; Casting
DPI Copy
        X x; // refers to Class X, which is not yet defined
UVM Tutorial     endclass Scope Resolution
     Operator
VMM Tutorial Null
    class X;
OVM Tutorial         int i; External Declaration
    endclass Classes And Structures
Easy Labs : SV
Typedef Class
Easy Labs : UVM RESULT Pure
Other Oops Features
Easy Labs : OVM
Error : Class X is not defined Misc
Easy Labs : VMM
AVM Switch TB Report a Bug or Comment
on This section - Your
VMM Ethernet sample When the compiler encounters the handle x of class type X referred to in class Y, it input is what keeps
does not yet know the definition for class X since it is later in the file. Thus, Testbench.in improving
compilation fails. with time!
Verilog To rectify this situation, typedef is used to forward reference the class declaration.
Verification
Verilog Switch TB EXAMPLE:
Basic Constructs     typedef class X;
    class Y ;
        X x; // refers to Class X, which is not yet defined
    endclass
OpenVera     
Constructs     class X;
Switch TB         int i;
    endclass
RVM Switch TB
RVM Ethernet sample
The typedef of class X allows the compiler to process Y before X is fully defined. Note
that typedef cannot be used to forward reference a class definition in another file.
This must be done using the inclusion of a header file.
Specman E
Interview Questions
Circular Dependency

A Circular dependency is a situation which can occur in programming languages


wherein the definition of an object includes the object itself.  One famous example is
Linked List.

EXAMPLE:
   class Y ;
      int i;

http://testbench.in/CL_19_TYPEDEF_CLASS.html[9/26/2012 2:09:26 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

      Y y; // refers to Class Y, which is not yet defined


   endclass

As you seen, there is a compilation error. To avoid this situation, typedef is used to
forward reference the class declaration and this circular dependency problem can be
avoided.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CL_19_TYPEDEF_CLASS.html[9/26/2012 2:09:26 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PURE Index


Introduction
SystemVerilog Class
Verification As we have already seen in the previous topics , a virtual method may or may not be Object
overridden in the derived lasses. It means, it is not necessary for a derived class to This
Constructs override a virtual method. Inheritance
Interface Encapsulation
But there are times when a base class is not able to define anything meaningful for Polymorphism
OOPS Abstract Classes
the virtual method in that case every derived class must provide its own definition of
Randomization the that method. Parameterised Class
Nested Classes
Functional Coverage Constant
A pure virtual method is a virtual method that you want to force derived classes to
Assertion override. If a class has any unoverridden pure virtuals, it is an "abstract class" and you Static
can't create objects of that type. Casting
DPI Copy
UVM Tutorial " pure virtual function " or " pure virtual task " declaration is supposed to represent Scope Resolution
the fact that the method has no implementation. Operator
VMM Tutorial Null
OVM Tutorial There are two major differences between a virtual and a pure virtual function, these External Declaration
are below: Classes And Structures
Easy Labs : SV
Typedef Class
Easy Labs : UVM There CAN'T be a definition of the pure virtual function in the base class. Pure
Other Oops Features
Easy Labs : OVM There MUST be a definition of the pure virtual function in the derived class. Misc
Easy Labs : VMM
AVM Switch TB Report a Bug or Comment
EXAMPLE:
on This section - Your
VMM Ethernet sample     class Base; input is what keeps
        pure virtual task disp();
Testbench.in improving
    end class
with time!
    
Verilog     program main
Verification         initial
        begin
Verilog Switch TB
            Base B;
Basic Constructs             B = new();
            B.disp();
        end
OpenVera     endprogram
Constructs RESULT
Switch TB
Error: pure virtual task disp(); must be overridden in derived class
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/CL_20_PURE.html[9/26/2012 2:09:34 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CL_20_PURE.html[9/26/2012 2:09:34 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS OTHER OOPS FEATURES Index


Introduction
SystemVerilog Class
Verification Multiple inheritence and Function overloading  and the OOPs features which are not Object
supported by System Verilog. This
Constructs Inheritance
Interface Encapsulation
Multiple Inheritence Polymorphism
OOPS Abstract Classes
Randomization Multiple inheritance refers to a feature of some object-oriented programming Parameterised Class
languages in which a class can inherit behaviors and features from more than one Nested Classes
Functional Coverage Constant
superclass. This contrasts with single inheritance, where a class may inherit from at
Assertion most one superclass. SystemC supports multiple inheritance, SystemVerilog supports Static
only single inheritance. Casting
DPI Copy
UVM Tutorial  Multiple inheritance allows a class to take on functionality from multiple other Scope Resolution
classes, such as allowing a class named D to inherit from a class named A, a class Operator
VMM Tutorial Null
named B, and a class named C.
OVM Tutorial External Declaration
Classes And Structures
Easy Labs : SV
EXAMPLE: Typedef Class
Easy Labs : UVM      class A; Pure
         ..... Other Oops Features
Easy Labs : OVM
     endclass Misc
Easy Labs : VMM     
AVM Switch TB      class B; Report a Bug or Comment
         ...... on This section - Your
VMM Ethernet sample      endclass input is what keeps
     Testbench.in improving
     class C; with time!
Verilog          ......
Verification      endclass
    
Verilog Switch TB      class D extends A,B,C;
Basic Constructs          .....
     endclass

Multiple inheritance is not implemented well in SystemVerilog languages .


OpenVera Implementation problems include:
Constructs Increased complexity
Switch TB Not being able to explicitly inherit from multiple times from a single class
RVM Switch TB Order of inheritance changing class semantics.
RVM Ethernet sample
Method Overloading

Specman E Method overloading is the practice of declaring the same method with different
signatures. The same method name will be used with different data type . This is Not
Interview Questions Supported by SystemVerilog as of 2008.

EXAMPLE:
     task my_task(integer i) { ... }
     task my_task(string s) { ... }

     program test {
       integer number = 10;
       string name = "vera";
       my_task(number);

http://testbench.in/CL_21_OTHER_OOPS_FEATURES.html[9/26/2012 2:09:43 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

       my_task(name);
     } 

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CL_21_OTHER_OOPS_FEATURES.html[9/26/2012 2:09:43 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS MISC Index


Introduction
SystemVerilog Always Block In Classes Class
Verification Object
This
Constructs SystemVerilog doesnot allow to define always block in program block or class, as Inheritance
Interface these are meant for testbench purpose.   Encapsulation
Polymorphism
OOPS Abstract Classes
Example to show the implimentation of always block in program block.
Randomization Parameterised Class
EXAMPLE: Nested Classes
Functional Coverage Constant
     program main;
Assertion      Static
          integer a,b; Casting
DPI Copy
          
UVM Tutorial           initial Scope Resolution
              repeat(4) Operator
VMM Tutorial Null
              begin
OVM Tutorial                   #({$random()}%20) External Declaration
                  a = $random(); Classes And Structures
Easy Labs : SV
                  #({$random()}%20) Typedef Class
Easy Labs : UVM                   b = $random(); Pure
              end Other Oops Features
Easy Labs : OVM
           Misc
Easy Labs : VMM           initial
AVM Switch TB              always_task(); Report a Bug or Comment
           on This section - Your
VMM Ethernet sample            input is what keeps
          task always_task(); Testbench.in improving
          fork with time!
Verilog               forever
Verification                  begin
                    @(a,b);
Verilog Switch TB                     $display(" a is %d : b is %d at %t ",a,b,$time);
Basic Constructs                  end
          join_none
          endtask
    
OpenVera      endprogram
Constructs
Switch TB RESULT
RVM Switch TB a is -1064739199 : b is           x at                    8
RVM Ethernet sample a is -1064739199 : b is -1309649309 at                   25
a is  1189058957 : b is -1309649309 at                   42
a is  1189058957 : b is -1992863214 at                   47
a is   114806029 : b is -1992863214 at                   48
Specman E a is   114806029 : b is   512609597 at                   66
Interview Questions a is  1177417612 : b is   512609597 at                   75
a is  1177417612 : b is  -482925370 at                   84

Example to show the implimentation of always block in class.

EXAMPLE
    class Base;
       integer a,b;

http://testbench.in/CL_22_MISC.html[9/26/2012 2:09:52 PM]


WWW.TESTBENCH.IN - Systemverilog OOPS

      
       task always_task();
       fork
           forever
           begin
              @(a,b);
              $display(" a is %d : b is %d at %t ",a,b,$time);
           end
       join_none
       endtask
      
    endclass
    
    program main;
    
        initial
        begin
            Base obj;
            obj = new();
            // start the always block.
            fork
                obj.always_task();
            join_none
            repeat(4)
                begin
                   #({$random()}%20)
                   obj.a = $random();
                   #({$random()}%20)
                   obj.b = $random();
                end
        
        end
    endprogram

RESULT

 a is -1064739199 : b is           x at                    8


 a is -1064739199 : b is -1309649309 at                   25
 a is  1189058957 : b is -1309649309 at                   42
 a is  1189058957 : b is -1992863214 at                   47
 a is   114806029 : b is -1992863214 at                   48
 a is   114806029 : b is   512609597 at                   66
 a is  1177417612 : b is   512609597 at                   75
 a is  1177417612 : b is  -482925370 at                   84

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CL_22_MISC.html[9/26/2012 2:09:52 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS CONSTRAINED RANDOM VERIFICATION Index


Constrained Random
SystemVerilog Introduction : Verification
Verification Verilog Crv
Historically,verification engineers used directed test bench to verify the functionality Systemverilog Crv
Constructs of their design.Rapid changes have occurred during the past decades in design and Randomizing Objects
Interface verification.High Level Verification Languages (HVLS) such as e, System Random Variables
c,Vera,SystemVerilog have become a necessity for verification environments. Randomization Methods
OOPS Checker
Randomization Constraint Random stimulus generation is not new. Everybody uses verilog and VHDL Constraint Block
at very low level abstraction for this purpose. HVLS provide constructs to express Inline Constraint
Functional Coverage Global Constraint
specification of stimulus at high level of abstraction and constraint solver generates
Assertion legal stimulus. Constraint Mode
External Constraints
DPI Randomization
UVM Tutorial Writing constraints at higher level of absctraction,makes the programming closer to Controlability
spec. Static Constraint
VMM Tutorial Constraint Expression
OVM Tutorial A constraint language should support: Variable Ordering
Constraint Solver Speed
Easy Labs : SV
Expressions to complex scenarios. Randcase
Easy Labs : UVM Randsequence
Felxibility to control dynamically. Random Stability
Easy Labs : OVM Combinational and sequential constraints. Array Randomization
Easy Labs : VMM Constraint Guards
AVM Switch TB Titbits
EXAMPLE:
VMM Ethernet sample Report a Bug or Comment
Combinational constraint : on This section - Your
  In ethernet, 13 & 14 th bytes should be equal to payload length. input is what keeps
Verilog Testbench.in improving
Sequential constraint: with time!
Verification   If request comes, then acknoldegement should be given between 4th to 10th cycles.
Verilog Switch TB
NOTE:SystemVerilog doec not support sequential constraints.
Basic Constructs
This article is about Constrained random verification using SystemVerilog.I tried to
explain every point using examples.
OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/CR_01_CONSTRAINED_RANDOM_VERIFICATION.html[9/26/2012 2:10:00 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CR_01_CONSTRAINED_RANDOM_VERIFICATION.html[9/26/2012 2:10:00 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS VERILOG CRV Index


Constrained Random
SystemVerilog Constrained Random Stimulus Generation In Verilog: Verification
Verification Verilog Crv
 Verilog has system function $random, which can be used to generate random input Systemverilog Crv
Constructs vectors. With this approach,we can generate values which we wouldnt have got, if Randomizing Objects
Interface listed manually. In this topic I would like to discuss what natural things happening Random Variables
behind $random and how we use it in different manners. Randomization Methods
OOPS Checker
Randomization Constraint Block
EXAMPLE: Inline Constraint
Functional Coverage Global Constraint
    module Tb_mem();
Assertion         reg clock; Constraint Mode
        reg read_write; External Constraints
DPI Randomization
        reg [31:0] data;
UVM Tutorial         reg [31:0] address; Controlability
         Static Constraint
VMM Tutorial Constraint Expression
        initial
OVM Tutorial         begin Variable Ordering
          clock = 0; Constraint Solver Speed
Easy Labs : SV
          forever #10 clock = ~clock; Randcase
Easy Labs : UVM         end Randsequence
         Random Stability
Easy Labs : OVM
        initial Array Randomization
Easy Labs : VMM         begin Constraint Guards
AVM Switch TB            repeat(5)@(negedge clock)  Titbits
           begin
VMM Ethernet sample              read_write = $random ; data = $random; address = $random;  Report a Bug or Comment
             $display($time," read_write = %d ; data = %d ; address = on This section - Your
%d;",read_write,data,address); input is what keeps
Verilog            end Testbench.in improving
           #10 $finish; with time!
Verification
        end
Verilog Switch TB         
Basic Constructs         
    endmodule

OpenVera RESULT:
Constructs
Switch TB                   20 read_write = 0 ; data = 3230228097 ; address = 2223298057;
                  40 read_write = 1 ; data = 112818957 ; address = 1189058957;
RVM Switch TB                   60 read_write = 1 ; data = 2302104082 ; address = 15983361;
RVM Ethernet sample                   80 read_write = 1 ; data = 992211318 ; address = 512609597;
                 100 read_write = 1 ; data = 1177417612 ; address = 2097015289;

Specman E
Interview Questions $random  system function returns a new 32-bit random number each time it is called.
The random number is a signed integer; it can be positive or negative.The following
example demonstrates random generation of signed numbers.

EXAMPLE:
   module Tb();
      integer address;
      
      initial
      begin

http://testbench.in/CR_02_VERILOG_CRV.html[9/26/2012 2:10:12 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

         repeat(5)
         #1 address = $random;
      end
      
      initial
          $monitor("address = %0d;",address);
      
   endmodule

RESULT:

address = 303379748;
address = -1064739199;
address = -2071669239;
address = -1309649309;
address = 112818957;

We have seen how to generate random numbers.But the numbers randge from - (2**32
-1) to 2 **32. Most of the time, the requirement is dont need this range. For example,
take a memory. The address starts from 0 to some 1k or 1m.Generating a random
address which DUT is not supporting is meaning less. In verilog there are no constructs
to constraint randomization. Following example demonstrated how to generate
random number between 0 to 10.Using % operation,the remainder of any number is
always between 0 to 10.

EXAMPLE:
    module Tb();
       integer add_1;
       initial
       begin
           repeat(5)
           begin
              #1;
              add_1 = $random % 10;
           end
       end
      
       initial
           $monitor("add_1 = %0d",add_1);
      
    endmodule

RESULT:

add_1 = 8;
add_1 = 4294967287;
add_1 = 4294967295;
add_1 = 9;

http://testbench.in/CR_02_VERILOG_CRV.html[9/26/2012 2:10:12 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

add_1 = 9;

OOPS!...... The results are not what is expected.The reason is $random generates
negative numbers also. The following example demonstrates proper way of generating
a random number between 0 to 10. Concatenation operator returns only bitvector. Bit
vectors are unsigned, so the results are correct as we expected. Verilog also has
$unsigned systemtask to convert signed numbers to signed number.This can also be
used to meet the requirements. The following example shows the usage of
concatenation operator and $unsigned.

EXAMPLE:
    module Tb();
        integer add_2;
        reg [31:0] add_1;
        integer add_3;
        
        initial
           begin
           repeat(5)
           begin
              #1;
              add_1 = $random % 10;
              add_2 = {$random} %10 ;
              add_3 = $unsigned($random) %10 ;
           end
        end
        
        initial
            $monitor("add_3 = %0d;add_2 = %0d;add_1 = %0d",add_3,add_2,add_1);
    
    endmodule

RESULT:

add_3 = 7;add_2 = 7;add_1 = 8


add_3 = 7;add_2 = 7;add_1 = 4
add_3 = 1;add_2 = 2;add_1 = 4
add_3 = 7;add_2 = 8;add_1 = 9
add_3 = 9;add_2 = 2;add_1 = 9

The above example shows the generation of numbers from 0 to N. Some specification
require the range to start from non Zero number. MIN + {$random} % (MAX - MIN ) will
generate random numbers between MIN and MAX.

EXAMPLE:
    module Tb();
       integer add;
      
       initial
       begin
          repeat(5)
             begin
             #1;
             add = 40 + {$random} % (50 - 40) ;
             $display("add = %0d",add);
             end
       end
    endmodule

RESULT:

add = 48
add = 47
add = 47
add = 47
add = 47

Now  how to generate a random number between two ranges? The number should be
between MIN1 and MAX1 or MIN2 and MAX2. The following example show how to

http://testbench.in/CR_02_VERILOG_CRV.html[9/26/2012 2:10:12 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

generate this specification.

EXAMPLE:
    module Tb();
    integer add;
    
    initial
    begin
        repeat(5)
        begin
           #1;
           if($random % 2)
              add = 40 + {$random} % (50 - 40) ;
           else
              add = 90 + {$random} % (100 - 90) ;
           $display("add = %0d",add);
        end
    end
    endmodule

RESULT:

add = 97
add = 47
add = 47
add = 42
add = 49

All the random numbers generated above are 32 bit vectors, which is not always the
same requirement. For example, to generate a 5 bit and 45 bit vector random
number, the following method can be used.

EXAMPLE:
    module Tb();
       reg [4:0]  add_1;
       reg [44:0] add_2;

       initial
       begin
          repeat(5)
          begin
             add_1 = $random ;
             add_2 = {$random,$random};
             $display("add_1 = %b,add_2 = %b ",add_1,add_2);
          end
       end
    endmodule

RESULTS:

add_1 = 00100,add_2 = 111101000000110000100100001001101011000001001


add_1 = 00011,add_2 = 110110000110101000110110111111001100110001101
add_1 = 00101,add_2 = 100100001001000000000111100111110001100000001
add_1 = 01101,add_2 = 100010111011000011110100011011100110100111101
add_1 = 01101,add_2 = 101111000110001111100111111011110100111111001

Some protocols require a random number which is multiple to some number. For
example, Ethernet packet is always in multiples of 8bits. Look at the following
example. It generates a random number which is multiple of 3 and 5.

$random * 3 will give random numbers which are multiples of 3. But if the number
after multiplication needs more than 32 bit to reprasent, then the results may be
wrong.

EXAMPLE:
     module Tb();
     integer num_1,num_2,tmp;

http://testbench.in/CR_02_VERILOG_CRV.html[9/26/2012 2:10:12 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

     initial
     begin
         repeat(5)
         begin
             num_1 =( $random / 3)*3;                    
             num_2 =( $random / 5)*5;                    
             $display("num_1 = %d,num_2 = %d",num_1,num_2);
         end
     end
     endmodule

RESULT:

num_1 = 303379746,num_2 = -1064739195


num_1 = -2071669239,num_2 = -1309649305
num_1 = 112818957,num_2 = 1189058955
num_1 = -1295874969,num_2 = -1992863210
num_1 = 15983361,num_2 = 114806025

All the above examples show that the random numbers are integers only. In verilog
there is no special construct to generate a random real number.The following method
shows generation of random real numbers.

EXAMPLE:
    module Tb();
    integer num_1,num_2,num_3;
    real r_num;
    initial
    begin
       repeat(5)
       begin
          #1;
          num_1 = $random;
          num_2 = $random;
          num_3 = $random;
          r_num = num_1 + ((10)**(-(num_2)))*(num_3);
          $display("r_num = %e",r_num);
       end
    end
    endmodule

RESULT:

r_num = -2.071669e+03
r_num = 2641.189059e+013
r_num = 976361.598336e+01
r_num = 57645.126096e+02
r_num = 24589.097015e+0

To generate random real number , system function $bitstoreal can also be used.

EXAMPLE:
   module Tb();
      real r_num;
      initial
      begin
          repeat(5)
          begin
             #1;
             r_num = $bitstoreal({$random,$random});
             $display("r_num = %e",r_num);
          end
      end
   endmodule

RESULTS:

r_num = 1.466745e-221
r_num = -6.841798e-287
r_num = 2.874848e-276

http://testbench.in/CR_02_VERILOG_CRV.html[9/26/2012 2:10:12 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

r_num = -3.516622e-64
r_num = 4.531144e-304

If you want more control over randomizing real numbers interms of sign, exponential
and mantissa, use $bitstoreal() as shown in example below. For positive numbers use
sgn = 0 and for negative numbers use sgn = 1 .

EXAMPLE:
   module Tb();
      reg  sgn;
      reg [10:0] exp;
      reg [51:0] man; 
      real r_num;

      initial
      begin
          repeat(5)
          begin
              sgn = $random;
              exp = $random;
              man = $random;
              r_num = $bitstoreal({sgn,exp,man});
              $display("r_num = %e",r_num);
          end
      end
   endmodule
RESULTS:

r_num = 3.649952e+193
r_num = -1.414950e-73
r_num = -3.910319e-149
r_num = -4.280878e-196
r_num = -4.327791e+273

Some times it is required to generate random numbers without repetition. The


random numbers should be unique. For example,to generate 10 random numbers
between 0 to 9 without repetition, the following logic can be used.

EXAMPLE:
    module Tb();
        integer num,i,j,index;
        integer arr[9:0];
        reg ind[9:0];
        reg got;
        
        initial
        begin
             index=0;
             for(i=0;i<10;i=i+1)
             begin
                 arr[i] = i;
                 ind[i] = 1;
             end
             for(j = 0;j<10 ;j=j+1)
             begin 
                 got = 0;
                 while(got == 0)
                 begin
                     index = { $random } % 10;
                     if(ind[index] == 1)
                     begin
                       ind[index] = 0;
                       got = 1;
                       num = arr[index];
                     end
                 end
                 $write("| num=%2d |",num);

http://testbench.in/CR_02_VERILOG_CRV.html[9/26/2012 2:10:12 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

             end
        end
    endmodule

RESULT:

| num= 8 || num= 7 || num= 5 || num= 2 || num= 1 || num= 9 || num= 6 || num= 4


|| num= 0 || num= 3 |

Random number returned by $random system function should be deterministic, i.e


when ever we run with simulator it should return values in same sequence. Otherwise
the bug found today cant be found return. For this purpose it has one argument called
seed. The seed parameter controls the numbers that $random returns, such that
different seeds generate different random streams. The seed parameter shall be
either a reg, an integer, or a time variable. The seed value should be assigned to this
variable prior to calling $random.                

EXAMPLE:
   module Tb();
   integer num,seed,i,j;
   initial
   begin
     for(j = 0;j<4 ;j=j+1)
     begin
       seed = j;
       $display(" seed is %d",seed);
       for(i = 0;i < 10; i=i+1)
       begin
         num = { $random(seed) } % 10;
         $write("| num=%2d |",num);
       end
       $display(" ");
       end
     end
   endmodule

RESULT:

 seed is 0
| num= 8 || num= 7 || num= 7 || num= 7 || num= 7 || num= 7 || num= 5 || num= 2
|| num= 1 || num= 9 |
 seed is 1
| num= 8 || num= 8 || num= 2 || num= 2 || num= 6 || num= 3 || num= 8 || num= 5
|| num= 5 || num= 5 |
 seed is 2
| num= 8 || num= 1 || num= 0 || num= 5 || num= 0 || num= 8 || num= 6 || num= 7
|| num= 1 || num= 6 |
 seed is 3
| num= 8 || num= 2 || num= 2 || num= 3 || num= 8 || num= 6 || num= 1 || num= 4
|| num= 3 || num= 9 |

The $random function has its own implicit variable as seed when user is not giving
explicitly seed. The following example shows that seed = 0 and implicit seed are
having same sequence.It means that the imlicity taken seed is also 0.

EXAMPLE:
   module Tb();
   integer num,seed,i,j;
   initial
   begin
     seed = 0;
     for(j = 0;j<2 ;j=j+1)
     begin
       if(j ==0)
         $display(" seed is %d",seed);
       else
         $display(" No seed is given ");
         for(i = 0;i < 10; i=i+1)
         begin

http://testbench.in/CR_02_VERILOG_CRV.html[9/26/2012 2:10:12 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

           if( j == 0)


             num = { $random(seed) } % 10;
           else
             num = { $random } % 10;
           $write("| num=%2d |",num);
         end
         $display(" ");
     end
   end
   endmodule

RESULT:

 seed is 0
| num= 8 || num= 7 || num= 7 || num= 7 || num= 7 || num= 7 || num= 5 || num= 2
|| num= 1 || num= 9 |
 No seed is given
| num= 8 || num= 7 || num= 7 || num= 7 || num= 7 || num= 7 || num= 5 || num= 2
|| num= 1 || num= 9 |

The system functions shall always return same series of values with same seed. This
facilitates debugging by making the operation of the system repeatable. The argument
for the seed parameter should be an integer variable that is initialized by the user and
only updated by the system function. This ensures the desired distribution is achieved.
In the following example, when ever the seed is changed to 2, the sequence 8-1-0-5-
0-8-6-7-11-6......... is followed. Check out in any tool you will see the same
sequence.

EXAMPLE:
   module Tb();
   integer num,seed,i,j;
   initial
   begin
     for(j = 0;j<4 ;j=j+1)
     begin
       seed = 2;
       $display(" seed is %d",seed);
       for(i = 0;i < 10; i=i+1)
       begin
         num = { $random(seed) } % 10;
         $write("| num=%2d |",num);
       end
       $display(" ");
     end
   end
   endmodule

RESULT:

 seed is 2
| num= 8 || num= 1 || num= 0 || num= 5 || num= 0 || num= 8 || num= 6 || num= 7
|| num= 1 || num= 6 |
 seed is 2
| num= 8 || num= 1 || num= 0 || num= 5 || num= 0 || num= 8 || num= 6 || num= 7
|| num= 1 || num= 6 |
 seed is 2
| num= 8 || num= 1 || num= 0 || num= 5 || num= 0 || num= 8 || num= 6 || num= 7
|| num= 1 || num= 6 |
 seed is 2
| num= 8 || num= 1 || num= 0 || num= 5 || num= 0 || num= 8 || num= 6 || num= 7
|| num= 1 || num= 6 |

Seed is inout port. Random number system function returns a random number and
also returns a random number to seed inout argument also. The results of the
following example demonstrates how seed value is getting changed.

EXAMPLE:
   module Tb();
   integer num,seed,i,j;
   initial
   begin
     seed = 0;

http://testbench.in/CR_02_VERILOG_CRV.html[9/26/2012 2:10:12 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

     for(j = 0;j<10 ;j=j+1)


     begin
       num = { $random(seed) } % 10;
       $write("| num=%2d |",num);
       $display(" seed is %d ",seed);
     end
   end
   endmodule

RESULT:

| num= 8 | seed is -1844104698


| num= 7 | seed is 1082744015
| num= 7 | seed is 75814084
| num= 7 | seed is 837833973
| num= 7 | seed is -2034665166
| num= 7 | seed is -958425333
| num= 5 | seed is 851608272
| num= 2 | seed is 154620049
| num= 1 | seed is -2131500770
| num= 9 | seed is -2032678137

From the above results we can make a table of seed values and return values of
$random. If a seed is taken from table, then rest of the sequence has to follow
sequence in table.

Table is as follows for initial seed 0;

| num= 8 | seed is -1844104698


| num= 7 | seed is 1082744015
| num= 7 | seed is 75814084
| num= 7 | seed is 837833973
| num= 7 | seed is -2034665166
| num= 7 | seed is -958425333
| num= 5 | seed is 851608272
| num= 2 | seed is 154620049
| num= 1 | seed is -2131500770
| num= 9 | seed is -2032678137
.
.
.
.
.
table goes on........

In the following example, the seed is 837833973, which is the 4 th seed from the
above table.

EXAMPLE:
   module Tb();
   integer num,seed,i,j;
   initial
   begin
     seed = 837833973;
     for(j = 0;j<10 ;j=j+1)
     begin
       num = { $random(seed) } % 10;
       $write("| num=%2d |",num);
       $display(" seed is %d ",seed);
     end
   end
   endmodule

RESULTS:

| num= 7 | seed is -2034665166


| num= 7 | seed is -958425333
| num= 5 | seed is 851608272
| num= 2 | seed is 154620049

http://testbench.in/CR_02_VERILOG_CRV.html[9/26/2012 2:10:12 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

| num= 1 | seed is -2131500770


| num= 9 | seed is -2032678137
| num= 8 | seed is -1155272804
| num= 7 | seed is -1634874387
| num= 9 | seed is -153856566
| num= 2 | seed is -970066749

From the above example we can come to conclusion that $random is not giving a
random number. It is randomizing seed and returning corresponding number for that
seed.

Total possible seed values are 4294967295(32'hFFFF_FFFF). Is it possible for $random


to generate all the seeds? . Lets say, if the seed gets repeated after 10 iterations,
then after the 10 iterations, same values are repeated. So $random is circulating
inside a chain of 10 numbers.

The following example demonstrates how $random misses many seeds. I tried to
display the seeds between 0 to 20 in the chaining formed by initial seed of 0. Results
show that total possible seeds are 4294967295 , and number of seeds possible in seed
chain are 4030768279 , so we are missing some seeds. Look at the seeds between 0 to
20. Seed == 1 is missing.

EXAMPLE:
 
   module Tb();
   integer num,seed,j;
   reg [0:31] i;
   initial
   begin
     i = 0;
     seed = 1;
     while (seed != 0)
     begin
       if(i == 0)
         seed = 0;
         i = i + 1;
         num = $random(seed);
       if(seed < 20 && seed > 0)
         $display(" seed is %d after values %d ",seed,i);
     end
     $display(" seed is zero after this number of random numbers %0d  total numbers
available are %d",i,{32'hffff_ffff});
   end
   endmodule

RESULTS:

 seed is 10 after values 93137101


 seed is 17 after values 307298440
 seed is 2 after values 410139893
 seed is 12 after values 483530075
 seed is 19 after values 592243262
 seed is 3 after values 720224974
 seed is 11 after values 1342230278
 seed is 15 after values 2032553666
 seed is 7 after values 2266624778
 seed is 13 after values 2362534380
 seed is 5 after values 2512466932
 seed is 9 after values 2575033104
 seed is 16 after values 2988686279
 seed is 4 after values 3173376451
 seed is 6 after values 3483433473
 seed is 8 after values 3547878575
 seed is 14 after values 3663208793
 seed is 18 after values 3930700709
 seed is zero after this number of random numbers 4030768279  total numbers
available are 4294967295

Now I tried to simulate with seed = 1 . It's interisting to know that some how the
sequence is able to enter this chaining which is formed with seed=0 and there is no

http://testbench.in/CR_02_VERILOG_CRV.html[9/26/2012 2:10:12 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

seed value 1 in this chaining and my simulation hanged. So aborted the simulation and
partial results show that the initial seed = 1 enters the chaing formed by seed 0.

EXAMPLE:
   module Tb();
   integer num,seed,j;
   reg [0:31] i;
   initial
   begin
     i = 0;
     seed = 0;
     while (seed != 1)
     begin
       if(i == 0)
       seed = 1;
       i = i + 1;
       num = $random(seed);
       if(seed < 20 && seed > 0)
       $display(" seed is %d after values %d ",seed,i);
     end
     $display(" seed is one after this number of random numbers %0d  total numbers
available are %d",i,{32'hffff_ffff});
   end
   endmodule

RESULTS:

 seed is 10 after values 357336117


 seed is 17 after values 571497456
 seed is 2 after values 674338909
 seed is 12 after values 747729091
 seed is 19 after values 856442278
 seed is 3 after values 984423990
 seed is 11 after values 1606429294
 seed is 15 after values 2296752682
 seed is 7 after values 2530823794
 seed is 13 after values 2626733396
 seed is 5 after values 2776665948
 seed is 9 after values 2839232120
 seed is 16 after values 3252885295
 seed is 4 after values 3437575467
 seed is 6 after values 3747632489
 seed is 8 after values 3812077591
 seed is 14 after values 3927407809
 seed is 18 after values 4194899725
 seed is 10 after values 357336117
 seed is 17 after values 571497456
 seed is 2 after values 674338909
 seed is 12 after values 747729091
 seed is 19 after values 856442278
 seed is 3 after values 984423990

Verilog also has other system functions to generate random numbers. Each of these
functions returns a pseudo-random number whose characteristics are described by the
function name.
Following are the Verilog random number genrator system functions:

$random
$dist_chi_square
$dist_erlang 
$dist_exponential 
$dist_normal
$dist_poisson 
$dist_t
$dist_uniform 

All parameters to the system functions are integer values. For the exponential,
poisson, chi-square ,t and erlang  functions the parameters mean, degree of freedom,
and k_stage must be greater than 0.

$dist_uniform(seed, min, max) is similar to min + {$random(seed)}%(max-min+1), the

http://testbench.in/CR_02_VERILOG_CRV.html[9/26/2012 2:10:12 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

difference is that in $dist_uniform the distribution is uniform. $dist_uniform returns a


number between min and max. In the $dist_uniform function, the start and end
parameters are integer inputs that bound the values returned. The start value should
be smaller than the end value.

The mean parameter used by $dist_normal, $dist_exponential, $dist_poisson and


$dist_erlang is an integer input that causes the average value returned by the function
to approach the value specified. The standard deviation parameter used with the
$dist_normal function is an integer input that helps determine the shape of the
density function. Larger numbers for standard deviation spread the returned values
over a wider range.

The degree of freedom parameter used with the $dist_chi_square and $dist_t
functions is an integer input that helps determine the shape of the density function.
Larger numbers spread the returned values over a wider range.

EXAMPLE:
   module Tb();
   integer num_1,num_2,seed;
   initial
   begin
     seed = 10;
     repeat(5)
     begin
       #1;
       num_1 = $dist_uniform(seed,20,25);
       num_2 = $dist_uniform(seed,50,55);
       $display("num_1 = %d,num_2 = %d",num_1,num_2);
     end
   end
   endmodule

RESULTS:

num_1 = 20,num_2 = 50
num_1 = 23,num_2 = 55
num_1 = 22,num_2 = 54
num_1 = 25,num_2 = 51
num_1 = 23,num_2 = 55

As i discussed $random randomizes its seed, Lets see whether $dist_uniform is also
doing the same.

EXAMPLE:

   module Tb();
   integer num_1,num_2,seedd,seedr;
   initial
   begin
     seedd = 10;
     seedr = 10;
     repeat(5)
     begin
       #1;
       num_1 = $dist_uniform(seedd,20,25);
       num_2 = 20 + ({$random(seedr)} % 6);
       $display("num_1 = %d,num_2 = %d,seedd = %d seedr =
%d",num_1,num_2,seedd,seedr);
     end
   end
   endmodule
RESULTS:

num_1 = 20,num_2 = 22,seedd = 690691 seedr = 690691


num_1 = 20,num_2 = 20,seedd = 460696424 seedr = 460696424
num_1 = 23,num_2 = 22,seedd = -1571386807 seedr = -1571386807
num_1 = 25,num_2 = 21,seedd = -291802762 seedr = -291802762
num_1 = 22,num_2 = 23,seedd = 1756551551 seedr = 1756551551

http://testbench.in/CR_02_VERILOG_CRV.html[9/26/2012 2:10:12 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

Look at the results... Its interesting to note that $random and $dist_uniform have
same seed sequence flow also.

As I mentioned, $dist_uniform(seed, min, max) is similar to min +


{$random(seed)}%(max-min+1). "similar" means they have some common functionality.
$dist_uniform is having uniform distribution, $random for that range is also uniformly
distributed. Following example demonstrates that $dist_uniform and $random are
uniformly distributed.

EXAMPLE:
   module Tb();
   integer num,seed;
   integer num_20,num_21,num_22,num_23,num_24,num_25;
   initial
   begin
     seed = 10;
     num_20 = 0;num_21 = 0;num_22 = 0;num_23 = 0;num_24 = 0;num_25 =0;
     repeat(6000)
     begin
       num = $dist_uniform(seed,20,25);
       if(num == 20 )
         num_20 = num_20 + 1;
       if(num == 21)
         num_21 = num_21 + 1;
       if(num == 22)
         num_22 = num_22 + 1;
       if(num == 23)
         num_23 = num_23 + 1;
       if(num == 24)
         num_24 = num_24 + 1;
       if(num == 25)
         num_25 = num_25 + 1;
     end
     $display("num_20 = %0d;num_21 = %0d;num_22 = %0d;num_23 = %0d;num_24 =
%0d;num_25 = %0d",num_20,num_21,num_22,num_23,num_24,num_25);
   end
   endmodule

RESULTS:

num_20 = 1014;num_21 = 983;num_22 = 946;num_23 = 1023;num_24 = 1014;num_25 =


1020

EXAMPLE:
   module Tb();
     integer num;
     integer num_20,num_21,num_22,num_23,num_24,num_25;
     initial
     begin
        seed = 10;
        num_20 = 0;num_21 = 0;num_22 = 0;num_23 = 0;num_24 = 0;num_25 =0;
        
        repeat(6000)
        begin
          
           num = 20 +( {$random(seed) } %6 );
           if(num == 20 )
              num_20 = num_20 + 1;
           if(num == 21)
              num_21 = num_21 + 1;
           if(num == 22)
              num_22 = num_22 + 1;
           if(num == 23)
              num_23 = num_23 + 1;
           if(num == 24)
              num_24 = num_24 + 1;
           if(num == 25)
              num_25 = num_25 + 1;
          
        end

http://testbench.in/CR_02_VERILOG_CRV.html[9/26/2012 2:10:12 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

        $display("num_20 = %0d;num_21 = %0d;num_22 = %0d;num_23 = %0d;num_24 =


%0d;num_25 = %0d",num_20,num_21,num_22,num_23,num_24,num_25);
     end
   endmodule
RESULTS:

num_20 = 973;num_21 = 1064;num_22 = 961;num_23 = 988;num_24 = 999;num_25 =


1015

As I mentioned ,$dist_uniform(seed, min, max) is similar to min +


{$random(seed)}%(max-min+1). "similar" means they have some difference. The
difference is that they generate different sequence.

EXAMPLE:
   module Tb();
      integer num_1,num_2,seedd,seedr;
      initial
      begin
         seedd = 10;
         seedr = 10;
         repeat(5)
         begin
            #1;
            num_1 = $dist_uniform(seedd,20,25);
            num_2 = 20 + ({$random(seedr)} % 6);
            $display("num_1 = %d,num_2 = %d",num_1,num_2);
         end
       end
   endmodule
RESULTS:

num_1 = 20,num_2 = 22
num_1 = 20,num_2 = 20
num_1 = 23,num_2 = 22
num_1 = 25,num_2 = 21
num_1 = 22,num_2 = 23

Till now what we have seen is $random has uniform distribution over integer values. It
means that distribution should be uniform across all the bits in 32 bit vector also. The
following example shows that bits positions 2,3,4,11,12,13 have equal probability of
getting 0. For demonstration I showed some index only. Try out rest of them and see
that results is same for all the bits.

EXAMPLE:
   module Tb();
      integer num;
      integer num_2,num_3,num_4,num_11,num_12,num_13;
      initial
      begin
          num_2 = 0;num_3 = 0;num_4 = 0;num_11 = 0;num_12 = 0;num_13 =0;
          repeat(6000)
          begin
              num = $random;
              if(num[2] == 0 )
                num_2 = num_2 + 1;
              if(num[3] == 0)
                num_3 = num_3 + 1;
              if(num[4] == 0)
                num_4 = num_4 + 1;
              if(num[11] == 0)
                num_11 = num_11 + 1;
              if(num[12] == 0)
                num_12 = num_12 + 1;
              if(num[13] == 0)
                num_13 = num_13 + 1;
          end
          $display("num_2 = %0d;num_3 = %0d;num_4 = %0d;num_11 = %0d;num_12 =
%0d;num_13 = %0d",num_2,num_3,num_4,num_11,num_12,num_13);
      end
   endmodule

http://testbench.in/CR_02_VERILOG_CRV.html[9/26/2012 2:10:12 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

RESULTS:

num_2 = 3012;num_3 = 2964;num_4 = 3065;num_11 = 3001;num_12 = 2964;num_13 =


2975

The distribution is uniform for system function $random. Suppose if the requirement
is to generate random numbers for more than one variable, and all the variables
should have uniform distribution, then use different seeds for each variable. Other
wise distribution is distributed on all the variables as overall variables which mightnot
be our requirement.. But for lower bits, the distribution is same as shown in example.

EXAMPLE:
   module Tb();
      integer seed;
      reg [1:0] var_1,var_2,var3,var4;
      integer num_2,num_3,num_1,num_0;
      integer cou_2,cou_3,cou_1,cou_0;
      
      initial
      begin
          seed = 10;
          num_2 = 0;num_3= 0;num_1= 0;num_0= 0;
          cou_2= 0;cou_3= 0;cou_1= 0;cou_0= 0;
          repeat(40000)
          begin
              var_1 = $random;
              var3 = $random;
              var4 = $random;
              var_2 = $random; 
              if(var_1 == 0 )
                 num_0 = num_0 + 1;
              if(var_1 == 1 )
                 num_1 = num_1 + 1;
              if(var_1 == 2 )
                 num_2 = num_2 + 1;
              if(var_1 == 3 )
                 num_3 = num_3 + 1;
              
              if(var_2 == 0 )
                 cou_0 = cou_0 + 1;
              if(var_2 == 1 )
                 cou_1 = cou_1 + 1;
              if(var_2 == 2 )
                 cou_2 = cou_2 + 1;
              if(var_2 == 3 )
                 cou_3 = cou_3 + 1;
          end
          $display("num_2 = %0d;num_3= %0d;num_1= %0d;num_0=
%0d;",num_2,num_3,num_1,num_0);
          $display("cou_2= %0d;cou_3= %0d;cou_1= %0d;cou_0=
%0d;",cou_2,cou_3,cou_1,cou_0);
      end
   endmodule

RESULTS:

num_2 = 9984;num_3= 10059;num_1= 10002;num_0= 9955;


cou_2= 10060;cou_3= 9934;cou_1= 10072;cou_0= 9934;

Use system time as seed, so the same TB simulated at different times have different
random sequences and there is more probability of finding bugs. The following is C
code useful in PLI to get system time in to verilog.

http://testbench.in/CR_02_VERILOG_CRV.html[9/26/2012 2:10:12 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

#include <stdio.h>
#include <time.h>
char *get_time_string(int mode24);
int get_systime() {
time_t seconds;
seconds = time (NULL);
return seconds;
}

In Verilog 1995 standard every simulator has its own random number generation
algorithm. But in Verilog 2001 a standard is made that every simulator has to follow
same algorithm. So the same random number sequence can seen on different
simulators for same seed.

Don't expect that the same sequence is generated on all the simulators. They are
only following same algorithm. The reason is race condition. Look at following
example, both the statements_1 and statement_2 are scheduled to execute at same
simulation time. The order of execution is not not known. Some simulators take
statement_1 as the first statement to execute and some other statement_2. If the
TB is built without any race condition to $random function calls, then the same
random sequence can be generated on different simulators and a testbench without
a racecondition on $random calls is not easy to build.

Look at the following 2 examples. I just changed the order of statements, the results
are reversed. 
@edes

EXAMPLE:new
   module Tb();
    
   initial
     $display("staement 2 :::%d",$random);
  
    initial
     $display("staement 1 :::%d",$random);
  
   endmodule

staement 2 :::  303379748
staement 1 :::-1064739199

EXAMPLE:
   module Tb();
    
   initial
     $display("staement 1 :::%d",$random);
  
    initial
     $display("staement 2 :::%d",$random);
  
   endmodule

staement 1 :::  303379748
staement 2 :::-1064739199

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/CR_02_VERILOG_CRV.html[9/26/2012 2:10:12 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CR_02_VERILOG_CRV.html[9/26/2012 2:10:12 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS SYSTEMVERILOG CRV Index


Constrained Random
SystemVerilog Systemverilog Constraint Random Stmulus Generaion : Verification
Verification Verilog Crv
Systemverilog Crv
Constructs We have seen how to get random values and constrain them. These constraints are at Randomizing Objects
Interface very low level of abstraction. Todays verification needs a better way to describ the Random Variables
constraints. SystemVerilog has randomization constructs to support todays verification Randomization Methods
OOPS Checker
needs.
Randomization Constraint Block
Following are the features of SystemVerilog which support Constraint Random Inline Constraint
Functional Coverage Global Constraint
Verification (CRV) :
Assertion Constraint Mode
1) Constraints : Purely random stimulus takes too long to generate interesting External Constraints
DPI Randomization
senarious. Specify the interesting subset of all possible stimulus with constraint
UVM Tutorial blocks. These are features provided by SystemVerilog for constraining randomness. Controlability
Random variable generated in verilog Boolean expressions, foreach (for constraining Static Constraint
VMM Tutorial Constraint Expression
elements of array), set membership, inline constraints, rand case, rand sequence,
OVM Tutorial Conditional constraints and implication constraints. Variable Ordering
Constraint Solver Speed
Easy Labs : SV
Randcase
Easy Labs : UVM
2) Randomization : random function, constrained and unconstrained randomization, Randsequence
uniform distribution, weighted distribution,weighted range, weighted case, pre Random Stability
Easy Labs : OVM randomization, post randomization, declaration of random variable and non repeating Array Randomization
Easy Labs : VMM sequence. Constraint Guards
AVM Switch TB Titbits
3) Dynamic constraints : inline constraints, guarded constraints, disabling/enabling
VMM Ethernet sample constraints, disabling/enabling random variables and overriding of constraint blocks. Report a Bug or Comment
on This section - Your
4) Random Stability : Thread stability, object stability and manual seeding. input is what keeps
Verilog Testbench.in improving
In verilog only system functions like $random are used for stimulus generation. with time!
Verification In SystemVerilog, constraint random stimulus can be generated in following ways.
Verilog Switch TB
Basic Constructs
Random Number Generator System Functions

OpenVera In addition to the system function which are in verilog, SystemVerilog has $urandom()
Constructs and $urandom_range(). $urandom() and $urandom_range() returns a unsigned values.
Switch TB The following example demonstrates random generation of unsigned numbers.
RVM Switch TB
RVM Ethernet sample EXAMPLE:
    module Tb();
    integer unsigned address;
Specman E         initial
        begin                              
Interview Questions             repeat(5)
            begin
            address = $urandom();                
            $display("address = %d;",address);
            end
        end
      
    endmodule

RESULTS:

http://testbench.in/CR_03_SYSTEMVERILOG_CRV.html[9/26/2012 2:10:22 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

# address = 3468265955;
# address =  541037099;
# address = 3836988758;
# address = 3611785217;
# address =  978699393;

The seed is an optional argument that determines the sequence of random numbers
generated. The seed can be any integral expression. The random number generator
(RNG) shall generate the same sequence of random numbers every time the same seed
is used.

EXAMPLE:
   module Tb();
      integer num,seed,i,j;
      initial
      begin
          for(j = 0;j<4 ;j=j+1)
          begin
              seed = 2;
              $display(" seed is set %d",seed);
              void'($urandom(seed));
          for(i = 0;i < 10; i=i+1)
          begin
               num =  $urandom()  % 10;
               $write("| num=%2d |",num);
          end
          $display(" ");
          end
      end
   endmodule

RESULTS:

 seed is set  2
| num= 1 || num= 2 || num= 7 || num= 2 || num= 1 || num= 7 || num= 4 || num= 2
|| num= 3 || num= 1 |
 seed is set  2
| num= 1 || num= 2 || num= 7 || num= 2 || num= 1 || num= 7 || num= 4 || num= 2
|| num= 3 || num= 1 |
 seed is set  2
| num= 1 || num= 2 || num= 7 || num= 2 || num= 1 || num= 7 || num= 4 || num= 2
|| num= 3 || num= 1 |
 seed is set  2
| num= 1 || num= 2 || num= 7 || num= 2 || num= 1 || num= 7 || num= 4 || num= 2
|| num= 3 || num= 1 |

http://testbench.in/CR_03_SYSTEMVERILOG_CRV.html[9/26/2012 2:10:22 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

$Urandom_range

The $urandom_range() function returns an unsigned integer within a specified range.


The syntax for $urandom_range() is as follows:
function int unsigned $urandom_range( int unsigned maxval,int unsigned minval = 0 );
The function shall return an unsigned integer in the range of maxval ... minval.

EXAMPLE:
   module Tb();
       integer num_1,num_2;
       initial
       begin
            repeat(5)
            begin
              #1;
              num_1 = $urandom_range(25,20);
              num_2 = $urandom_range(55,50);
              $display("num_1 = %0d,num_2 = %0d",num_1,num_2);
            end
       end
   endmodule

RESULTS:

# num_1 = 25,num_2 = 55
# num_1 = 22,num_2 = 55
# num_1 = 23,num_2 = 52
# num_1 = 21,num_2 = 54
# num_1 = 25,num_2 = 54

If minval is omitted, the function shall return a value in the range of maxval ... 0.

EXAMPLE:
   module Tb();
       integer num_1,num_2;
       initial
       begin
           repeat(5)
           begin
               #1;
               num_1 = $urandom_range(3);
               num_2 = $urandom_range(5);
               $display("num_1 = %0d,num_2 = %0d",num_1,num_2);
           end
       end
   endmodule

RESULTS:

num_1 = 3,num_2 = 5
num_1 = 2,num_2 = 5
num_1 = 1,num_2 = 2
num_1 = 3,num_2 = 4
num_1 = 1,num_2 = 4

If maxval is less than minval, the arguments are automatically reversed so that the
first argument is larger than the second argument.

EXAMPLE:
   module Tb();
      integer num_1,num_2;
      initial
      begin
          repeat(5)
          begin
               #1;
               num_1 = $urandom_range(20,25);
               num_2 = $urandom_range(50,55);

http://testbench.in/CR_03_SYSTEMVERILOG_CRV.html[9/26/2012 2:10:22 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

               $display("num_1 = %0d,num_2 = %0d",num_1,num_2);


          end
      end
   endmodule

RESULTS:

num_1 = 25,num_2 = 55
num_1 = 22,num_2 = 55
num_1 = 23,num_2 = 52
num_1 = 21,num_2 = 54
num_1 = 25,num_2 = 54

Scope Randomize Function

The scope randomize function, randomize(), enables users to randomize data in the
current scope.Variables which are passed as arguments are randomized and there is
no limit on the number of arguments.For simpler applications,randomize() function
leads to stright farward implimentation.This gives better control over the $random,as
it allows to add constraints using inline constraints and constraint solver gives valid
solution.Variables which are in the constraint block and not passed as arguments to
randomize() function are not randomized.In the following example Variable Var is
randomized and MIN is not randomized.

EXAMPLE:
   module scope_3;
       integer Var;
       initial
       begin
            for ( int i = 0;i<6 ;i++)
               if( randomize(Var))
                   $display(" Randomization sucsessfull : Var = %0d ",Var);
               else
                   $display("Randomization failed");
            $finish;
       end
   endmodule

RESULTS:

Randomization sucsessfull : Var = -826701341


Randomization sucsessfull : Var = 541037099
Randomization sucsessfull : Var = -457978538
Randomization sucsessfull : Var = -683182079
Randomization sucsessfull : Var = 978699393
Randomization sucsessfull : Var = 717199556
Randomization sucsessfull : Var = 1114265683

Scope randomize function gives better control over the $random, as it allows to add
constraints using inline constraints and constraint solver gives valid solution. Variables
which are in the constraint block and not passed as arguments to randomize() function
are not randomized. In the following example Variable Var is randomized and MIN is
not randomized.

EXAMPLE:
    module scope_4;
       integer Var;
       integer MIN;
       initial
       begin
            MIN = 50;
            for ( int i = 0;i<100 ;i++)
                if( randomize(Var) with { Var < 100 ; Var > MIN ;})
                    $display(" Randomization sucsessfull : Var = %0d Min = %0d",Var,MIN);
                else
                    $display("Randomization failed");
            $finish;
       end

http://testbench.in/CR_03_SYSTEMVERILOG_CRV.html[9/26/2012 2:10:22 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

      
    endmodule

RESULTS:

#  Randomization sucsessfull : Var = 94 Min = 50


#  Randomization sucsessfull : Var = 69 Min = 50
#  Randomization sucsessfull : Var = 53 Min = 50
#  Randomization sucsessfull : Var = 71 Min = 50
#  Randomization sucsessfull : Var = 51 Min = 50
#  Randomization sucsessfull : Var = 78 Min = 50
#  Randomization sucsessfull : Var = 95 Min = 50

In randomize function, the solver can't solve if X or Z is used. randomize(Var) with {


Var == 'bx ;} or {MIN = 'bx} will result in an error.

Randomizing Objects

Generating random stimulus within objects :

SystemVerilog allows object-oriented programiming for random stimulus generation,


subjected to specified constraints. During randomization, variables declared as rand
or randc inside class are only considered for randomization. Built-in randomize()
method is called to generate new random values for the declared random variables.

EXAMPLE:
   program Simple_pro_5;
        class Simple;
            rand integer Var;
        endclass
        Simple
obj;                                                                                                                            
        initial
        begin
             obj = new();
             repeat(5)
                 if(obj.randomize())
                   $display(" Randomization successful : Var = %0d ",obj.Var);
                 else
                   $display("Randomization failed");
        end
   endprogram

RESULTS:

#  Randomization sucsessfull : Var = -82993358


#  Randomization sucsessfull : Var = -112342886
#  Randomization sucsessfull : Var = -867551972
#  Randomization sucsessfull : Var = -34537722
#  Randomization sucsessfull : Var = 1977312553

Random Unpacked Structs:

SystemVerilog allows unpackedstructs to be declared as rand for randomization. Only


members of struct which are declared as rand or randc are only randomized. randc is
not allowed on unpacked structs. If Struct is not declared as rand, solver considers it
as state variable.

EXAMPLE:
   class Rand_struct;
     typedef struct {
               randc int Var1;
               int Var2;
                    } Struct_t;
     rand Struct_t Str;          // To randomize Var1 and Struct_t type has to declared as
rand
   endclass
  

http://testbench.in/CR_03_SYSTEMVERILOG_CRV.html[9/26/2012 2:10:22 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

   program stru_rand_6;
     Rand_struct RS ;
     initial
     begin
       RS = new();
       repeat(10)
       if(RS.randomize())
         $display(" Var1 : %d",RS.Str.Var1);
     end
   endprogram
  
RESULTS:

#  Var1 :  -430761355
#  Var1 :   424439941
#  Var1 : -1129955555
#  Var1 :  1781908941
#  Var1 :  -752252755
#  Var1 :   922477361
#  Var1 : -2115981855
#  Var1 :  1551031961
#  Var1 :   -91393015
#  Var1 :   262093271

Simillar to struct, the same can be achived using class by calling the randomize()
function on the object, which is created by using class.

EXAMPLE:
   program class_rand_7;
     class Class_t;
       rand int Var1;
       int Var2;
     endclass
    
     class Rand_class;
       rand Class_t Cla;     // To randomize Var1,Class_t type has to declared as rand
       function new();
         Cla = new();
       endfunction
     endclass
    
     Rand_class RC = new();
     initial
       repeat(10)
         if(RC.randomize())
           $display(" Var1 : %0d Var2 : %0d",RC.Cla.Var1,RC.Cla.Var2);
   endprogram
  
RESULTS:

#  Var1 : 733126180 Var2 : 0


#  Var1 : -119008195 Var2 : 0
#  Var1 : 342785185 Var2 : 0
#  Var1 : 679818185 Var2 : 0
#  Var1 : -717162992 Var2 : 0
#  Var1 : 664520634 Var2 : 0
#  Var1 : -1944980214 Var2 : 0
#  Var1 : -1350759145 Var2 : 0
#  Var1 : -1374963034 Var2 : 0
#  Var1 : -462078992 Var2 : 0

SystemVerilog structs are static objects, where as class instances are dynamic
objects, declaring a class instance does not allocate memory space for object. Calling
built in new() function creates memory for object. Class have built in functions and
tasks, where as struct dont, this speeds up simulation time if structs are used. Check
your data structure, if they need simple encapsulation use struct otherwise if they
need object oriented mechanisms then choose class.

Rand Case :

You can use randcase to make a weighted choice between different items, without

http://testbench.in/CR_03_SYSTEMVERILOG_CRV.html[9/26/2012 2:10:22 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

having to create a class and instance. An items weight divided by the sum of all
weights gives the probability of taking that branch. More details are discussed in the
following units.

Rand Sequence :

SystemVerilog provides randsequnce to generate random sequencess of operation. It


will be useful for randomly generating structured sequences of stimulus such as
instructions or network traffic patterns.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CR_03_SYSTEMVERILOG_CRV.html[9/26/2012 2:10:22 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS RANDOMIZING OBJECTS Index


Constrained Random
SystemVerilog Generating Random Stimulus Within Class : Verification
Verification Verilog Crv
SystemVerilog features which support Constraint random generation inside objects are Systemverilog Crv
Constructs : Randomizing Objects
Interface Random Variables
1) Random Variable declaration. Randomization Methods
OOPS Checker
2) Built in Functions for generation. Constraint Block
Randomization 3) Constraints to control random generation. Inline Constraint
Functional Coverage   Global Constraint
Assertion Constraint Mode
Variables declared as rand or randc are assigned random values when randomize() External Constraints
DPI function is called, where the constraint specifies the valid solution space from which Randomization
UVM Tutorial
the random values are picked. Controlability
Static Constraint
VMM Tutorial Constraint Expression
OVM Tutorial Variable Ordering
Constraint Solver Speed
Easy Labs : SV
Randcase
Easy Labs : UVM Randsequence
Random Stability
Easy Labs : OVM
Array Randomization
Easy Labs : VMM Constraint Guards
AVM Switch TB Titbits

VMM Ethernet sample Report a Bug or Comment


on This section - Your
input is what keeps
Verilog Testbench.in improving
with time!
Verification
Verilog Switch TB
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/CR_04_RANDOMIZING_OBJECTS.html[9/26/2012 2:10:30 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CR_04_RANDOMIZING_OBJECTS.html[9/26/2012 2:10:30 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS RANDOM VARIABLES Index


Constrained Random
SystemVerilog Random Varible Declaration: Verification
Verification Verilog Crv
Variables declared as rand or randc are only randomized due to call of randomize() Systemverilog Crv
Constructs function. All other varibles are considered as state variables. Randomizing Objects
Interface Random Variables
Randomization Methods
OOPS Checker
EXAMPLE:
Randomization   class ex_8; Constraint Block
      rand [3:0] var1; Inline Constraint
Functional Coverage Global Constraint
      randc [3:0] var2;
Assertion       rand integer var3; Constraint Mode
  endclass External Constraints
DPI Randomization
UVM Tutorial Controlability
Fixed arrays, dynamic arrays, associative arrays and queues can be declared as rand Static Constraint
VMM Tutorial Constraint Expression
or randc. All their elements are treated as random. Individual array elements can also
OVM Tutorial be constrained,in this case, index expression must be constant. For dynamic arrays, Variable Ordering
the size of the array length can be constrained. Non integer data types like shortreal, Constraint Solver Speed
Easy Labs : SV
real and realtime are not allowed for random variable declaration. Randcase
Easy Labs : UVM Randsequence
Random Stability
Easy Labs : OVM
Rand Modifier : Array Randomization
Easy Labs : VMM Constraint Guards
AVM Switch TB Variables declared with rand keyword are standard random variables. When there are Titbits
no other control on distrubution, these variables are uniformly distributed across valid
VMM Ethernet sample values. Report a Bug or Comment
on This section - Your
input is what keeps
Verilog EXAMPLE: Testbench.in improving
   class rand_cl; with time!
Verification
        rand bit [0:2] Var;
Verilog Switch TB         constraint limit_c { Var < 4;}
Basic Constructs    endclass
  
   program rand_p_9;
       rand_cl obj;
OpenVera        integer count_0, count_1, count_2, count_3;
Constructs        initial
Switch TB        begin
         obj = new();
RVM Switch TB          count_0 = 0;count_1 = 0;count_2 = 0;count_3 = 0;
RVM Ethernet sample          repeat(100000)
         begin
          void'(obj.randomize());
          if( obj.Var == 0) count_0 ++;
Specman E           else if( obj.Var == 1) count_1 ++;
Interview Questions           else if( obj.Var == 2) count_2 ++;
          else if( obj.Var == 3) count_3 ++;
       end
       $display(" count_0 = %0d , count_1 = %0d, count_2 = %0d, count_3 = %0d
",count_0, count_1, count_2, count_3);
       end
   endprogram

RESULTS:

count_0 = 25046 , count_1 = 24940, count_2 = 24969, count_3 = 25045

http://testbench.in/CR_05_RANDOM_VARIABLES.html[9/26/2012 2:10:38 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

Simulation results show that the rand variable is distrubuted uniformly.

Randc Modifier :

Variables declared as randc are random cyclic that randomly iterates over all the
values in the range and no value is repeated with in an iteration until every possible
value has been assigned. But Iteration sequences are won't be same. Bit and
enumerated types can be randc variables. To reduce memory requirements,
implementations can impose a limit on maximum size of a randc variable, it should be
not be more than 8 bits.

EXAMPLE:
   class rand_c;
     randc bit [1:0] Var;
   endclass
  
   program rand_cp_10;
     rand_c obj=new();
     initial
       for(int i=0;i<20;i++)
       begin
         void'(obj.randomize());
         $write("%0d_",obj.Var);
         if(i%4==3)
         $display("");
       end
   endprogram

RESULTS:

# 0_3_1_2_
# 3_0_2_1_
# 0_3_1_2_
# 0_1_2_3_
# 3_0_2_1_

The permutation sequence for any given randc variable is recomputed whenever the
constraints changes on that variable or when none of the remaining values in the
permutation can satisfy the constraints.

EXAMPLE:
   class rand_c;
     randc bit [2:0] Var;
     integer MIN = 4;
     constraint C { Var < MIN ;}    

http://testbench.in/CR_05_RANDOM_VARIABLES.html[9/26/2012 2:10:38 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

   endclass                          
                                                                                                                                
   program rand_cp_11;
     rand_c obj=new();
     initial
     for(int i=0;i<20;i++)
     begin
       obj.MIN = 4;
       if(i>12)
         obj.MIN=7;
       void'(obj.randomize());
       if(i==12)
         $display(" CONSTRAINT CHANGED ");
       $write("%0d_",obj.Var);
       if((i%4==3))      
         $display("");                                                          
     end                                                                        
   endprogram

RESULTS:

0_2_3_1_
0_1_3_2_
3_2_0_1_
 CONSTRAINT CHANGED
0_1_4_2_
6_5_3_0_

Permutation sequence is computed on every call of new() function. So if randc


variables won't behave like random cyclic, if new() is called for every randomization.
In the following example variable Var is not behaving like random cyclic.

EXAMPLE:
   class rand_c;
     randc bit [1:0]Var;
   endclass
                                                                                                                                
   program rand_cp_12;
     rand_c obj=new();
     initial
     for(int i=0;i<20;i++)
     begin
       obj=new();
       void'(obj.randomize());
       $write("%0d_",obj.Var);
       if(i%4==3)
         $display("");
     end
   endprogram
RESULTS:

# 1_3_1_2_
# 3_2_2_1_
# 2_0_0_0_
# 3_3_1_0_
# 3_0_1_0_

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/CR_05_RANDOM_VARIABLES.html[9/26/2012 2:10:38 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CR_05_RANDOM_VARIABLES.html[9/26/2012 2:10:38 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS RANDOMIZATION METHODS Index


Constrained Random
SystemVerilog Randomization Built-In Methods Verification
Verification Verilog Crv
SystemVerilog has randomize(),pre_randomize() and post_randomize() built-in Systemverilog Crv
Constructs functions for randomization. Calling randomize() causes new values to be selected for Randomizing Objects
Interface all of the random variables in an object. To perform operations immediately before or Random Variables
after randomization,pre_randomize() and post_randomize() are used. Randomization Methods
OOPS Checker
Randomization Constraint Block
Randomize() Inline Constraint
Functional Coverage Global Constraint
Assertion Every class has a virtual  predefined function randomize(), which is provided for Constraint Mode
generating a new value.Randomization function returns 1 if the solver finds a valid External Constraints
DPI Randomization
solution. We cannot override this predefined function. It is strongly recommended to
UVM Tutorial check the return value of randomize function. Constraint solver never fails after one Controlability
successful randomization, if solution space is not changed. For every randomization Static Constraint
VMM Tutorial Constraint Expression
call, check the return value, solver may fail due to dynamically changing the
OVM Tutorial constraints.In the following example, there is no solution for Var < 100 and Var > Variable Ordering
200,so the randomization fails. Constraint Solver Speed
Easy Labs : SV
Randcase
Easy Labs : UVM The best way to check status of randomization return value is by using assertion. Randsequence
Random Stability
Easy Labs : OVM
    assert(obj.randomize());  Array Randomization
Easy Labs : VMM Constraint Guards
AVM Switch TB Titbits
EXAMPLE:
VMM Ethernet sample    program Simple_pro_13; Report a Bug or Comment
     class Simple; on This section - Your
       rand integer Var; input is what keeps
Verilog        constraint c1 { Var <100;} Testbench.in improving
       constraint c2 { Var >200;} with time!
Verification
     endclass
Verilog Switch TB      initial
Basic Constructs      begin 
       Simple obj = new();
       if(obj.randomize())
       $display(" Randomization sucsessfull : Var = %0d ",obj.Var);
OpenVera        else
Constructs        $display("Randomization failed");
Switch TB      end
   endprogram
RVM Switch TB
RVM Ethernet sample RESULTS:
# Randomization failed
Specman E
Interview Questions If randomize() fails, the constraints are infeasible and the random variables retain
their previous values. In the following example, For the first randomization call there
is a solution. When the constraints are changed, the randomization failed. Simulation
results show that after randomization failed, random variables hold their previous
values.

EXAMPLE:
   program Simple_pro_14;
     class Simple;
       rand integer Var;

http://testbench.in/CR_06_RANDOMIZATION_METHODS.html[9/26/2012 2:10:48 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

       integer MIN = 20 ;
       constraint c { Var < 100 ; Var > MIN ; }
     endclass
     Simple
obj;                                                                                                                            
     initial
     begin
       obj = new();
       if(obj.randomize())
         $display(" Randomization successful : Var = %0d ",obj.Var);
       else
         $display("Randomization failed: Var = %0d ",obj.Var);
       obj.MIN = 200;
       $display(" MIN is changed to fail the constraint");
       if(obj.randomize())
         $display(" Randomization sucsessfull : Var = %0d ",obj.Var);
       else
         $display(" Randomization failed : Var = %0d",obj.Var);
     end
   endprogram
RESULTS:

#  Randomization sucsessfull : Var = 87


#  MIN is changed to fail the constraint.
#  Randomization failed : Var = 87

Pre_randomize And Post_randomize

Every class contains pre_randomize() and post_randomize() methods, which are


automatically called by randomize() before and after computing new random values.
When randomize() is called,it first invokes the pre_randomize() then randomize()
finally if the randomization is sucesusful only post_randomize is invoked.
These methods can be used as hooks for the user to perform operations such as
setting initial values and performing functions after assigning random variables.

EXAMPLE:
   program pre_post_15;
     class simple;
       function void pre_randomize;
         $display(" PRE_RANDOMIZATION ");
       endfunction
       function void post_randomize;
         $display(" POST_RANDOMIZATION ");
       endfunction
     endclass
     simple obj = new();
     initial
       void'(obj.randomize());                    
   endprogram

http://testbench.in/CR_06_RANDOMIZATION_METHODS.html[9/26/2012 2:10:48 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

RESULTS:

#  PRE_RANDOMIZATION
#  POST_RANDOMIZATION

Overriding of pre_randomize and post_randomize functions is allowed by child class. If


parent class functions are not called when overriding pre_randomize() and
post_randomize functions, parent class function definations will be omitted.

EXAMPLE:
     class Base;
       function void pre_randomize;
         $display(" BASE PRE_RANDOMIZATION ");
       endfunction
       function void post_randomize;
         $display(" BASE POST_RANDOMIZATION ");
       endfunction
     endclass
    
     class Extend_1 extends Base;
       function void pre_randomize;
         $display(" EXTEND_1 PRE_RANDOMIZATION ");
       endfunction
       function void post_randomize;
         $display(" EXTEND_1 POST_RANDOMIZATION ");
       endfunction
     endclass
    
     class Extend_2 extends Base;
       function void pre_randomize;
         super.pre_randomize();
         $display(" EXTEND_2 PRE_RANDOMIZATION ");
       endfunction
       function void post_randomize;
         super.post_randomize();
         $display(" EXTEND_2 POST_RANDOMIZATION ");
       endfunction
     endclass
    
     program pre_post_16;
       Base B = new();
       Extend_1 E1 = new();
       Extend_2 E2 = new();
       initial
       begin
         void'(B.randomize());
         void'(E1.randomize());
         void'(E2.randomize());
       end
     endprogram

In the extended class EXTEND_1, when overiding the builtin functions, parent class
functions are not called. In the extended class EXTEND_2, super.methods are called
which invokes the parent class methods also.

 
RESULTS:

#  BASE PRE_RANDOMIZATION
#  BASE POST_RANDOMIZATION
#  EXTEND_1 PRE_RANDOMIZATION
#  EXTEND_1 POST_RANDOMIZATION
#  BASE PRE_RANDOMIZATION
#  EXTEND_2 PRE_RANDOMIZATION
#  BASE POST_RANDOMIZATION
#  EXTEND_2 POST_RANDOMIZATION

The pre_randomize() and post_randomize() methods are not virtual. However,

http://testbench.in/CR_06_RANDOMIZATION_METHODS.html[9/26/2012 2:10:48 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

because they are automatically called by the randomize() method, which is virtual,
they appear to behave as virtual methods. This example demonstrates that these
functions are not virtual but simulation results show that, it executed extended class
definition functions. Extended class object is created and assigned to base class
object. Calls to pre_randomize and post_randomize calls in object B ,executed the
extended class definitions.

EXAMPLE:
   class Base;
     function void pre_randomize;
       $display(" BASE PRE_RANDOMIZATION ");
      endfunction
     virtual function void post_randomize;
       $display(" BASE POST_RANDOMIZATION ");
      endfunction
   endclass
                                                                                                                                  
   class Extend extends Base;
     function void pre_randomize;
       $display(" EXTEND PRE_RANDOMIZATION ");
     endfunction
     function void post_randomize;
       $display(" EXTEND POST_RANDOMIZATION ");
     endfunction
   endclass
                                                                                                                                
   program pre_post_17;
     Base B ;
     Extend E = new();
     initial
     begin
       B = E ;
       void'(B.randomize());
       void'(E.randomize());
     end
   endprogram

RESULTS:

 There should be compilation error.

 In the above example compilation error is due to the declaration of post_randmoize()
function as virtual. By removing the virtual keyword for the post_randomize()
function, calling the randomize() function by parent and child class, both will execute
functions of child class only. Which is a virtual function behaviour.  

EXAMPLE:
   class Base;
     function void pre_randomize;
       $display(" BASE PRE_RANDOMIZATION ");
      endfunction
     function void post_randomize;
       $display(" BASE POST_RANDOMIZATION ");
      endfunction
   endclass
                                                                                                                                  
   class Extend extends Base;
     function void pre_randomize;
       $display(" EXTEND PRE_RANDOMIZATION ");
     endfunction
     function void post_randomize;
       $display(" EXTEND POST_RANDOMIZATION ");
     endfunction
   endclass
                                                                                                                                
   program pre_post_17;
     Base B ;
     Extend E = new();
     initial
     begin
       B = E ;
       void'(B.randomize());

http://testbench.in/CR_06_RANDOMIZATION_METHODS.html[9/26/2012 2:10:48 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

       void'(E.randomize());
     end
   endprogram

RESULTS:

 #  EXTEND PRE_RANDOMIZATION
 #  EXTEND POST_RANDOMIZATION
 #  EXTEND PRE_RANDOMIZATION
 #  EXTEND POST_RANDOMIZATION

If the class is a derived class and no user-defined implementation of pre_randomize()


and post_randomize() exists, then pre_randomize() and post_randomize() will
automatically invoke super.pre_randomize() and super.post_randomize() respectively.

EXAMPLE:
   class Base;
     function void pre_randomize;
       $display(" BASE PRE_RANDOMIZATION ");
     endfunction
     function void post_randomize;
       $display(" BASE POST_RANDOMIZATION ");
     endfunction
   endclass
                                                                                                                                
   class Extend extends Base;
   endclass
                                                                                                                                
   program pre_post_19;
     Extend E = new();
     initial
       void'(E.randomize());
   endprogram
            
RESULTS:

#  BASE PRE_RANDOMIZATION
#  BASE POST_RANDOMIZATION

EXAMPLE:
   class Base;
     function void pre_randomize;
       $display(" BASE PRE_RANDOMIZATION \n");
     endfunction
     function void post_randomize;
       $display(" BASE POST_RANDOMIZATION \n");
     endfunction
   endclass
  
   class Extend extends Base;
   function void pre_randomize;
     super.pre_randomize();
     $display(" EXTENDED PRE_RANDOMIZATION \n");
   endfunction 
   function void post_randomize;
     $display(" EXTENDED POST_RANDOMIZATION \n");
   endfunction
   endclass
  
   program pre_post;
      Base B;
      Extend E = new();
      initial
      begin
      B = E;
      if(B.randomize())
        $display(" randomization done \n");
      end
   endprogram
  
RESULTS:

http://testbench.in/CR_06_RANDOMIZATION_METHODS.html[9/26/2012 2:10:48 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

BASE PRE_RANDOMIZATION
EXTENDED PRE_RANDOMIZATION
EXTENDED POST_RANDOMIZATION
randomization done

Results show that, if extended class is having new definition, explicitly super.pre_ or
post_ has to be called.
super.pre_randomize() is called in extended class, but super.post_randomize() is not
called in above example. See the  difference in results.
If a class A instance is in Class B,To randomize class A by calling the randomize
function of class B,Class A instance has to be declared as rand variable.

EXAMPLE:
   class A;
    rand integer Var;
   endclass
  
   class B;
     rand A obj_1 = new() ;
     A obj_2 = new();
   endclass
  
   program a_b_20;      
     B obj=new();
     initial
     begin
       obj.obj_1.Var = 1;
       obj.obj_2.Var = 1;
       repeat(10)
       begin
         void'(obj.randomize());
         $display(" Var1 = %d ,Var2 = %d ",obj.obj_1.Var,obj.obj_2.Var );
       end
     end
   endprogram
  
RESULTS:

#  Var1 = 733126180 ,Var2 = 1


#  Var1 = -119008195 ,Var2 = 1
#  Var1 = 342785185 ,Var2 = 1
#  Var1 = 679818185 ,Var2 = 1
#  Var1 = -717162992 ,Var2 = 1
#  Var1 = 664520634 ,Var2 = 1
#  Var1 = -1944980214 ,Var2 = 1
#  Var1 = -1350759145 ,Var2 = 1
#  Var1 = -1374963034 ,Var2 = 1
#  Var1 = -462078992 ,Var2 = 1

Look at the results. Variable of obj_2 is not randomized. Only variable of obj_1 which
is declared as rand is ranomized.

Upon calling the randomize method of B object which contains rand A object, First B
prerandomize is called, then A prerandomize method is called, then B is randomized,
if a solution was found, new values are assigned to the random A objects.If solution
was found, for each random object that is a class instance it's post_randomize method
is called. That means if randomization is successful next B postrandomize, next A
postrandomize functions are called. Upon calling B randomize function this is
sequence it follow.

B-Prerandomize --> A-prerandomize --> A.randomize --> B-postrandomize --> A-


postrandomize        

 
EXAMPLE:
   class A;
     rand integer Var;
     function void pre_randomize;

http://testbench.in/CR_06_RANDOMIZATION_METHODS.html[9/26/2012 2:10:48 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

       $display(" A PRE_RANDOMIZATION ");


     endfunction
     function void post_randomize;
       $display(" A POST_RANDOMIZATION ");
     endfunction
   endclass
  
   class B;
     rand A obj_a;
     function new();
       obj_a = new();
     endfunction
     function void pre_randomize;
       $display(" B PRE_RANDOMIZATION ");
     endfunction
     function void post_randomize;
       $display(" B POST_RANDOMIZATION ");
     endfunction
   endclass
  
   program pre_post_21;
     B obj_b = new();
     initial
       void'(obj_b.randomize());
   endprogram
  

RESULTS:

#  B PRE_RANDOMIZATION
#  A PRE_RANDOMIZATION
#  B POST_RANDOMIZATION
#  A POST_RANDOMIZATION

If randomization failed for obj_a, then post_randomize of obj_a and post_randomize


of obj_b won't be called, and randomization will fail for obj_b also.  

EXAMPLE:
   class A;
     rand bit [2:0] Var;
     constraint randge_c { Var > 2 ; Var < 2;}
     function void pre_randomize;
       $display(" A PRE_RANDOMIZATION ");
     endfunction
     function void post_randomize;
       $display(" A POST_RANDOMIZATION ");
     endfunction
   endclass
  
   class B;
     rand A obj_a;
     function void pre_randomize;
       $display(" B PRE_RANDOMIZATION ");
     endfunction
     function void post_randomize;
       $display(" B POST_RANDOMIZATION ");
     endfunction
     function new();
       obj_a = new();
     endfunction
   endclass
  
   program pre_post_22;
     B obj_b = new();
     initial
       void'(obj_b.randomize());
   endprogram

RESULTS:

#  B PRE_RANDOMIZATION

http://testbench.in/CR_06_RANDOMIZATION_METHODS.html[9/26/2012 2:10:48 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

#  A PRE_RANDOMIZATION

Disabling Random Variable

The random nature of variables declared as rand or randc can be turned on or off
dynamically. To change the status of variable which is declared as rand or randc to
state variable, built in rand_mode() method is used. State variables are not
randomized by randomize() mehod. By default all rand and randc variables are active.
When called as a task, the arguments to the rand_mode method determines the
operation to be performed. If the arguments is 0, then all the variables declared as
rand and randc will become non random i.e all random variables treated as state
variables. IF argument is 1, then all variables declares as rand and randc will be
randomized.

EXAMPLE:
   class rand_mo;
     rand integer Var1;
     rand integer Var2;
   endclass
  
   program rand_mo_p_23;
     rand_mo obj = new();
     initial
     begin
       void'(obj.randomize());
       $display(" Var1 : %d   Var2 : %d ",obj.Var1,obj.Var2);
       obj.rand_mode(0);               // Var1 and Var2 will be treated as State variables.
       void'(obj.randomize());
       $display(" Var1 : %d   Var2 : %d ",obj.Var1,obj.Var2);
       obj.rand_mode(1);              // // Var1 and Var2 will be treated as random
variables.
       void'(obj.randomize());
       $display(" Var1 : %d   Var2 : %d ",obj.Var1,obj.Var2);
     end
   endprogram
  
RESULTS:

#  Var1 :   733126180   Var2 :  -119008195


#  Var1 :   733126180   Var2 :  -119008195
#  Var1 :   342785185   Var2 :   679818185

If arguments are Variable name, then only that variable will be non random.

EXAMPLE:
    class rand_mo;
      rand integer Var1;
      rand integer Var2;
    endclass
                                                                                                                                
    program rand_mo_p_24;
      rand_mo obj = new();
      initial
      begin
        void'(obj.randomize());
        $display(" Var1 : %d   Var2 : %d ",obj.Var1,obj.Var2);
        obj.Var1.rand_mode(0);          // Var1 will become State variable
        void'(obj.randomize());
        $display(" Var1 : %d   Var2 : %d ",obj.Var1,obj.Var2);
        obj.Var2.rand_mode(0);          //  Var2 will also become State variable
        $display(" Var1 : %d   Var2 : %d ",obj.Var1,obj.Var2);
        obj.Var1.rand_mode(1);         // // Var1 will become random variable
        void'(obj.randomize());
        $display(" Var1 : %d   Var2 : %d ",obj.Var1,obj.Var2);
      end
    endprogram
    
RESULTS:

#  Var1 :   733126180   Var2 :  -119008195


#  Var1 :   733126180   Var2 :   342785185

http://testbench.in/CR_06_RANDOMIZATION_METHODS.html[9/26/2012 2:10:48 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

#  Var1 :   733126180   Var2 :   342785185


#  Var1 :   679818185   Var2 :   342785185

When rand_mode method is called as function, it returns the active status of the
specified random variable.

EXAMPLE:
   class rand_mo;
     rand integer Var1;
     rand integer Var2;
   endclass
                                                                                                                                
   program rand_mo_p_24;
     rand_mo obj = new();
     initial
     begin
       void'(obj.randomize());
       $display(" Var1 : %d   Var2 : %d ",obj.Var1,obj.Var2);
       obj.Var1.rand_mode(0);
       void'(obj.randomize());
       $display(" Var1 : %d   Var2 : %d ",obj.Var1,obj.Var2);
       if(obj.Var1.rand_mode())
         $display(" Var1 is random");
       else  
         $display(" Var1 is nonrandom");
       void'(obj.randomize());
       $display(" Var1 : %d   Var2 : %d ",obj.Var1,obj.Var2);
     end
   endprogram
  
RESULTS:

#  Var1 :   733126180   Var2 :  -119008195


#  Var1 :   733126180   Var2 :   342785185
#  Var1 is nonrandom
#  Var1 :   733126180   Var2 :   679818185

If you are changing the status of a variable, which is not existing it is compilation
error.

EXAMPLE:
   class rand_mo;
     rand integer Var1;
     rand integer Var2;
   endclass
                                                                                                                                
   program rand_mo_p_24;
     rand_mo obj = new();
     initial
     begin
       void'(obj.randomize());
       $display(" Var1 : %d   Var2 : %d ",obj.Var1,obj.Var2);
       obj.Var3.rand_mode(0);
       void'(obj.randomize());
       $display(" Var1 : %d   Var2 : %d ",obj.Var1,obj.Var2);
       if(obj.Var3.rand_mode())
       $display(" Var3 is nonrandom");
       void'(obj.randomize());
       $display(" Var1 : %d   Var2 : %d ",obj.Var1,obj.Var2);
     end
   endprogram
  

A compiler error shall be issued if the specified variable does not exist within the
class hierarchy or eventhough it exists but not declared as rand or randc. The
following example illustrates the second case.

EXAMPLE:
   class rand_mo;
     rand integer Var1;

http://testbench.in/CR_06_RANDOMIZATION_METHODS.html[9/26/2012 2:10:48 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

     integer Var2;
   endclass
                                                                                                                                
   program rand_mo_p_24;
     rand_mo obj = new();
     initial
     begin
       void'(obj.randomize());
       $display(" Var1 : %d   Var2 : %d ",obj.Var1,obj.Var2);
       obj.Var2.rand_mode(0);
       void'(obj.randomize());
       $display(" Var1 : %d   Var2 : %d ",obj.Var1,obj.Var2);
       if(obj.Var2.rand_mode())
       $display(" Var1 is nonrandom");
       void'(obj.randomize());
       $display(" Var1 : %d   Var2 : %d ",obj.Var1,obj.Var2);
     end
   endprogram
  

In the above example, Var2 is state variable. If the random variable is an object
handle, only the mode of the object is changed, not the mode of random variables
within that object.

EXAMPLE:
   class rand_var;
     rand integer Var2;
   endclass
   class rand_mo;
     rand integer Var1;
     rand rand_var rv;
     function new();
       rv = new();
     endfunction
   endclass
  
   program rand_mo_p_23;
     rand_mo obj = new();
     initial
     begin
       void'(obj.randomize());
       $display(" Var1 : %d   Var2 : %d ",obj.Var1,obj.rv.Var2);
       obj.rand_mode(0);
       void'(obj.randomize());
       $display(" Var1 : %d   Var2 : %d ",obj.Var1,obj.rv.Var2);
       void'(obj.rv.randomize());
       $display(" Var1 : %d   Var2 : %d ",obj.Var1,obj.rv.Var2);
     end
   endprogram

RESULTS:

 Var1 : 345345423   Var2 : 234563556


 Var1 : 345345423   Var2 : 234563556
 Var1 : 345345423   Var2 : -2456456

Random Static Variable

Randomization does not depend on life time of variable. Even if a variable is


static,randomization is specfic to object.So rand_mode() on static variable,only
switches off the randomization on the variable of that object.This is true for dist and
randc.
In the following example, Var1 is static and Var2 is automatic.Var1 and Var2 in obj_2
are made nonrandom using rand_mode(0).Var1 and Var2 in obj_1 are getting
randomized.The only difference between Var1 and Var2 is that new random value for
Var1 is appreas on both objects.

EXAMPLE:
   class A;
      rand static integer Var1;
      rand integer Var2;

http://testbench.in/CR_06_RANDOMIZATION_METHODS.html[9/26/2012 2:10:48 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

   endclass
    
   program A_p_27;
      A obj_1 = new;
      A obj_2 = new;
      
      initial
      begin
         obj_2.Var1.rand_mode(0);
         obj_2.Var2.rand_mode(0);
         repeat(2)
         begin
            void'(obj_1.randomize());
            void'(obj_2.randomize());
            $display("obj_1.Var1 : %d ,obj_1.Var2 : %d : obj_2.Var1 : %d ,obj_2.Var2 : %d
:",obj_1.Var1,obj_1.Var2,obj_2.Var1,obj_2.Var2); 
         end 
      end
   endprogram
  
RESULTS:

obj_1.Var1 : 934734534,obj_1.Var2 : 234232342: obj_2.Var1 : 934734534 ,obj_2.Var2


:0:
obj_1.Var1 : 908123314,obj_1.Var2 : 121891223: obj_2.Var1 : 908123314 ,obj_2.Var2
:0:

Random variables declared as static are shared by all instances of the class in which
they are declared. Each time the randomize() method is called, the variable is
changed in every class instance.

Randomizing Nonrand Varible

All the variables(randc, rand and nonrandom variables) randomization nature can be
changed dynamically. Using rand_mode() rand and randc varibles changes its nature.
The random nature of variables which are not declared as rand or randc can also be
randomized dynamically. When the randomize method is called with no arguments, it
randomizes the variables which are declared as rand or randc,so that all of the
constraints are satisfied. When randomize is called with arguments, those arguments
designate the complete set of random variables within that object, all other variables
in the object are considered state variables.

EXAMPLE:
    class CA;
      rand byte x, y;
      byte v, w;
      constraint c1 { x < v && y > w ;}
    endclass
    
    program CA_p_28;
      CA a = new;
      initial
      begin
        a.x = 10;a.y = 10;a.v = 10;a.w = 10;
        $display(" x : %3d y : %3d : v : %3d : w : %3d ",a.x,a.y,a.v,a.w);
        void'(a.randomize()); // random variables: x, y state variables: v, w
        $display(" x : %3d y : %3d : v : %3d : w : %3d ",a.x,a.y,a.v,a.w);
        void'(a.randomize(x)); // random variables: x state variables: y, v, w
        $display(" x : %3d y : %3d : v : %3d : w : %3d ",a.x,a.y,a.v,a.w);
        void'(a.randomize(v,w)); // random variables: v, w state variables: x, y
        $display(" x : %3d y : %3d : v : %3d : w : %3d ",a.x,a.y,a.v,a.w);
        void'(a.randomize(w,x)); // random variables: w, x state variables: y, v
        $display(" x : %3d y : %3d : v : %3d : w : %3d ",a.x,a.y,a.v,a.w);
      end
    endprogram
    

RESULTS:

#  x :  10 y :  10 : v :  10 : w :  10


#  x : -71 y :  96 : v :  10 : w :  10

http://testbench.in/CR_06_RANDOMIZATION_METHODS.html[9/26/2012 2:10:48 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

#  x : -37 y :  96 : v :  10 : w :  10


#  x : -37 y :  96 : v : -22 : w :  80
#  x : -90 y :  96 : v : -22 : w : -41

In above example x and y are rand variables, v and w are state variables. When
a.randomize() is called, all rand varibles are randomized and state variables are hold
the same value. When a.randomize(w) is called, only w is considered as rand variable
and all others as state varibles. Here w is in constraint block so it has to satisfy the
constraints. v,y and x also are state variables now, they also need to satisfy the
constraint else it fails.

Replacing the class variables, with its hierarchical result also should result same.

EXAMPLE:
   program CA_p_29;
     CA a = new;
     initial
     begin
       a.x = 10;a.y = 10;a.v = 10;a.w = 10;
       $display(" x : %3d y : %3d : v : %3d : w : %3d ",a.x,a.y,a.v,a.w);
       void'(a.randomize()); // random variables: x, y state variables: v, w
       $display(" x : %3d y : %3d : v : %3d : w : %3d ",a.x,a.y,a.v,a.w);
       void'(a.randomize( a.x )); // random variables: x state variables: y, v, w
       $display(" x : %3d y : %3d : v : %3d : w : %3d ",a.x,a.y,a.v,a.w);
       void'(a.randomize( a.v, a.w )); // random variables: v, w state variables: x, y
       $display(" x : %3d y : %3d : v : %3d : w : %3d ",a.x,a.y,a.v,a.w);
       void'(a.randomize( a.w, a.x )); // random variables: w, x state variables: y, v
       $display(" x : %3d y : %3d : v : %3d : w : %3d ",a.x,a.y,a.v,a.w);
     end
   endprogram

RESULTS:

#  x :  10 y :  10 : v :  10 : w :  10


#  x : -71 y :  96 : v :  10 : w :  10
#  x : -37 y :  96 : v :  10 : w :  10
#  x : -37 y :  96 : v : -22 : w :  80
#  x : -90 y :  96 : v : -22 : w : -41

If you are not interested to satisfy the constraints in constraint block, instead of
switching off the constraint block, just randomize the variables using scope
randomize() function. Scope randomize provide the ability to randomize class
variables also along with non class variables.

EXAMPLE:
  program CA_p_30;
    integer x,y,v,w;
    initial
    begin
      x = 10;y = 10;v = 10;w = 10;
      $display(" x : %3d y : %3d : v : %3d : w : %3d ",x,y,v,w);
      randomize( x ); // random variables: x state variables: y, v, w
      $display(" x : %3d y : %3d : v : %3d : w : %3d ",x,y,v,w);
      randomize(v,w ); // random variables: v, w state variables: x, y
      $display(" x : %3d y : %3d : v : %3d : w : %3d ",x,y,v,w);
      randomize(w,x ); // random variables: w, x state variables: y, v
      $display(" x : %3d y : %3d : v : %3d : w : %3d ",x,y,v,w);
    end
  endprogram
    
RESULTS:

  #  x :  10 y :  10 : v :  10 : w :  10


  #  x : -826701341 y :  10 : v :  10 : w :  10
  #  x : -826701341 y :  10 : v : 541037099 : w : -457978538
  #  x : 978699393 y :  10 : v : 541037099 : w : -683182079

http://testbench.in/CR_06_RANDOMIZATION_METHODS.html[9/26/2012 2:10:48 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CR_06_RANDOMIZATION_METHODS.html[9/26/2012 2:10:48 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS CHECKER Index


Constrained Random
SystemVerilog Verification
Verification Built-in method randomize() not only used for randomization, it can be used as Verilog Crv
checker. When randomize() method is called by passing null, randomize() method Systemverilog Crv
Constructs behaves as checker instead of random generator. It evaluates all the constraints and Randomizing Objects
Interface returns the status. This is true for both scope randomization function and class Random Variables
randomization function. When a randomize() method is called, first RNG assigns Randomization Methods
OOPS Checker
values to random varibles and then solver checks the constraints. When
Randomization randomize(null) is called, it wont call the RNG to assign values to random variables, it Constraint Block
just solves constraints. Inline Constraint
Functional Coverage Global Constraint
Assertion Constraint Mode
EXAMPLE: External Constraints
DPI Randomization
class Eth_rx;
UVM Tutorial   rand integer Pkt_len; Controlability
  rand integer Var; Static Constraint
VMM Tutorial Constraint Expression
  constraint var_c { Var < 1518 ;Var > 64 ;}
OVM Tutorial endclass Variable Ordering
Constraint Solver Speed
Easy Labs : SV
program Eth_25; Randcase
Easy Labs : UVM   Eth_rx rx = new(); Randsequence
  initial Random Stability
Easy Labs : OVM
  begin Array Randomization
Easy Labs : VMM     rx.Pkt_len = 32; Constraint Guards
AVM Switch TB     rx.Var = 871; Titbits
    if(rx.randomize(null))
VMM Ethernet sample       $display(" VALID PKT IS RECIVED "); Report a Bug or Comment
    else on This section - Your
      $display(" INVALID PKT IS RECIVED "); input is what keeps
Verilog     end Testbench.in improving
endprogram with time!
Verification
Verilog Switch TB
Basic Constructs RESULTS:

#  VALID PKT IS RECIVED


OpenVera
Constructs Constraints can be written without having random varibles in expressions. If there is
Switch TB any constraint on state variables and they are dynamically changed, and if you want
to make sure that these dynamic changes should satisfy the constraint, use randomize
RVM Switch TB check to make sure that relation is satisfied.
RVM Ethernet sample In the following example, MIN and MAX are dynamically controllable state variables.
Constraint checker_c fails when MIn = 50 and MAX = 10.

Specman E EXAMPLE:
Interview Questions class Base;
  rand integer Var;
  integer MIN,MAX;  
  constraint randge_r { Var < MAX ; Var > MIN ;}
  constraint checker_c{ MIN < MAX ;} // This checks that these dynamic variables are
valid
  task set (integer MIN,integer MAX);
    this.MIN = MIN;
    this.MAX = MAX;
  $display( " SET : MIN = %0d , MAX = %0d ",MIN,MAX);
  endtask

http://testbench.in/CR_07_CHECKER.html[9/26/2012 2:10:57 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

endclass

program inhe_26;
  Base obj;
  initial
  begin
    obj = new();
    obj.set(0,100) ;
    for(int i=0 ; i < 5 ; i++)
      if(obj.randomize())
        $display(" Randomization sucsessfull : Var = %0d ",obj.Var);
      else
        $display("Randomization failed");
    
    obj.set(50,10) ;
    for(int i=0 ; i < 5 ; i++)
      if(obj.randomize())
        $display(" Randomization sucsessfull : Var = %0d ",obj.Var);
      else
        $display("Randomization failed");
  end
endprogram

RESULTS:

#  SET : MIN = 0 , MAX = 100


#  Randomization sucsessfull : Var = 68
#  Randomization sucsessfull : Var = 11
#  Randomization sucsessfull : Var = 8
#  Randomization sucsessfull : Var = 36
#  Randomization sucsessfull : Var = 64
#  SET : MIN = 50 , MAX = 10
# Randomization failed
# Randomization failed
# Randomization failed
# Randomization failed
# Randomization failed

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/CR_07_CHECKER.html[9/26/2012 2:10:57 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CR_07_CHECKER.html[9/26/2012 2:10:57 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS CONSTRAINT BLOCK Index


Constrained Random
SystemVerilog Verification
Verification Constraint block contains declarative statements which restrict the range of variable Verilog Crv
or defines the relation between variables. Constraint programming is a powerful Systemverilog Crv
Constructs method that lets users build generic, resuble objects that can be extended or more Randomizing Objects
Interface constrained later. constraint solver can only support 2 stete values. If a 4 state Random Variables
variable is used, solver treates them as 2 state variable.. Constraint solver fails only if Randomization Methods
OOPS Checker
there is no solution which satisfies all the constraints. Constraint block can also have
Randomization nonrandom variables, but at least one random variable is needed for randomization. Constraint Block
Constraints are tied to objects. This allows inheritance, hierarchical constraints, Inline Constraint
Functional Coverage Global Constraint
controlling the constraints of specific object.
Assertion Constraint Mode
External Constraints
DPI Randomization
Inheritance
UVM Tutorial Controlability
One of the main advantage of class randomization is Inheritance. Constraints in Static Constraint
VMM Tutorial Constraint Expression
derived class with the same name in base class overrides the base class constraints
OVM Tutorial just like task and functions. Variable Ordering
Constraint Solver Speed
Easy Labs : SV
Randcase
Easy Labs : UVM EXAMPLE: Randsequence
class Base; Random Stability
Easy Labs : OVM
  rand integer Var; Array Randomization
Easy Labs : VMM   constraint range { Var < 100 ; Var > 0 ;} Constraint Guards
AVM Switch TB endclass Titbits

VMM Ethernet sample class Extended extends Base; Report a Bug or Comment


  constraint range { Var < 100 ; Var > 50 ;} // Overrighting the Base class constraints. on This section - Your
endclass input is what keeps
Verilog Testbench.in improving
program inhe_31; with time!
Verification
  Extended obj;
Verilog Switch TB   initial
Basic Constructs   begin
    obj = new();
    for(int i=0 ; i < 100 ; i++)
      if(obj.randomize())
OpenVera         $display(" Randomization sucsessfull : Var = %0d ",obj.Var);
Constructs       else
Switch TB         $display("Randomization failed");
  end
RVM Switch TB endprogram
RVM Ethernet sample
RESULTS:

#  Randomization sucsessfull : Var = 91


Specman E #  Randomization sucsessfull : Var = 93
Interview Questions #  Randomization sucsessfull : Var = 77
#  Randomization sucsessfull : Var = 68
#  Randomization sucsessfull : Var = 67
#  Randomization sucsessfull : Var = 52
#  Randomization sucsessfull : Var = 71
#  Randomization sucsessfull : Var = 98
#  Randomization sucsessfull : Var = 69

Adding new constraints in the derived class, can change the solution space. Solver has
to solve both constraints defined in base class and derived class. In the example given

http://testbench.in/CR_08_CONSTRAINT_BLOCK.html[9/26/2012 2:11:07 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

below, Constraint range_1 defines the range that Var is between 0 to 100.Constraint
range_2 limits the Var to be greater than 50 and solver has to solve both the
constraints and the solution space is between 50 to 100.

EXAMPLE:
class Base;
  rand integer Var;
  constraint range_1 { Var < 100 ; Var > 0 ;}
endclass

class Extended extends Base;
  constraint range_2 { Var > 50 ;} // Adding new constraints in the Extended class
endclass

program inhe_32;
  Extended obj;
  initial
  begin
    obj = new();
    for(int i=0 ; i < 20 ; i++)
      if(obj.randomize())
        $write(": Var = %0d :",obj.Var);
      else
        $display("Randomization failed");
  end
endprogram

RESULTS:

Var = 91 :: Var = 93 :: Var = 77 :: Var = 68 :: Var = 67 :: Var = 52 :: Var = 71 :: Var =


98 :: Var = 69 :: Var = 70 :: Var = 96 :: Var = 88 :: Var = 84 :: Var = 99 :: Var = 68 ::
Var = 83 :: Var = 52 :: Var = 72 :: Var = 93 :: Var = 80 :

Overrighting Constraints

The randomize() task is virtual. Accordingly it treats the class constraints in a virtual
manner. When a named constraint is redefined in an extended class, the previous
definition is overridden and when casting extended class to base class does not change
the constraint set.

EXAMPLE:
  class Base;
     rand integer Var;
     constraint range { Var < 100 ; Var > 0 ;}
  endclass
                                                                                                                              
  class Extended extends Base;
     constraint range { Var ==  100 ;} // Overrighting the Base class constraints.

http://testbench.in/CR_08_CONSTRAINT_BLOCK.html[9/26/2012 2:11:07 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

  endclass
                                                                                                                              
  program inhe_33;
     Extended obj_e;
     Base
obj_b;                                                                                                                            
     initial
     begin
        obj_e = new();
        obj_b = obj_e;
        for(int i=0 ; i < 7 ; i++)
           if(obj_b.randomize())
              $display(" Randomization sucsessfull : Var = %0d ",obj_b.Var);
           else
              $display("Randomization failed");
     end
  endprogram

RESULTS:

#  Randomization sucsessfull : Var = 100


#  Randomization sucsessfull : Var = 100
#  Randomization sucsessfull : Var = 100
#  Randomization sucsessfull : Var = 100
#  Randomization sucsessfull : Var = 100
#  Randomization sucsessfull : Var = 100
#  Randomization sucsessfull : Var = 100

When an extended object is casted to base object, all the constraints in extended
object are solved along with the constraints in base object.

EXAMPLE:
class Base;
rand integer Var;
  constraint range_1 { Var < 100 ; Var > 0 ;}
endclass
                                                                                                                            
class Extended extends Base;
  constraint range_2 { Var > 50 ;}
endclass
                                                                                                                            
program inhe_34;
  Extended obj_e;
  Base
obj_b;                                                                                                                            
  initial
  begin
    obj_e = new();
    obj_b = obj_e;
    for(int i=0 ; i < 10 ; i++)
    if(obj_b.randomize())
      $display(" Randomization sucsessfull : Var = %0d ",obj_b.Var);
    else
      $display("Randomization failed");
  end
endprogram
RESULTS:

#  Randomization sucsessfull : Var = 91


#  Randomization sucsessfull : Var = 93
#  Randomization sucsessfull : Var = 77
#  Randomization sucsessfull : Var = 68
#  Randomization sucsessfull : Var = 67
#  Randomization sucsessfull : Var = 52
#  Randomization sucsessfull : Var = 71
#  Randomization sucsessfull : Var = 98
#  Randomization sucsessfull : Var = 69
#  Randomization sucsessfull : Var = 70

http://testbench.in/CR_08_CONSTRAINT_BLOCK.html[9/26/2012 2:11:07 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CR_08_CONSTRAINT_BLOCK.html[9/26/2012 2:11:07 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INLINE CONSTRAINT Index


Constrained Random
SystemVerilog Verification
Verification Inline constraints allows to add extra constraints to already existing constraints which Verilog Crv
are declared inside class. If you have constraints already defined for variavle var, Systemverilog Crv
Constructs solver solves those constraints along with the in-line constraints. Randomizing Objects
Interface Random Variables
Randomization Methods
OOPS Checker
EXAMPLE:
Randomization class inline; Constraint Block
  rand integer Var; Inline Constraint
Functional Coverage Global Constraint
  constraint default_c { Var > 0 ; Var < 100;}
Assertion endclass Constraint Mode
External Constraints
DPI Randomization
program inline_p_35;
UVM Tutorial   inline obj; Controlability
  initial Static Constraint
VMM Tutorial Constraint Expression
  begin
OVM Tutorial     obj = new(); Variable Ordering
    repeat(5) Constraint Solver Speed
Easy Labs : SV
      if(obj.randomize() with { Var == 50;}) Randcase
Easy Labs : UVM       $display(" Randodmize sucessful Var %d ",obj.Var); Randsequence
      else Random Stability
Easy Labs : OVM
      $display(" Randomization failes"); Array Randomization
Easy Labs : VMM   end Constraint Guards
AVM Switch TB endprogram Titbits

VMM Ethernet sample RESULTS: Report a Bug or Comment


on This section - Your
#  Randodmize sucessful Var          50 input is what keeps
Verilog #  Randodmize sucessful Var          50 Testbench.in improving
#  Randodmize sucessful Var          50 with time!
Verification
#  Randodmize sucessful Var          50
Verilog Switch TB #  Randodmize sucessful Var          50
Basic Constructs

In the above example, by default only default_c constraints are considered. Using
inline constraint Var == 50 resulted value on variable Var based on both the default_c
OpenVera and inline constraints.
Constructs
Switch TB
The scope for variable names in a constraint block, from inner to outer, is
RVM Switch TB randomize()...with object class, automatic and local variables, task and function
RVM Ethernet sample arguments, class variables, and variables in the enclosing scope. The
randomize()...with class is brought into scope at the innermost nesting level. In the
f.randomize() with constraint block, x is a member of class Foo and hides the x in
program Bar. It also hides the x argument in the doit() task. y is a member of Bar. z is
Specman E a local argument.
Interview Questions
In the example below, the randomize()...with class is Foo.

EXAMPLE:
  class Foo;
     rand integer x;
  endclass
  
  program  Bar_36;
      Foo obj = new();

http://testbench.in/CR_09_INLINE_CONSTRAINT.html[9/26/2012 2:11:17 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

      integer x;
      integer y;
      
      task doit(Foo f, integer x, integer z);
         int result;
         result = f.randomize() with {x < y + z;};
         $display(":: obj.x : %d :: x : %d :: y : %d :: z : %d ::",obj.x,x,y,z);
      endtask
      
      initial
      begin
         x = 'd10;
      
         repeat(5)
            begin
            y = $urandom % 10;
            doit(obj,x ,'d12);
            end
      end
  endprogram

RESULTS:

 
 :: obj.x : -1538701546 :: x :          10 :: y :           5 :: z :          12 ::
 :: obj.x : -1048494686 :: x :          10 :: y :           9 :: z :          12 ::
 :: obj.x : -1122673684 :: x :          10 :: y :           8 :: z :          12 ::
 :: obj.x : -2050360121 :: x :          10 :: y :           7 :: z :          12 ::
 :: obj.x :  -886228933 :: x :          10 :: y :           3 :: z :          12 ::

 By seeing this output we can tell the variable which used in inline constraint is class
member x.

constraint { x < y + z } means { obj.x < Bar_36.y + do_it.z }

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/CR_09_INLINE_CONSTRAINT.html[9/26/2012 2:11:17 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CR_09_INLINE_CONSTRAINT.html[9/26/2012 2:11:17 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS GLOBAL CONSTRAINT Index


Constrained Random
SystemVerilog Verification
Verification SystemVerilog allows to have constraints between variables of different objects. Verilog Crv
These are called global constraints. Using the hierarchy notation, constraints can be Systemverilog Crv
Constructs applied on variables of different objects. When object is randomized, so are the Randomizing Objects
Interface contained objects and all other constraints are considered simultaneously. Random Variables
Randomization Methods
OOPS Checker
Randomization EXAMPLE: Constraint Block
class child; Inline Constraint
Functional Coverage Global Constraint
  rand int Var1;
Assertion endclass Constraint Mode
                                                                                                                             External Constraints
DPI Randomization
class parent;
UVM Tutorial   rand   child child_obj; Controlability
  rand   int Var2; Static Constraint
VMM Tutorial Constraint Expression
  constraint global_c { Var2 < child_obj.Var1 ;}
OVM Tutorial   function new(); Variable Ordering
     child_obj = new(); Constraint Solver Speed
Easy Labs : SV
  endfunction Randcase
Easy Labs : UVM endclass Randsequence
                                                                                                                             Random Stability
Easy Labs : OVM
program random_37; Array Randomization
Easy Labs : VMM   initial Constraint Guards
AVM Switch TB     for(int i=0;i<5;i++) Titbits
    begin
VMM Ethernet sample       parent parent_obj; Report a Bug or Comment
      parent_obj = new (); on This section - Your
      void'(parent_obj.randomize ()); input is what keeps
Verilog     $display(" Var1 = %0d ,Var2 = %0d ",parent_obj.child_obj.Var1,parent_obj.Var2 ); Testbench.in improving
    end with time!
Verification
endprogram
Verilog Switch TB
Basic Constructs
RESULTS:

#  Var1 = 903271284 ,Var2 = -1102515531


OpenVera #  Var1 = 2112727279 ,Var2 = -838916208
Constructs #  Var1 = 1614679637 ,Var2 = 1572451945
Switch TB #  Var1 = 1284140376 ,Var2 = -373511538
#  Var1 = 463675676 ,Var2 = -516850003
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/CR_10_GLOBAL_CONSTRAINT.html[9/26/2012 2:11:24 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CR_10_GLOBAL_CONSTRAINT.html[9/26/2012 2:11:24 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS CONSTRAINT MODE Index


Constrained Random
SystemVerilog Disabling Constraint Block Verification
Verification Verilog Crv
SystemVerilog supports to change the status of constraint block dynamically. To Systemverilog Crv
Constructs change the status of a Constraint block, built in constraint_mode() method is used. By Randomizing Objects
Interface default all the constraint blocks are active. When it is called as task, the arguments Random Variables
to the task determines the operation to be performed. If the arguments are 0 or 1, Randomization Methods
OOPS Checker
then all the constraints blocks are effected.
Randomization Constraint Block
Inline Constraint
Functional Coverage Global Constraint
EXAMPLE:
Assertion class rand_mo; Constraint Mode
  rand integer Var1; External Constraints
DPI Randomization
  rand integer Var2;
UVM Tutorial   constraint Var_1 { Var1 == 20;} Controlability
  constraint Var_2 { Var2 == 10;} Static Constraint
VMM Tutorial Constraint Expression
endclass
OVM Tutorial Variable Ordering
program rand_mo_p_38; Constraint Solver Speed
Easy Labs : SV
  rand_mo obj = new(); Randcase
Easy Labs : UVM   initial Randsequence
  begin Random Stability
Easy Labs : OVM
    void'(obj.randomize());              //By default all constraints are active. Array Randomization
Easy Labs : VMM     $display(" Var1 : %d   Var2 : %d ",obj.Var1,obj.Var2); Constraint Guards
AVM Switch TB     obj.constraint_mode(0);            //Both constraints Var_1 and Var_2 are turned off. Titbits
    void'(obj.randomize());
VMM Ethernet sample     $display(" Var1 : %d   Var2 : %d ",obj.Var1,obj.Var2); Report a Bug or Comment
    obj.constraint_mode(1);            //Both constraints Var_1 and Var_2 are turned on. on This section - Your
    void'(obj.randomize()); input is what keeps
Verilog     $display(" Var1 : %d   Var2 : %d ",obj.Var1,obj.Var2); Testbench.in improving
  end with time!
Verification
endprogram
Verilog Switch TB
Basic Constructs RESULTS:

#  Var1 :          20   Var2 :          10


#  Var1 :   733126180   Var2 :  -119008195
OpenVera #  Var1 :          20   Var2 :          10
Constructs
Switch TB
RVM Switch TB If the arguments are Variable name, then only the status of that constraint block is
RVM Ethernet sample changed.

EXAMPLE:
Specman E class rand_mo;
Interview Questions   rand integer Var1;
  rand integer Var2;
  constraint Var_1 { Var1 == 20;}
  constraint Var_2 { Var2 == 10;}
endclass

program rand_mo_p_38;
  rand_mo obj = new();
  initial
  begin
    void'(obj.randomize());

http://testbench.in/CR_11_CONSTRAINT_MODE.html[9/26/2012 2:11:32 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

    $display(" Var1 : %d   Var2 : %d ",obj.Var1,obj.Var2);


    obj.Var_1.constraint_mode(0);
    void'(obj.randomize());
    $display(" Var1 : %d   Var2 : %d ",obj.Var1,obj.Var2);
    obj.Var_1.constraint_mode(1);
    void'(obj.randomize());
    $display(" Var1 : %d   Var2 : %d ",obj.Var1,obj.Var2);
  end
endprogram

RESULTS:

Var1 : 20   Var2 : 10


Var1 : 3w456456   Var2 : 10
Var1 : 20   Var2 : 10

When it is called as function, it returns the active status of the specified constraint
block.

EXAMPLE:
     class rand_mo;
         rand integer Var1;
         rand integer Var2;
         constraint Var_1 { Var1 == 20;}
         constraint Var_2 { Var2 == 10;}
        
     endclass
    
     program rand_mo_p_38;
         rand_mo obj = new();
         initial
         begin
            void'(obj.randomize());                //By default all constraints are active.
            $display(" Var1 : %d   Var2 : %d ",obj.Var1,obj.Var2);
            obj.Var_1.constraint_mode(0);          //Both constraint Var_1 is are turned
off.  
            void'(obj.randomize());
            $display(" Var1 : %d   Var2 : %d ",obj.Var1,obj.Var2);
            if (obj.Var_1.constraint_mode())
                $display("Var_1 constraint si active");
            else 
                $display("Var_1 constraint si inactive");
            
            if (obj.Var_2.constraint_mode())
                $display("Var_2 constraint si active");
            else 
                $display("Var_2 constraint si inactive");
              

http://testbench.in/CR_11_CONSTRAINT_MODE.html[9/26/2012 2:11:32 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

            void'(obj.randomize());
            $display(" Var1 : %d   Var2 : %d ",obj.Var1,obj.Var2);
         end
     endprogram

RESULTS:

Var1 :          20   Var2 :          10


Var1 : -2048772810   Var2 :          10
Var_1 constraint si inactive
Var_2 constraint si active
Var1 :  -673275588   Var2 :          10

If you are changing the status of a constraint block, which is not existing, then there
should be a compilation error else contact your Application engineer to file the bug.

EXAMPLE:
   class rand_mo;
     rand integer Var1;
     rand integer Var2;
     constraint Var_1 { Var1 == 20;}
     constraint Var_2 { Var2 == 10;}
   endclass
  
   program rand_mo_p_38;
     rand_mo obj = new();
     initial
     begin
       void'(obj.randomize());
       $display(" Var1 : %d   Var2 : %d ",obj.Var1,obj.Var2);
       obj.Var_3.constraint_mode(0);
       void'(obj.randomize());
       $display(" Var1 : %d   Var2 : %d ",obj.Var1,obj.Var2);
       if(obj.Var_3.constraint_mode())
       $display(" Vat_1 constraint block is off");
       void'(obj.randomize());
       $display(" Var1 : %d   Var2 : %d ",obj.Var1,obj.Var2);
     end
   endprogram
  

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CR_11_CONSTRAINT_MODE.html[9/26/2012 2:11:32 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS EXTERNAL CONSTRAINTS Index


Constrained Random
SystemVerilog Verification
Verification Constraint blocks can be defined externally in the same file or other files. Defining the Verilog Crv
constraints in external file, gives some what aspect oriented style of programming. Systemverilog Crv
Constructs For example, test_1 requires Var between 0 to 100 and tets_2 requires Var between Randomizing Objects
Interface 50 to 100.Declare the constraint block as empty and define them in other files. Random Variables
Randomization Methods
OOPS Checker
Randomization EXAMPLE: Constraint Block
    class Base; Inline Constraint
Functional Coverage Global Constraint
      rand integer Var;
Assertion       constraint range;  Constraint Mode
    endclass External Constraints
DPI Randomization
    
UVM Tutorial     program inhe_39; Controlability
    Base obj; Static Constraint
VMM Tutorial Constraint Expression
    initial
OVM Tutorial     begin Variable Ordering
      obj = new(); Constraint Solver Speed
Easy Labs : SV
      for(int i=0 ; i < 100 ; i++) Randcase
Easy Labs : UVM         if(obj.randomize()) Randsequence
          $display(" Randomization sucsessfull : Var = %0d ",obj.Var); Random Stability
Easy Labs : OVM
        else Array Randomization
Easy Labs : VMM           $display("Randomization failed"); Constraint Guards
AVM Switch TB     end Titbits
    endprogram
VMM Ethernet sample Report a Bug or Comment
In test_1 file,include on This section - Your
   constraint Base::range { Var < 100; Var > 0;} input is what keeps
Verilog In test_2 file,include Testbench.in improving
   constraint Base::range { Var < 100; Var > 50;} with time!
Verification
Verilog Switch TB  Very popular verilog style of including testcases is by using `include which can also be
Basic Constructs used hear.
 Write the constraints in a file and include it.

//
OpenVera EXAMPLE:
Constructs    class Base;
Switch TB      rand integer Var;
     `include "constraint.sv"
RVM Switch TB    endclass
RVM Ethernet sample   
   program inhe_40;
     Base obj;
     initial
Specman E      begin
Interview Questions        obj = new();
       for(int i=0 ; i < 100 ; i++)
         if(obj.randomize())
           $display(" Randomization sucsessfull : Var = %0d ",obj.Var);
         else
           $display("Randomization failed");
     end
   endprogram

http://testbench.in/CR_12_EXTERNAL_CONSTRAINTS.html[9/26/2012 2:11:39 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

Constraint Hiding

In SV Std 1800-2005 LRM , its not mentioned any where that constraints can be
declared as local or protected. If they support to declare constraints as local, it would
be helpful not to switchoff the constraint block accedentally is it is not supposed to
be done. The constraint BNF explicitly excludes the local and protected modifiers.
The main reason for their exclusion is because constraints behave like virtual methods
that are called by the built-in randomize method. If a constraint were declared
local/protected it would still be visible to randomize and participate in the constraint
equations. The only limitation would be to call the constraint_mode on
local/protected constraints from certain methods, and this does not seem very useful
and probably create more confusion with regards to overridden methods.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CR_12_EXTERNAL_CONSTRAINTS.html[9/26/2012 2:11:39 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS RANDOMIZATION CONTROLABILITY Index


Constrained Random
SystemVerilog Controlability Verification
Verification Verilog Crv
Additional to the controllability feauters supported by SystemVerilog, following are Systemverilog Crv
Constructs more points with which controlabiity can be achieved. Randomizing Objects
Interface Random Variables
In the following example, MACROS MIN_D and MAX_D are defined. Set the MIN and MAX Randomization Methods
OOPS Checker
values in the pre_randomize as shown. As MIN_D and MAX_D are macros, they can be
Randomization assigned from command line. Biggest disadvantage for the method shown below is Constraint Block
dynamic controllability. Inline Constraint
Functional Coverage Global Constraint
Assertion Constraint Mode
EXAMPLE: External Constraints
DPI Randomization
   `define MAX_D 100
UVM Tutorial    `define MIN_D 50 Controlability
   class Base; Static Constraint
VMM Tutorial Constraint Expression
     rand integer Var;
OVM Tutorial      integer MIN,MAX; Variable Ordering
     constraint randge { Var < MAX ; Var > MIN ;} Constraint Solver Speed
Easy Labs : SV
     function void pre_randomize (); Randcase
Easy Labs : UVM        this.MIN = `MIN_D; Randsequence
       this.MAX = `MAX_D; Random Stability
Easy Labs : OVM
       $display( " PRE_RANDOMIZE : MIN = %0d , MAX = %0d ",MIN,MAX); Array Randomization
Easy Labs : VMM      endfunction Constraint Guards
AVM Switch TB    endclass Titbits
  
VMM Ethernet sample    program inhe_42; Report a Bug or Comment
     Base obj; on This section - Your
     initial input is what keeps
Verilog      begin Testbench.in improving
       obj = new(); with time!
Verification
       for(int i=0 ; i < 100 ; i++)
Verilog Switch TB          if(obj.randomize())
Basic Constructs            $display(" Randomization sucsessfull : Var = %0d ",obj.Var);
         else
           $display("Randomization failed");
     end
OpenVera    endprogram
Constructs  
Switch TB
RESULTS:
RVM Switch TB
RVM Ethernet sample #  PRE_RANDOMIZE : MIN = 50 , MAX = 100
#  Randomization sucsessfull : Var = 91
#  PRE_RANDOMIZE : MIN = 50 , MAX = 100
#  Randomization sucsessfull : Var = 93
Specman E #  PRE_RANDOMIZE : MIN = 50 , MAX = 100
Interview Questions #  Randomization sucsessfull : Var = 77
#  PRE_RANDOMIZE : MIN = 50 , MAX = 100
#  Randomization sucsessfull : Var = 68
#  PRE_RANDOMIZE : MIN = 50 , MAX = 100
#  Randomization sucsessfull : Var = 67
#  PRE_RANDOMIZE : MIN = 50 , MAX = 100
#  Randomization sucsessfull : Var = 52
#  PRE_RANDOMIZE : MIN = 50 , MAX = 100
#  Randomization sucsessfull : Var = 71
#  PRE_RANDOMIZE : MIN = 50 , MAX = 100
#  Randomization sucsessfull : Var = 98

http://testbench.in/CR_13_RANDOMIZATION_CONTROLABILITY.html[9/26/2012 2:11:48 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

...etc.

As in this example,a single object is created and randomized 100 times. Due to
this,pre_reandomize is called 100 times, which may not be preferred.
By assigning the values while declaration itself this can be avoided. Simpler way to
achieve the above logic.

EXAMPLE:
`define MAX_D 100
`define MIN_D 50
class Base;
  rand integer Var;
  integer MIN = `MIN_D;
  integer MAX = `MAX_D;
  constraint range { Var < MAX ; Var > MIN ;}
endclass

program inhe_43;
  Base obj;
  initial
  begin
    obj = new();
    for(int i=0 ; i < 100 ; i++)
      if(obj.randomize())
        $display(" Randomization sucsessfull : Var = %0d ",obj.Var);
      else
        $display("Randomization failed");
  end
endprogram

RESULTS:

#  Randomization sucsessfull : Var = 91


#  Randomization sucsessfull : Var = 93
#  Randomization sucsessfull : Var = 77
#  Randomization sucsessfull : Var = 68
#  Randomization sucsessfull : Var = 67
#  Randomization sucsessfull : Var = 52
#  Randomization sucsessfull : Var = 71
#  Randomization sucsessfull : Var = 98
#  Randomization sucsessfull : Var = 69
#  Randomization sucsessfull : Var = 70
...etc.

With the above approach also, dynamic controlability is lost. For dynamic
controllability, define a task, pass this values as arguments when ever the changed is
needed.

http://testbench.in/CR_13_RANDOMIZATION_CONTROLABILITY.html[9/26/2012 2:11:48 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

EXAMPLE:
class Base;
  rand integer Var;
  integer MIN = 10,MAX = 20;  // Define default values,If function set is not
called,with this it will work
  constraint randge { Var < MAX ; Var > MIN ;}
  task set (integer MIN,integer MAX);
    this.MIN = MIN;
    this.MAX = MAX;
    $display( " SET : MIN = %0d , MAX = %0d ",MIN,MAX);
  endtask
endclass

program inhe_44;
  Base obj;
  
  initial
  begin
    obj = new();
    obj.set(0,100) ;
    for(int i=0 ; i < 5 ; i++)
      if(obj.randomize())
        $display(" Randomization sucsessfull : Var = %0d ",obj.Var);
      else
        $display("Randomization failed");
    
    obj.set(50,100) ;
    for(int i=0 ; i < 5 ; i++)
      if(obj.randomize())
        $display(" Randomization sucsessfull : Var = %0d ",obj.Var);
      else
        $display("Randomization failed");
  end
endprogram
RESULTS:

#  SET : MIN = 0 , MAX = 100


#  Randomization sucsessfull : Var = 24
#  Randomization sucsessfull : Var = 68
#  Randomization sucsessfull : Var = 43
#  Randomization sucsessfull : Var = 11
#  Randomization sucsessfull : Var = 4
#  SET : MIN = 50 , MAX = 100
#  Randomization sucsessfull : Var = 52
#  Randomization sucsessfull : Var = 71
#  Randomization sucsessfull : Var = 98
#  Randomization sucsessfull : Var = 69
#  Randomization sucsessfull : Var = 70

More simpler way to dynamically modifying the constraints is by modifying the data
members of class via object reference.

EXAMPLE:
class Base;
  rand integer Var;
  integer MIN = 20,MAX =30;
  constraint randge { Var < MAX ; Var > MIN ;}
endclass

program inhe_45;
  Base obj;
  
  initial
  begin
    obj = new();
    obj.MIN = 0;
    obj.MAX = 100;
    for(int i=0 ; i < 5 ; i++)
    if(obj.randomize())

http://testbench.in/CR_13_RANDOMIZATION_CONTROLABILITY.html[9/26/2012 2:11:48 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

      $display(" Randomization sucsessfull : Var = %0d ",obj.Var);


    else
      $display("Randomization failed");
      $display("MIN and MAX changed");
    
    obj.MIN = 50;
    obj.MAX = 100;
    for(int i=0 ; i < 5 ; i++)
      if(obj.randomize())
        $display(" Randomization sucsessfull : Var = %0d ",obj.Var);
      else
        $display("Randomization failed");
  end
endprogram

RESULTS:

#  Randomization sucsessfull : Var = 24


#  Randomization sucsessfull : Var = 68
#  Randomization sucsessfull : Var = 43
#  Randomization sucsessfull : Var = 11
#  Randomization sucsessfull : Var = 4
# MIN and MAX changed
#  Randomization sucsessfull : Var = 52
#  Randomization sucsessfull : Var = 71
#  Randomization sucsessfull : Var = 98
#  Randomization sucsessfull : Var = 69
#  Randomization sucsessfull : Var = 70

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CR_13_RANDOMIZATION_CONTROLABILITY.html[9/26/2012 2:11:48 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS STATIC CONSTRAINT Index


Constrained Random
SystemVerilog Verification
Verification If a constraint block is declared as static, then constraint mode on that block will Verilog Crv
effect on all the instancess of that class. In the following example, two objects obj_1 Systemverilog Crv
Constructs and obj_2 are declared. Constraints Var1_c is static and Var2_c is not static. When Randomizing Objects
Interface constraint_mode is used to switch off the constraints in in obj_2, constraint var1_c in Random Variables
obj_1 is also switched off. Randomization Methods
OOPS Checker
Randomization   Constraint Block
EXAMPLE: Inline Constraint
Functional Coverage Global Constraint
class A;
Assertion   rand integer Var1, Var2; Constraint Mode
  static constraint Var1_c { Var1 == 10 ;} External Constraints
DPI Randomization
  constraint Var2_c { Var2 == 10 ;}
UVM Tutorial endclass Controlability
Static Constraint
VMM Tutorial Constraint Expression
program A_p_46;
OVM Tutorial   A obj_1 = new; Variable Ordering
  A obj_2 = new; Constraint Solver Speed
Easy Labs : SV
  initial Randcase
Easy Labs : UVM   begin Randsequence
    obj_2.Var1_c.constraint_mode(0); Random Stability
Easy Labs : OVM
    obj_2.Var2_c.constraint_mode(0); Array Randomization
Easy Labs : VMM     repeat(10) Constraint Guards
AVM Switch TB     begin Titbits
      void'(obj_1.randomize());
VMM Ethernet sample       $display("obj_1.Var1 : %d ,obj_1.Var2 : %d ",obj_1.Var1,obj_1.Var2);  Report a Bug or Comment
    end  on This section - Your
  end input is what keeps
Verilog endprogram Testbench.in improving
with time!
Verification
RESULTS:
Verilog Switch TB
Basic Constructs # obj_1.Var1 :   733126180 ,obj_1.Var2 :          10
# obj_1.Var1 :  -119008195 ,obj_1.Var2 :          10
# obj_1.Var1 :   342785185 ,obj_1.Var2 :          10
# obj_1.Var1 :   679818185 ,obj_1.Var2 :          10
OpenVera # obj_1.Var1 :  -717162992 ,obj_1.Var2 :          10
Constructs # obj_1.Var1 :   664520634 ,obj_1.Var2 :          10
Switch TB # obj_1.Var1 : -1944980214 ,obj_1.Var2 :          10
# obj_1.Var1 : -1350759145 ,obj_1.Var2 :          10
RVM Switch TB # obj_1.Var1 : -1374963034 ,obj_1.Var2 :          10
RVM Ethernet sample # obj_1.Var1 :  -462078992 ,obj_1.Var2 :          10

Specman E
Interview Questions

http://testbench.in/CR_14_STATIC_CONSTRAINT.html[9/26/2012 2:11:56 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CR_14_STATIC_CONSTRAINT.html[9/26/2012 2:11:56 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS CONSTRAINT EXPRESSION Index


Constrained Random
SystemVerilog Verification
Verification A constraint_expression is any SystemVerilog expression or one of the constraint Verilog Crv
specific operators( -> (Implication) and dist). Functions are allowed to certain Systemverilog Crv
Constructs limitation. Operators which has side effects are not allowed like ++,--. Randomizing Objects
Interface Random Variables
Randomization Methods
OOPS Checker
Randomization Set Membership Constraint Block
Inline Constraint
Functional Coverage Global Constraint
A set membership is a list of expressions or a range. This operator searches for the
Assertion existences of the value in the specified expression or range and returns 1 if it is Constraint Mode
existing. External Constraints
DPI Randomization
UVM Tutorial Controlability
EXAMPLE: Static Constraint
VMM Tutorial Constraint Expression
class set_mem;
OVM Tutorial   rand integer Var; Variable Ordering
  constraint range { Var inside {0,1,[50:60],[90:100]}; } Constraint Solver Speed
Easy Labs : SV
  function void post_randomize(); Randcase
Easy Labs : UVM     $write("%0d__",Var); Randsequence
  endfunction Random Stability
Easy Labs : OVM
endclass Array Randomization
Easy Labs : VMM Constraint Guards
AVM Switch TB program set_mem_p_47; Titbits
  set_mem obj=new();
VMM Ethernet sample   initial Report a Bug or Comment
    repeat(10) on This section - Your
      void'(obj.randomize()); input is what keeps
Verilog endprogram Testbench.in improving
with time!
Verification
RESULTS:
Verilog Switch TB
Basic Constructs 50__57__60__93__100__94__90__1__54__100__

If you want to define a range which is outside the set, use negation.
OpenVera
Constructs
Switch TB EXAMPLE:
class set_mem;
RVM Switch TB   rand bit [0:2] Var;
RVM Ethernet sample   constraint range { !( Var inside {0,1,5,6});}
  function void post_randomize();
    $write("%0d__",Var);
  endfunction
Specman E endclass
Interview Questions                                                                                                                             
program set_mem_p_48;
  set_mem obj=new();
  initial
    repeat(10)
      void'(obj.randomize());
endprogram

RESULTS:

http://testbench.in/CR_15_CONSTRAINT_EXPRESSION.html[9/26/2012 2:12:07 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

7__4__4__4__7__2__2__3__2__7__

Engineers often mistaken that set membership operator is used only in constraint
block. It can also be used in other scopes also.

class set_mem;
  rand bit [0:2] Var;
endclass
                                                                                                                            
program set_mem_p_48;
  set_mem obj=new();
  integer repet = 0;
  initial
  begin
      obj.Var = 1;
      repeat(10)
      begin
      void'(obj.randomize());      
      while ( obj.Var inside {[1:5]})
      begin
        $display("Var = %0d",obj.Var);        
        break;
      end
      end
    end  
endprogram
RESULTS:

# Var = 4
# Var = 5
# Var = 1
# Var = 1
# Var = 2
# Var = 2

NOTE: X and Z are allowed in set membership operator, but not in constraint block,
inside {....} is a statement which returns 0,1 or X .
Expressions are allowed in value set of inside operator.

rand integer y,x;
constraint c1 {x inside {3, 5,[y:2*y], z};}

If an expression in the list is an array then just use the array name in the constraint
block. Elements are traversed by descending into the array until reaching a singular
value.

http://testbench.in/CR_15_CONSTRAINT_EXPRESSION.html[9/26/2012 2:12:07 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

int array [$] = '{3,4,5};
if ( ex inside {1, 2, array} )

Weighted Distribution

There are two types of distribution operators.


The := operator assigns the specified weight to the item or, if the item is a range, to
every value in the range.
The :/ operator assigns the specified weight to the item or, if the item is a range, to
the range as a whole. If there are n values in the range, the weight of each value is
range_weight / n.

Var dist { 10 := 1; 20 := 2 ; 30 := 2 }

The probability of Var is equal to 10,20 and 30 is in the ratio of 1,2,2 respectively.

Var dist { 10 := 1; 20 := 2 ; [30:32] := 2 }

The probability of Var is equal to 10,20,30,31 and 32 is in the ratio of 1,2,2,2,2


respectively.
If you use the := operator each element weitht of the range has the assigned weight.
If you want to weight for the whole group,use :/ and the weight is equally distributed
for each element in that group.

Var dist { 10 := 1; 20 := 2 ; [30:32] :/ 2 }

The probability of Var is equal to  10,20,30,31,32 is in the ration of 1,2,2/3,2/3,2/3


respectively.

To demonstrate the distribution property,hear is an example.

EXAMPLE:
class Dist;
  rand integer Var;
  constraint range { Var dist { [0:1] := 50 , [2:7] := 50 }; }
endclass

program Dist_p_49;
  Dist obj;
  integer count_0, count_1, count_2, count_3, count_4, count_5, count_6, count_7;
  integer count_0_1 ,count_2_7 ;
  
  initial
  begin
    obj=new();
    count_0 = 0;count_1 = 0;count_2 = 0;count_3 = 0;
    count_4 = 0;count_5 = 0;count_6 = 0;count_7 = 0;
    count_0_1 = 0;count_2_7 = 0;
    for(int i=0; i< 10000; i++)
      if( obj.randomize())
      begin
        if( obj.Var == 0) count_0 ++;
        else if( obj.Var == 1) count_1 ++;
        else if( obj.Var == 2) count_2 ++;
        else if( obj.Var == 3) count_3 ++;
        else if( obj.Var == 4) count_4 ++;
        else if( obj.Var == 5) count_5 ++;
        else if( obj.Var == 6) count_6 ++;
        else if( obj.Var == 7) count_7 ++;
        if( obj.Var inside {0,1} ) count_0_1 ++;
        else if( obj.Var inside {[2:7]} ) count_2_7 ++;
      end
  
    $display(" count_0 = %0d , count_1 = %0d, count_2 = %0d, count_3 = %0d, count_4 =
%0d, count_5 = %0d, count_6 = %0d, count_7= %0d
",count_0, count_1, count_2, count_3, count_4, count_5, count_6, count_7);
    $display(" count_0_1 = %0d ;count_2_7 = %0d ",count_0_1,count_2_7);
    $finish;
  end
endprogram

http://testbench.in/CR_15_CONSTRAINT_EXPRESSION.html[9/26/2012 2:12:07 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

RESULTS:

#  count_0 = 1290 , count_1 = 1244, count_2 = 1286, count_3 = 1265, count_4 = 1230,
count_5 = 1243, count_6 = 1189, count_7= 1253
#  count_0_1 = 2534 ;count_2_7 = 7466

Now change the constraint to

constraint range { Var dist { [0:1] :/ 50 , [2:7] :/ 50 }; }

EXAMPLE:
class Dist;
  rand integer Var;
  constraint range { Var dist { [0:1] :/ 50 , [2:7] :/ 50 }; }
endclass

program Dist_p_50;
  Dist obj;
  integer count_0, count_1, count_2, count_3, count_4, count_5, count_6, count_7;
  integer count_0_1 ,count_2_7 ;
  
  initial
  begin
    obj=new();
    count_0 = 0;count_1 = 0;count_2 = 0;count_3 = 0;
    count_4 = 0;count_5 = 0;count_6 = 0;count_7 = 0;
    count_0_1 = 0;count_2_7 = 0;
    
    for(int i=0; i< 10000; i++)
      if( obj.randomize())
      begin
        if( obj.Var == 0) count_0 ++;
        else if( obj.Var == 1) count_1 ++;
        else if( obj.Var == 2) count_2 ++;
        else if( obj.Var == 3) count_3 ++;
        else if( obj.Var == 4) count_4 ++;
        else if( obj.Var == 5) count_5 ++;
        else if( obj.Var == 6) count_6 ++;
        else if( obj.Var == 7) count_7 ++;
        if( obj.Var inside {0,1} ) count_0_1 ++;
        else if( obj.Var inside {[2:7]} ) count_2_7 ++;
      end

    $display(" count_0 = %0d , count_1 = %0d, count_2 = %0d, count_3 = %0d, count_4 =
%0d, count_5 = %0d, count_6 = %0d, count_7= %0d
",count_0, count_1, count_2, count_3, count_4, count_5, count_6, count_7);
    $display(" count_0_1 = %0d ;count_2_7 = %0d ",count_0_1,count_2_7);
    $finish;
    end
endprogram

RESULTS:

#  count_0 = 2496, count_1 = 2508, count_2 = 846, count_3 = 824, count_4 = 833,
count_5 = 862, count_6 = 820, count_7= 811
#  count_0_1 = 5004 ;count_2_7 = 4996

Both the results show, how may times each value occured.

NOTE: If no weight is specified for items,the default weight is 1. Weight 0 is also


allowed.
NOTE: Variable declared as randc are not allowed int dist.

If there are constraints on some expressions that cause the distribution weights on
these expressions to be not satisfiable, implementations are only required to satisfy
the non dist constraints. Use dist only on a one variable in a set of constraint
expression variable.
In the following example, Even though probability of Var2 is equal to 0 to 1 is in ratio
of 50, 50 to satisfy other constraints, the dist is ignored.

http://testbench.in/CR_15_CONSTRAINT_EXPRESSION.html[9/26/2012 2:12:07 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

EXAMPLE:
class Dist;
  rand integer Var1,Var2;
  constraint dist_c { Var2 dist { [0:1] := 50 , [2:7] := 50 }; }
  constraint relation_c { Var1 < Var2; }
  constraint range_c { Var2 inside {2,3,4};}
endclass

program Dist_p_51;
  Dist obj;
  integer count_0, count_1, count_2, count_3, count_4, count_5, count_6, count_7;
  integer count_0_1 ,count_2_7 ;

  initial
  begin
    obj=new();
    count_0 = 0;count_1 = 0;count_2 = 0;count_3 = 0;
    count_4 = 0;count_5 = 0;count_6 = 0;count_7 = 0;
    count_0_1 = 0;count_2_7 = 0;
  
    for(int i=0; i< 10000; i++)
      if( obj.randomize())
      begin
        if( obj.Var2 == 0) count_0 ++;
        else if( obj.Var2 == 1) count_1 ++;
        else if( obj.Var2 == 2) count_2 ++;
        else if( obj.Var2 == 3) count_3 ++;
        else if( obj.Var2 == 4) count_4 ++;
        else if( obj.Var2 == 5) count_5 ++;
        else if( obj.Var2 == 6) count_6 ++;
        else if( obj.Var2 == 7) count_7 ++;
        if( obj.Var2 inside {0,1} ) count_0_1 ++;
        else if( obj.Var2 inside {[2:7]} ) count_2_7 ++;
      end
    
    $display(" count_0 = %0d , count_1 = %0d, count_2 = %0d, count_3 = %0d, count_4 =
%0d, count_5 = %0d, count_6 = %0d, count_7= %0d
",count_0, count_1, count_2, count_3, count_4, count_5, count_6, count_7);
    $display(" count_0_1 = %0d ;count_2_7 = %0d ",count_0_1,count_2_7);
    $finish;
  end
endprogram

RESULTS:

#  count_0 = 0 , count_1 = 0, count_2 = 3362, count_3 = 3321, count_4 = 3317,


count_5 = 0, count_6 = 0, count_7= 0
#  count_0_1 = 0 ;count_2_7 = 10000

Calling a new(), resets the distrubution algorithem. If new() is called to creat an


object when ever randomized is called,the dist algorithm restarts and the distribution
may not be what is expected.

EXAMPLE:
class Dist;
   rand integer Var;
   constraint range { Var dist { [0:1] := 50 , [2:7] := 50 }; }
endclass
                                                                                                                            
program Dist_p_52;
   Dist obj;
   integer count_0_1 ,count_2_7 ;
  
   initial
   begin
       obj=new();
       count_0_1 = 0;count_2_7 = 0;
       for(int i=0; i< 10000; i++)
       begin

http://testbench.in/CR_15_CONSTRAINT_EXPRESSION.html[9/26/2012 2:12:07 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

          obj = new();
          if( obj.randomize())
          if( obj.Var inside {0,1} ) count_0_1 ++;
          else if( obj.Var inside {[2:7]} ) count_2_7 ++;
       end
       $display("count_0_1 : %0d : count_2_7 : %0d  ",count_0_1,count_2_7);
   end
endprogram  
        
RESULTS:

# count_0_1 : 3478 : count_2_7 : 6522  

The distribution is not followed if the variable is declared as randc as distribution may
require repetition and randc doesnot allow. In the below example try changing the
weights in distribution function,  you will get always same results otherwise
compilation error.

 
EXAMPLE:
   class Dist;
       randc byte Var;
       constraint range { Var dist { [0:1] := 50 , [2:7] := 50 }; }
   endclass
                                                                                                                                
   program Dist_p_52;
      Dist obj;
      integer count_0_1 ,count_2_7 ;
      
      initial
      begin
         obj=new();
         count_0_1 = 0;count_2_7 = 0;
         for(int i=0; i< 10000; i++)
         begin
            if( obj.randomize())
            if( obj.Var inside {0,1} ) count_0_1 ++;
            else if( obj.Var inside {[2:7]} ) count_2_7 ++;
            end
            $display("count_0_1 : %0d : count_2_7 : %0d  ",count_0_1,count_2_7);
      end
   endprogram  
  

To constraint enumerated values using dist, if they are less number, give weights
individually. If you want to give weights to enumerated values in groups, then give a
continues group. As enumeration is represented in integer, the discontinuation in the
declaration may not result properly.

EXAMPLE:
program enums_53;
 typedef enum {V_SMALL,SMALL,MEDIUM,LARGE,V_LARGE} size_e;
 class dist_c;
   rand size_e size_d;
   constraint size_dist{size_d
dist {[V_SMALL:MEDIUM] :/40,[LARGE:V_LARGE] :/ 60}; }
 endclass 

initial begin
  dist_c obj;
  obj=new;
  for (int i=0; i<=10; i++)
  begin
  obj.randomize();
  $display (" size_d = %0s ", obj.size_d);
  end
end 
endprogram

http://testbench.in/CR_15_CONSTRAINT_EXPRESSION.html[9/26/2012 2:12:07 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

Implication

Implication operator can be used to declare conditional relation. The syntax is


expression -> constraint set. If the expression is true,then the constraint solver should
satisfy the constraint set. If the expression is false then the random numbers
generated are unconstrainted by constraint set. The boolean equivalent of a -> b is
(!a || b).

rand bit a;
rand bit [3:0] b;
constraint c { (a == 0) -> (b == 1); }

a is one and b is 4 bit, So there are total of 32 solutions. But due to constraint c
(when  ever a is 0 b should be 1) 15 solutions are removed. So probability of a = 0 is
1/(32-15) = 1/17. If u observe the following program results        count_0/count_1
approximately equal to 1/17.  

EXAMPLE:
class impli;
  rand bit a;
  rand bit [3:0] b;
  constraint c { (a == 0) -> (b == 1); }
endclass
                                                                                                                            
program impli_p_54;
  impli obj;
  integer count_0 ,count_1 ;
  
  initial
  begin
    obj=new();
    count_0 = 0;count_1 = 0;
    for(int i=0; i< 10000; i++)
    begin
      if( obj.randomize())
      if( obj.a == 0 ) count_0 ++;
      else count_1 ++;
  end
    $display(" count_0 = %0d;count_1 = %0d; ",count_0 ,count_1);
  end
endprogram 

RESULTS:

#  count_0 = 571;count_1 = 9429;

If..Else

Just like implication, if...else style constraints are bidirectional.Above example


applies hear too.

EXAMPLE:
class if_else;
  rand bit a;
  rand bit [3:0] b;
  constraint c { if(a == 0) (b == 1); }
endclass
                                                                                                                            
program if_else_p_55;
  if_else obj;
  integer count_0 ,count_1 ;
  
  initial
  begin
    obj=new();
    count_0 = 0;count_1 = 0;
    for(int i=0; i< 10000; i++)
    begin
      obj = new();
      if( obj.randomize())
      begin

http://testbench.in/CR_15_CONSTRAINT_EXPRESSION.html[9/26/2012 2:12:07 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

        if( obj.a == 0 ) count_0 ++;


        else if( obj.a == 1 ) count_1 ++;
      end
    end
    $display(" count_0 = %0d;count_1 = %0d;",count_0 ,count_1);
  end
endprogram
 
RESULTS:

#  count_0 = 571;count_1 = 9429;

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CR_15_CONSTRAINT_EXPRESSION.html[9/26/2012 2:12:07 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS VARIABLE ORDERING Index


Constrained Random
SystemVerilog Verification
Verification SystemVerilog constraints provide a mechanism for ordering variables so that some Verilog Crv
variables can be chosen independently of some variables. The solution space remains Systemverilog Crv
Constructs the same, but the probability of picking up the solution space changes. The syntax for Randomizing Objects
Interface variable ordering is "solve x before y". The exact meaning of this statement is "choos x Random Variables
before y"  as the this statement is to guide the distribution, but not the solution Randomization Methods
OOPS Checker
space.
Randomization Only rand variables are allowed. Constraint Block
Inline Constraint
Functional Coverage Global Constraint
EXAMPLE:
Assertion class Var_order_56; Constraint Mode
  rand bit a; External Constraints
DPI Randomization
  rand bit [3:0] b;
UVM Tutorial   constraint bidirectional { a -> b == 0; } Controlability
endclass Static Constraint
VMM Tutorial Constraint Expression
OVM Tutorial Variable Ordering
The probability of a=1 is 1/((2**5)-15)=1/17, as constraints are bidirectional i.e both Constraint Solver Speed
Easy Labs : SV
the values of a and b are determined together. Constraints will be solved only once, Randcase
Easy Labs : UVM the solver picks the one solution from the possible set of {a,b} which has 17 solutions. Randsequence
To guide the probability of selecting a= 0 to 50% and a = 1 to 50%, use Random Stability
Easy Labs : OVM
Array Randomization
Easy Labs : VMM constraint order { solve a before b ;} Constraint Guards
AVM Switch TB Titbits
This guides the solver to give highest priority to a than b while picking the solution
VMM Ethernet sample from solution space. This is explicit variable ordering. The solver follows the implicit Report a Bug or Comment
variable ordering also, like randc are solved before rand variables. In dynamic arrays on This section - Your
size and elements are solved with two constraints( size constraint and element value input is what keeps
Verilog constraint) ,array size is solved before element. Testbench.in improving
with time!
Verification
Verilog Switch TB EXAMPLE:
Basic Constructs class if_57;
  rand bit a;
  rand bit [3:0] b;
  constraint c { if(a == 0) (b == 1); }
OpenVera   constraint order { solve a before b;}
Constructs endclass
Switch TB                                                                                                                             
program if_p;
RVM Switch TB   if_57 obj;
RVM Ethernet sample   integer count_0 ,count_1 ;
  
  initial
  begin
Specman E     count_0 = 0;count_1 = 0;
Interview Questions     for(int i=0; i< 10000; i++)
    begin
      obj = new();
      if( obj.randomize())
      if( obj.a == 0 ) count_0 ++;
      else if( obj.a == 1 ) count_1 ++;
    end
    $display(" count_0 = %0d;count_1 = %0d;",count_0 ,count_1);
  end
endprogram

http://testbench.in/CR_16_VARIABLE_ORDERING.html[9/26/2012 2:12:17 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

RESULTS:

#  count_0 = 4974;count_1 = 5026;

Too many explicit variable ordering may lead to circular dependency. The LRM says
that "Circular dependencies created by the implicit variable ordering shall result in an
error." and "circular dependency is not allowed". But it does not put restriction on
what to do if a explicit circular dependency exists. Check with your tool, if explicit
Circular dependency is existing, it may report warning,it may fail solver or proceed by
just ignoring the order.

EXAMPLE:
program Cir_Dip_p_58;
  class Cir_Dep;
    rand integer a,b,c;
    constraint a_c { solve a before b ;}
    constraint b_c { solve b before c ;}
    constraint c_c { solve c before a ;}
  endclass
  
  Cir_Dip obj=new();
  initial
    void'(obj.randomize());
endprogram

RESULTS:

Error: Cird.sv(14): Cyclical dependency between random variables specified by


solve/before constraints.

LRM says, if the outcome is same, solver can solve without following the rule. In the
following case, x has only one possible assignment (0), so x can be solved for before
y. The constraint solver can use this flexibility to speed up the solving process.

EXAMPLE:
   class slove_before;
      rand integer x,y;
      constraint C {x == 0;
                    x < y;
                   solve y before x; }
   endclass

   program s_b_59;
      slove_before obj ;
      initial
      begin
         obj = new();
         repeat(5)

http://testbench.in/CR_16_VARIABLE_ORDERING.html[9/26/2012 2:12:17 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

            if(obj.randomize())
                $display(" x : %d :: y :%d ",obj.x,obj.y);
            else
                $display("Randomization failed ");
      end
   endprogram

RESULTS:

#  x :           0 :: y: 2064490291


#  x :           0 :: y: 2035140763
#  x :           0 :: y: 1279931677
#  x :           0 :: y: 2112945927
#  x :           0 :: y: 1977312554

Functions

Functions are allowed in constraints. It will be useful in applications like constrain the
max packet size based on the bandwidth other parameters.  Constraint statements are
more error pron. Functions in constraints are called before constraints are solved. The
return value of the function is used to solve the constraint and it is treated as state
variable. There is an implicit variable ordering when solving these constraints.
Function should not be declared as static and should not modify the constraints, for
example calling the rand_mode and constraint_mode methods.

EXAMPLE:
class B_61;
  rand int x, y;
  constraint C { x <= F(y); }
  constraint D { y inside { 2, 4, 8 } ; }
endclass

Random variables used as function arguments shall establish an implicit variable


ordering or priority. Constraints that include only variables with higher priority are
solved before other lower priority constraints. Random variables solved as part of a
higher priority set of constraints, become state variables to the remaining set of
constraints. In above example y is solved before x. If y is not rand variable, then F(y)
is equalent to calling it in the pre_randomize method.

Iterative Constraints

Iterative constraints allow Constraining individual elements of fixed-size, dynamic,


associative arrays or queue. foreach construct specifies iteration over the each
elements of array.

EXAMPLE:
class Eth_pkt_60;
  rand byte Payload[] ;
  constraint size_c { Payload.size() inside {[10:1500]}; }
  constraint element_c { foreach ( Payload[ i ] )  Payload[ i ] inside {[50:100]}; }
    function void post_randomize;
      foreach(Payload[i])
        $display( " Payload[ %0d ] :%d ",i,Payload[ i ] );    
    endfunction
endclass

program iterative_60;
  Eth_pkt_60 obj;
  initial
  begin
    obj = new();
    if(obj.randomize())
      $display(" RANDOMIZATION DONE ");
  end
endprogram

RESULTS:

http://testbench.in/CR_16_VARIABLE_ORDERING.html[9/26/2012 2:12:17 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

#  Payload[ 0 ] :  87
#  Payload[ 1 ] :  52
#  Payload[ 2 ] :  70
#  Payload[ 3 ] :  76
#  Payload[ 4 ] :  71
#  Payload[ 5 ] :  63
#  Payload[ 6 ] :  62
#  Payload[ 7 ] :  63
#  Payload[ 8 ] :  66
#  Payload[ 9 ] :  85
#  Payload[ 10 ] :  95
#  Payload[ 11 ] :  57
#  Payload[ 12 ] :  78

NOTE: Remember while randomizing each element of array also array should be


declared as random variable otherwise randomization wont happen.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CR_16_VARIABLE_ORDERING.html[9/26/2012 2:12:17 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS CONSTRAINT SOLVER SPEED Index


Constrained Random
SystemVerilog Verification
Verification IEEE SystemVerilog 2005 LRM does not specify the constraint solver algorithm. So Verilog Crv
different vendors use different consraint solver algorithms. Some vendors may get the Systemverilog Crv
Constructs solution quickly, some may not. Randomizing Objects
Interface All the points discussed in this are not specific to a vendor. Just check your tool with Random Variables
these examples to know how ur vendor constraint solver works. Randomization Methods
OOPS Checker
Randomization As it is handy to type int and integer, we always declare some data types like size of Constraint Block
dynamic arrays as integer and constraint it to required range. Inline Constraint
Functional Coverage Global Constraint
This will create 2^32 values and solver has to choose random number and solve the
Assertion constraint which will hit only few times. Constraint Mode
Probability of a random value to be in solution space is less than appearing it outside External Constraints
DPI Randomization
the solution space. To speed up ur solver, use the proper data types.
UVM Tutorial In the following example i showed the results of Questasim tool. Controlability
integer  is 32 bit datatype. Static Constraint
VMM Tutorial Constraint Expression
shortint is 16 bit datatype.
OVM Tutorial byte     is 8 bit datatype. Variable Ordering
Constraint Solver Speed
Easy Labs : SV
EXAMPLE: Randcase
Easy Labs : UVM program inte_p_62; Randsequence
  class inte; Random Stability
Easy Labs : OVM
    rand integer Var; Array Randomization
Easy Labs : VMM     constraint randge_c { Var inside {[0:10]};} Constraint Guards
AVM Switch TB   endclass Titbits
  inte obj=new();
VMM Ethernet sample   initial Report a Bug or Comment
  begin on This section - Your
    repeat(10000) input is what keeps
Verilog       void'(obj.randomize()); Testbench.in improving
    $finish(2); with time!
Verification
  end
Verilog Switch TB endprogram
Basic Constructs RESULT:

# ** Note: Data structure takes 3407960 bytes of memory


#          Process time 2.78 seconds
OpenVera
Constructs
Switch TB EXAMPLE:
program inte_p_62;
RVM Switch TB   class inte;
RVM Ethernet sample     rand bit [4:0] Var;
    constraint randge_c { Var inside {[0:10]};}
  endclass
  inte obj=new();
Specman E   initial
Interview Questions   begin
    repeat(10000)
      void'(obj.randomize());
    $finish(2);
  end
endprogram

RESULT:

# ** Note: Data structure takes 3407960 bytes of memory


#          Process time 1.95 seconds

http://testbench.in/CR_17_CONSTRAINT_SOLVER_SPEED.html[9/26/2012 2:12:27 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

To generate a random value which is one of the 2**0,2**1,2**2,......2**31.


If data type is integer and randomizing it will consume lot of simulation time.

constraint C { Var inside {2**0,2**1,2**2,......2**31};} 

Write a function to check only one bit is high.

constraint C { $countones(array) == 1 ;)
constraint C { Var == (1 << index) ;}

Instead declare an 5 bit variable index, randomize it and set the index bit to 1 in post
randomize.

EXAMPLE:
class expo_cons_64;
  rand bit [0:4] index;
  integer array;   // No need to randomize array
  function void post_randomize;
    array = 'b0;
    array[index]=1'b1;
  endfunction
endclass

Adding smaller constraints in to a single block, speeds up simulation for some


simulators. Check these examples with your simulator. Some Solver may need more
iterations to get the valid solution. Split the constraints as small as possible. With this
controllability on constraint blocks is also improved.

EXAMPLE:1
class constr;
  rand int a,b,c,d;
  constraint C { (a == 10)&&( b < 20 ) && (c > 30) && (d < 40) ;}
endclass

program constr_p_65;
  constr obj;
  initial
  begin
    obj=new();
    repeat(10000)
      void'(obj.randomize());
    $finish(2);
  end
endprogram
RESULT:

# ** Note: Data structure takes 3276888 bytes of memory

http://testbench.in/CR_17_CONSTRAINT_SOLVER_SPEED.html[9/26/2012 2:12:27 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

#          Process time 9.44 seconds

EXAMPLE:2
class constr;
  rand int a,b,c,d;
  constraint Ac {(a == 10);}
  constraint Bc {(b < 20) ;}
  constraint Cc {(c > 30) ;}
  constraint Dc {(d < 40) ;}
endclass

program constr_p_66;
  constr obj;
  initial
  begin
    obj=new();
    repeat(10000)
      void'(obj.randomize());
    $finish(2);
  end
endprogram
RESULT:

# ** Note: Data structure takes 3407960 bytes of memory


#          Process time 9.27 seconds

EXAMPLE:3
class constr_67;
  rand int a,b,c,d;
  constraint Ac { (a == 10) ; ( b < 20 ) ; (c > 30) ; (d < 40) ;}
endclass

program constr_p_67;
  constr_p_67 obj;
  initial
  begin
    obj=new();
    repeat(10000)
      void'(obj.randomize());
    $finish(2);
  end
endprogram
RESULT:

# ** Note: Data structure takes 3407960 bytes of memory


#          Process time 9.24 seconds

Run all the above three examples with your simulator and check how your simulation
speed varies.

When iterative constraints are used on arrays, each element has a constraint on it. If
the constraints are simple enough to implement with out using constraint block,
simulation time may be saved. In the following example, there are two constraints
blocks, one for size other for each element. In reality there may be more constraint
blocks.

EXAMPLE:
class Eth_pkt;
  rand byte Payload[] ;
  constraint size_c { Payload.size() inside {[46:1500]}; }
  constraint element_c { foreach ( Payload[ i ] )  Payload[ i ] inside {[50:100]}; }
endclass

program iterative_68;
  Eth_pkt obj;
  initial
  begin
    obj = new();
    for(int i=0;i< 10000;i++)
    begin
      if(obj.randomize())
        $display(" RANDOMIZATION DONE ");

http://testbench.in/CR_17_CONSTRAINT_SOLVER_SPEED.html[9/26/2012 2:12:27 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

    end
    $finish(2);
  end
endprogram
RESULT:

# ** Note: Data structure takes 3407960 bytes of memory


#          Process time 705.51 seconds

The above logic can implemented using post_randomize. Check how these two
example with ur vendor tool and look at the simulation speed. You may find
difference.

EXAMPLE:
class Eth_pkt;
  rand integer length;
  byte Payload[] ;
  constraint size_c { length inside {[46:1500]}; }
  function void post_randomize;
    Payload = new[length];
    for(int i=0;i< length;i++)
      Payload[ i ] = 50 + $urandom % 51 ;
  endfunction
endclass

program iterative_69;
  Eth_pkt obj;
  initial
  begin
    obj = new();
    for(int i=0;i< 10000;i++)
    begin
      if(obj.randomize())
        $display(" RANDOMIZATION DONE ");
      end
      $finish(2);
  end
endprogram

# ** Note: Data structure takes 3539032 bytes of memory


#          Process time 3.92 seconds

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CR_17_CONSTRAINT_SOLVER_SPEED.html[9/26/2012 2:12:27 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS RANDCASE Index


Constrained Random
SystemVerilog Verification
Verification randcase is a case statement that randomly selects one of its branches. The randcase Verilog Crv
item expressions are non-negative integral values that constitute the branch weights. Systemverilog Crv
Constructs An item weight divided by the sum of all weights gives the probability of taking that Randomizing Objects
Interface branch. Randcase can be used in class are modules. The randcase weights can be Random Variables
arbitrary expressions, not just constants. Randomization Methods
OOPS Checker
Randomization Constraint Block
EXAMPLE: Inline Constraint
Functional Coverage Global Constraint
randcase
Assertion 3 : x = 1; Constraint Mode
1 : x = 2; External Constraints
DPI Randomization
4 : x = 3;
UVM Tutorial endcase Controlability
Static Constraint
VMM Tutorial Constraint Expression
The sum of all weights is 8; therefore, the probability of taking the first branch is
OVM Tutorial 0.375, the probability of taking the second is 0.125, and the probability of taking the Variable Ordering
third is 0.5. If a branch specifies a zero weight, then that branch is not taken. The Constraint Solver Speed
Easy Labs : SV
sum of all weights (SUM) is computed (negative values contribute a zero weight). If Randcase
Easy Labs : UVM SUM is zero or exceeds (2*32-1), no branch is taken. Each call to randcae statement Randsequence
will return a random number in the range from 0 to SUM. $urandom_range(0,SUM) is Random Stability
Easy Labs : OVM
used to generate a random number. As the random numbers are generated using Array Randomization
Easy Labs : VMM $urandom are thread stable, randcase also exhibit random stability. Constraint Guards
AVM Switch TB Titbits

VMM Ethernet sample EXAMPLE: Report a Bug or Comment


module rand_case_70; on This section - Your
  integer x; input is what keeps
Verilog   integer cnt_1,cnt_2,cnt_3; Testbench.in improving
  initial with time!
Verification
  begin
Verilog Switch TB     cnt_1 = 0;cnt_2=0;cnt_3 = 0;    
Basic Constructs     repeat(100000)
    begin
      randcase
        3 : x = 1;
OpenVera         1 : x = 2;
Constructs         4 : x = 3;
Switch TB       endcase
      if(x == 1)
RVM Switch TB         cnt_1++;
RVM Ethernet sample       else if(x == 2)
        cnt_2++;
      else if(x ==3)
        cnt_3++;
Specman E     end
Interview Questions     $display("count_1 =%0d count_2 =%0d count_3 =%0d ",cnt_1,cnt_2,cnt_3);
    $display("Probability of count_1 =%0f count_2 =%0f count_3 =%0f
",(cnt_1/100000.0),(cnt_2/100000.0),(cnt_3/100000.0));
  end
endmodule

RESULTS:

# count_1 =37578 count_2 =12643 count_3 =49779


# Probability of count_1 =0.375780 count_2 =0.126430 count_3 =0.497790

http://testbench.in/CR_18_RANDCASE.html[9/26/2012 2:12:37 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CR_18_RANDCASE.html[9/26/2012 2:12:37 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS RANDSEQUENCE Index


Constrained Random
SystemVerilog Verification
Verification Verilog Crv
The random sequence generator is useful for randomly generating sequences of Systemverilog Crv
Constructs stimulus. For example, to verify a temporal scenario, a sequence of packets are Randomizing Objects
Interface needed. By randomizing a packet, it will generate most unlikely scenarios which are Random Variables
not interested. These type of sequence of scenarios can be generated using Randomization Methods
OOPS Checker
randsequence. A randsequence grammar is composed of one or more productions.
Randomization Production items are further classified into terminals and nonterminals. A terminal is Constraint Block
an indivisible item that needs no further definition than its associated code block. Inline Constraint
Functional Coverage Global Constraint
Assertion Constraint Mode
EXAMPLE: External Constraints
DPI Randomization
module rs();
UVM Tutorial   initial Controlability
  begin Static Constraint
VMM Tutorial Constraint Expression
    repeat(5)
OVM Tutorial     begin Variable Ordering
      randsequence( main ) Constraint Solver Speed
Easy Labs : SV
        main : one two three ; Randcase
Easy Labs : UVM         one  : {$write("one");}; Randsequence
        two  : {$write(" two");}; Random Stability
Easy Labs : OVM
        three: {$display(" three");}; Array Randomization
Easy Labs : VMM       endsequence Constraint Guards
AVM Switch TB     end Titbits
  end
VMM Ethernet sample endmodule Report a Bug or Comment
on This section - Your
RESULTS: input is what keeps
Verilog Testbench.in improving
one two three with time!
Verification
one two three
Verilog Switch TB one two three
Basic Constructs one two three
one two three

OpenVera
Constructs The production main is defined in terms of three nonterminals: one, two and three.
Switch TB Productions one,two and three are terminals. When the main is chosen, it will select
the sequence one, two and three in order.
RVM Switch TB
RVM Ethernet sample
Random Productions:

A single production can contain multiple production lists separated by the | symbol.
Specman E Production lists separated by a | imply a set of choices, which the generator will
Interview Questions make at random.

EXAMPLE:
module rs();
  initial
    repeat(8)
      randsequence( main )
        main : one | two | three ;
        one  : {$display("one");};
        two  : {$display("two");};

http://testbench.in/CR_19_RANDSEQUENCE.html[9/26/2012 2:12:47 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

        three: {$display("three");};
      endsequence
endmodule

RESULTS:

#  three
#  three
#  three
#  three
#  one
#  three
#  two
#  two

Results show that one, two and three are selected randomly.

Random Production Weights :

The probability that a production list is generated can be changed by assigning


weights to production lists. The probability that a particular production list is
generated is proportional to its specified weight. The := operator assigns the weight
specified by the weight_specification to its production list. A weight_specification
must evaluate to an integral non-negative value. A weight is only meaningful when
assigned to alternative productions, that is, production list separated by a |. Weight
expressions are evaluated when their enclosing production is selected, thus allowing
weights to change dynamically.

EXAMPLE:
module rs();
  integer one_1,two_2,three_3;
  initial
  begin
    one_1 = 0;
    two_2 = 0;
    three_3 = 0;
    repeat(6000)
      randsequence( main )
        main : one := 1| two := 2| three := 3;
        one  : {one_1++;}; 
        two  : {two_2++;};
        three: {three_3++;};
    endsequence
    $display(" one %0d two %0d three %0d",one_1,two_2,three_3);
  end
endmodule

http://testbench.in/CR_19_RANDSEQUENCE.html[9/26/2012 2:12:47 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

RESULTS:

#  one 1011 two 2005 three 2984

If..Else

A production can be made conditional by means of an if..else production statement.


The expression can be any expression that evaluates to a boolean value. If the
expression evaluates to true, the production following the expression is generated,
otherwise the production following the optional else statement is generated.

EXAMPLE:
module rs();
  integer one_1,two_2,three_3;
  reg on;
  initial
  begin
    on = 0;
    one_1 = 0;
    two_2 = 0;
    three_3 = 0;
    repeat(2500)
      randsequence( main )
        main : one  three;
        one  : {if(on) one_1++; else two_2 ++; };
        three: {three_3++;};
      endsequence
    $display(" one %0d two %0d three %0d",one_1,two_2,three_3);
  end
endmodule

RESULTS:

#  one 0 two 2500 three 2500

Case

A production can be selected from a set of alternatives using a case production


statement. The case expression is evaluated, and its value is compared against the
value of each case-item expression, which are evaluated and compared in the order in
which they are given. The production associated with the first case-item expression
that matches the case expression is generated. If no matching case-item expression is
found then the production associated with the optional default item is generated, or
nothing if there no default item. Case-item expressions separated by commas allow
multiple expressions to share the production.

EXAMPLE:
module rs();
  integer one_1,two_2,three_3;
  initial
  begin
    one_1 = 0;
    two_2 = 0;
    three_3 = 0;
    for(int i = 0 ;i < 6 ;i++) 
    begin
      randsequence( main )
        main : case(i%3)
               0  : one; 
               1  : two;
               default: def;
               endcase;
        one : {$display("one");};
        two : {$display("two");};
        def : {$display("default");};
      endsequence
    end
  end
endmodule

http://testbench.in/CR_19_RANDSEQUENCE.html[9/26/2012 2:12:47 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

RESULTS:

one
two
default
one
two
default

Repeat Production Statements :

The repeat production statement is used to iterate a production over a specified


number of times. The repeat production statement itself cannot be terminated
prematurely. A break statement will terminate the entire randsequence block

PUSH_OPER : repeat( $urandom_range( 2, 6 ) ) PUSH ;

Interleaving productions-rand join :

EXAMPLE:
    module rs();
    integer one_1,two_2,three_3;
    
    initial
    begin
       one_1 = 0;
       two_2 = 0;
       three_3 = 0;
       repeat(6000)
          randsequence( main )
              main : one | repeat(2) two | repeat (3) three ;
              one  : one_1++; 
              two  : two_2++;
              three: three_3++;
          endsequence
      
       $display(" one %d two %d three %d",one_1,two_2,three_3);
    end
    endmodule

RESULTS:

one 989 two 2101 three 2810

Rand Join

The rand join production control is used to randomly interleave two or more
production sequences while maintaining the relative order of each sequence.

EXAMPLE:
   module rs();
  
   initial
   for(int i = 0;i < 24;i++) begin
      randsequence( main )
         main : rand join S1 S2 ;
         S1 : A B ;
         S2 : C D ;
         A  : $write("A");
         B  : $write("B");
         C  : $write("C");
         D  : $write("D");
      endsequence
      if(i%4 == 3 )
         $display("");
      end
   endmodule

RESULTS:

ABCD

http://testbench.in/CR_19_RANDSEQUENCE.html[9/26/2012 2:12:47 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

A C BD
A C DB
C D AB
C A BD
C A DB

Note that B always comes after A and D comes after C. The optional expression
following the rand join keywords must be a real number in the range 0.0 to 1.0. The
value of this expression represents the degree to which the length of the sequences to
be interleaved affects the probability of selecting a sequence. A sequences length is
the number of productions not yet interleaved at a given time. If the expression is
0.0, the shortest sequences are given higher priority. If the expression is 1.0, the
longest sequences are given priority.

EXAMPLE:
    module rs();
    
       initial
       for(int i = 0;i < 24;i++) begin
          randsequence( main )
             main : rand join (0.0) S1 S2 ;
             S1 : A B ;
             S2 : C D ;
             A  : $write("A");
             B  : $write("B");
             C  : $write("C");
             D  : $write("D");
          endsequence
          if(i%4 == 3 )
             $display("");
       end
    endmodule

RESULTS:

A BCD
C DAB
A CBD
A CDB
C ABD
C ADB

EXAMPLE:
    module rs();
    
    initial
    for(int i = 0;i < 24;i++) begin
        randsequence( main )
           main : rand join (1.0) S1 S2 ;
           S1 : A B ;
           S2 : C D ;
           A  : $write("A");
           B  : $write("B");
           C  : $write("C");
           D  : $write("D");
        endsequence
        if(i%4 == 3 )
            $display("");
        end
    endmodule
    
RESULTS:

A CBD
A CDB
C ADB
C ADB
A BCD
C DAB
C ABD

http://testbench.in/CR_19_RANDSEQUENCE.html[9/26/2012 2:12:47 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

Break

The break statement terminates the sequence generation. When a break statement is
executed from within a production code block, it forces a jump out the randsequence
block.

EXAMPLE:
   randsequence()
      WRITE : SETUP DATA ;
      SETUP : { if( fifo_length >= max_length ) break; } COMMAND ;
      DATA : ...
   endsequence

When the example above executes the break statement within the SETUP production,
the COMMAND production is not generated, and execution continues on the line
labeled next_statement.

Return

The return statement aborts the generation of the current production. When a return
statement is executed from within a production code block, the current production is
aborted. Sequence generation continues with the next production following the
aborted production.

EXAMPLE:
   randsequence()
      TOP : P1 P2 ;
      P1 : A B C ;
      P2 : A { if( flag == 1 ) return; } B C ;
      A : { $display( A ); } ;
      B : { if( flag == 2 ) return; $display( B ); } ;
      C : { $display( C ); } ;
   endsequence

Depending on the value of variable flag, the example above displays the following:
flag == 0 ==> A B C A B C
flag == 1 ==> A B C A
flag == 2 ==> A C A C
When flag == 1, production P2 is aborted in the middle, after generating A. When flag
== 2, production B is aborted twice (once as part of P1 and once as part of P2), but
each time, generation continues with the next
production, C.

Value Passing Between Productions

Data can be passed down to a production about to be generated, and generated


productions can return data to the non-terminals that triggered their generation.
Passing data to a production is similar to a task call, and uses the same syntax.
Returning data from a production requires that a type be declared for the production,
which uses the same syntax as a variable declaration. Productions that accept data
include a formal argument list. The syntax for declaring the arguments to a
production is similar to a task prototype; the syntax for passing data to the
production is the same as a task call.

EXAMPLE:
    randsequence( main )
        main : first second gen ;
        first : add | dec ;
        second : pop | push ;
        add : gen("add") ;
        dec : gen("dec") ;
        pop : gen("pop") ;
        push : gen("push") ;
        gen( string s = "done" ) : { $display( s ); } ;
    endsequence

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/CR_19_RANDSEQUENCE.html[9/26/2012 2:12:47 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CR_19_RANDSEQUENCE.html[9/26/2012 2:12:47 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS RANDOM STABILITY Index


Constrained Random
SystemVerilog Verification
Verification In verilog,if the source code does not change,with the same seed,the simulator Verilog Crv
producess the same random stimulus on any mechine or any operating system.Verilog Systemverilog Crv
Constructs has only one Random number generator.Random stimulus is generated using Randomizing Objects
Interface $random(seed) where the seed is input to the RNG.$random will always return the Random Variables
same value for same seed. Randomization Methods
OOPS Checker
Randomization EXAMPLE: Constraint Block
    module seed_74(); Inline Constraint
Functional Coverage Global Constraint
       initial
Assertion        repeat(5) Constraint Mode
          $display("random stimuls is  %d",$random(Seed); External Constraints
DPI Randomization
    endmodule
UVM Tutorial Controlability
Static Constraint
VMM Tutorial Constraint Expression
While debugging to produce the same simulation, we should make sure that calls to
OVM Tutorial RNG is not disturbed. In Verilog if source code changes it is very unlikely that same Variable Ordering
stimulus is produced with the same seed and we miss the bug. Constraint Solver Speed
Easy Labs : SV
Randcase
Easy Labs : UVM In SystemVerilog seeding will be done hierachily. Every module instance, interface Randsequence
instance, program instance and package has initialization RNG. Every thread and Random Stability
Easy Labs : OVM
object has independent RNG . When ever dynamic thread is created its RNG is Array Randomization
Easy Labs : VMM initialized with the next random value from its parent thread. RNG initialization and Constraint Guards
AVM Switch TB RNG generation are different process.During RNG initialization,only seed is set to Titbits
RNG.  When ever static thread is created its RNG is initialized with the next random
VMM Ethernet sample value from the initialization RNG of module instance, interface instance, program Report a Bug or Comment
interface or package containing thread declaration. RNG initialization and RNG on This section - Your
generation are different process. During RNG initialization,only seed is set to RNG. input is what keeps
Verilog The random number generator is deterministic. Each time the program executes, it Testbench.in improving
cycles through the same random sequence. This sequence can be made with time!
Verification
nondeterministic by seeding the $urandom function with an extrinsic random variable,
Verilog Switch TB such as the time of day.
Basic Constructs
SystemVerilog system functions $urandom and $urandom_range are thread stable.
Calls to RNG using these system function, uses the RNG of that thread. So next time
while using $random in SystemVerilog,think twice.  
OpenVera     
Constructs NOTE: The same stimulus sequence can not be produced on different simulators as
Switch TB the LRM does not restrict the vendors to impliment specific constraint solver. Verilog
LRM specifies the RNG algorithm for $random ,so the same stimulas can be produced
RVM Switch TB on different simulators(not always as I discussed in one of the above topic). Even if
RVM Ethernet sample the SystemVerilog LRM specifies RNG algorithm ,the same sequence cannot be
produced on different vendors because of the following are few reasons :
-> LRM doesnot restrict the constraint solver algorithm.
-> Order of threads creation.
Specman E -> Order of thread execution.
Interview Questions
      
EXAMPLE:
class Ran_Stb_1;
  rand bit [2:0] Var;
endclass

program Ran_Stb_p_75;
  Ran_Stb_1 obj_1 = new();
  initial
    repeat(10)

http://testbench.in/CR_20_RANDOM_STABILITY.html[9/26/2012 2:12:56 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

    begin
      void'(obj_1.randomize());
        $display(" Ran_Stb_1.Var : %0d  ",obj_1.Var);
  end
endprogram

RESULTS:

#  Ran_Stb_1.Var : 4  
#  Ran_Stb_1.Var : 5  
#  Ran_Stb_1.Var : 1  
#  Ran_Stb_1.Var : 1  
#  Ran_Stb_1.Var : 0  
#  Ran_Stb_1.Var : 2  
#  Ran_Stb_1.Var : 2  
#  Ran_Stb_1.Var : 7  
#  Ran_Stb_1.Var : 6  
#  Ran_Stb_1.Var : 0  

Stimulus generated in a thread or object is independed of other stimulus. So changes


in the source code will not effect threads or objects. This is Valid as long as the order
of the threads is not distrubed. If a new object is created, make sure that that they
are added at the end.

EXAMPLE:
class Ran_Stb_1;
  rand bit [2:0] Var;
endclass  

class Ran_Stb_2;
  rand bit [2:0] Var;
endclass
                                                                                                                          
program Ran_Stb_p_76;
  Ran_Stb_1 obj_1 = new();
  Ran_Stb_2 obj_2 = new();
  initial
    repeat(10)
    begin
      void'(obj_1.randomize());
        $display(" Ran_Stb_1.Var : %0d  ",obj_1.Var);
    end
endprogram

New object obj_2 is added after all the objects. Look at the simulation results,they
are same as the above.

RESULTS:

http://testbench.in/CR_20_RANDOM_STABILITY.html[9/26/2012 2:12:56 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

#  Ran_Stb_1.Var : 4  
#  Ran_Stb_1.Var : 5  
#  Ran_Stb_1.Var : 1  
#  Ran_Stb_1.Var : 1  
#  Ran_Stb_1.Var : 0  
#  Ran_Stb_1.Var : 2  
#  Ran_Stb_1.Var : 2  
#  Ran_Stb_1.Var : 7  
#  Ran_Stb_1.Var : 6  
#  Ran_Stb_1.Var : 0  

If a new thread is added, make sure that it is added after all the threads.

EXAMPLE:
class Ran_Stb_1;
  rand bit [2:0] Var;
endclass

class Ran_Stb_2;
  rand bit [2:0] Var;
endclass

program Ran_Stb_p_77;
  Ran_Stb_1 obj_1 = new();
  Ran_Stb_2 obj_2 = new();
  initial
  begin
    repeat(5)
    begin
      void'(obj_1.randomize());
      $display(" Ran_Stb_1.Var : %0d ",obj_1.Var);
    end
    repeat(5)
    begin
      void'(obj_2.randomize());
      $display(" Ran_Stb_2.Var : %0d ",obj_2.Var);
    end
  end
endprogram

The results show clearly that Random values in obj_1 are same as previous program
simulation.

RESULTS:

#  Ran_Stb_1.Var : 4
#  Ran_Stb_1.Var : 5
#  Ran_Stb_1.Var : 1
#  Ran_Stb_1.Var : 1
#  Ran_Stb_1.Var : 0
#  Ran_Stb_2.Var : 3
#  Ran_Stb_2.Var : 3
#  Ran_Stb_2.Var : 6
#  Ran_Stb_2.Var : 1
#  Ran_Stb_2.Var : 1

Order of the randomize call to different objects doesnot effect the RNG generation.

EXAMPLE:
class Ran_Stb_1;
  rand bit [2:0] Var;
endclass

class Ran_Stb_2;
  rand bit [2:0] Var;
endclass

program Ran_Stb_p_78;
  Ran_Stb_1 obj_1 = new();
  Ran_Stb_2 obj_2 = new();

http://testbench.in/CR_20_RANDOM_STABILITY.html[9/26/2012 2:12:56 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

  initial
  begin
    repeat(5)
    begin
      void'(obj_2.randomize());
      $display(" Ran_Stb_2.Var : %0d ",obj_2.Var);
    end
    repeat(5)
    begin
      void'(obj_1.randomize());
      $display(" Ran_Stb_1.Var : %0d ",obj_1.Var);
    end
  end
endprogram

RESULTS:

#  Ran_Stb_2.Var : 3
#  Ran_Stb_2.Var : 3
#  Ran_Stb_2.Var : 6
#  Ran_Stb_2.Var : 1
#  Ran_Stb_2.Var : 1
#  Ran_Stb_1.Var : 4
#  Ran_Stb_1.Var : 5
#  Ran_Stb_1.Var : 1
#  Ran_Stb_1.Var : 1
#  Ran_Stb_1.Var : 0

Adding a constraint in one class, will only effect the stimuls of that object only.

EXAMPLE:
class Ran_Stb_1;
  rand bit [2:0] Var;
  constraint C { Var < 4 ;}
endclass

class Ran_Stb_2;
  rand bit [2:0] Var;
endclass

program Ran_Stb_p_79;
  Ran_Stb_1 obj_1 = new();
  Ran_Stb_2 obj_2 = new();
  initial
    repeat(5)
    begin
      void'(obj_1.randomize());
      void'(obj_2.randomize());
      $display(" Ran_Stb_1.Var : %0d :: Ran_Stb_2.Var : %0d ",obj_1.Var,obj_2.Var);
    end
endprogram

RESULTS:

#  Ran_Stb_1.Var : 0 :: Ran_Stb_2.Var : 3
#  Ran_Stb_1.Var : 1 :: Ran_Stb_2.Var : 3
#  Ran_Stb_1.Var : 1 :: Ran_Stb_2.Var : 6
#  Ran_Stb_1.Var : 1 :: Ran_Stb_2.Var : 1
#  Ran_Stb_1.Var : 0 :: Ran_Stb_2.Var : 1

Srandom

When an object or thread is created, its RNG is seeded using the next value from the
RNG of the thread that creates the object. This process is called hierarchical object
seeding. Sometimes it is desirable to manually seed an objects RNG using the
srandom() method. This can be done either in a class method or external to the class
definition. Example to demonstrate seeding in objects.

EXAMPLE:
class Rand_seed;
 rand integer Var;
 function new (int seed);

http://testbench.in/CR_20_RANDOM_STABILITY.html[9/26/2012 2:12:56 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

   srandom(seed);
   $display(" SEED is initised to %0d ",seed);
 endfunction

 function void post_randomize();
   $display(": %0d :",Var);
 endfunction
endclass

program Rand_seed_p_80;
  Rand_seed rs;
  initial
  begin
    rs = new(20);
    repeat(5)
      void'(rs.randomize());
    rs = new(1);
    repeat(5)
      void'(rs.randomize());
    rs = new(20);
    repeat(5)
      void'(rs.randomize());
  end
endprogram

RESULTS:

#  SEED is initised to 20
# : 1238041889 :
# : 1426811443 :
# : 220507023 :
# : -388868248 :
# : -1494908082 :
#  SEED is initised to 1
# : 1910312675 :
# : 632781593 :
# : -453486143 :
# : 671009059 :
# : -967095385 :
#  SEED is initised to 20
# : 1238041889 :
# : 1426811443 :
# : 220507023 :
# : -388868248 :
# : -1494908082 :

Simulation results show that same sequence is repeated when the same seed is used
for initialization.

Example to demonstrate seeding a thread.

EXAMPLE:
integer x, y, z;
fork //set a seed at the start of a thread
begin process::self.srandom(100); x = $urandom; end
//set a seed during a thread
begin y = $urandom; process::self.srandom(200); end
// draw 2 values from the thread RNG
begin z = $urandom + $urandom ; end
join

The above program fragment illustrates several properties:


Thread locality: The values returned for x, y, and z are independent of the order of
thread execution. This is an important property because it allows development of
subsystems that are independent, controllable, and predictable.
Hierarchical seeding: When a thread is created, its random state is initialized using
the next random value from the parent thread as a seed. The three forked threads are
all seeded from the parent thread.

http://testbench.in/CR_20_RANDOM_STABILITY.html[9/26/2012 2:12:56 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

IEEE 2005 SystemVerilog LRM does not specify whether scope randomization function
is random stable or not.

From LRM
13.13 Random stability
The RNG is localized to threads and objects. Because the sequence of random values
returned by a thread or object is independent of the RNG in other threads or objects,
this property is called random stability.

Random stability applies to the following:

The system randomization calls, $urandom() and $urandom_range()


The object and process random seeding method, srandom()
The object randomization method, randomize()

In above its mentioned that "object randomization method, randomize()". There is


nothing mentioned about std::randomize() method random stability.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CR_20_RANDOM_STABILITY.html[9/26/2012 2:12:56 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS ARRAY RANDOMIZATION Index


Constrained Random
SystemVerilog Verification
Verification Most application require to randomize elememts of array.Arrays are used to model Verilog Crv
payload,port connections etc. Systemverilog Crv
Constructs SystemVerilog has Fixed Arrays,Dynamic arrays,queues and Associative arrays. Randomizing Objects
Interface If an array is constrained by both size constraints and iterative constraints for Random Variables
constraining every element of array. The size constraints are solved first, and the Randomization Methods
OOPS Checker
iterative constraints next. In the example,size_c is solved first before element_c. As
Randomization constraint element_c canot be solved without knowing the size. So there is implicit Constraint Block
ordering while solveing this type of constraints. Inline Constraint
Functional Coverage Global Constraint
This is the only approach for applying constraints to individual elements of arrays,
Assertion with this approach,performance is degraded. If  Payload.size() = 1000, then 1000 Constraint Mode
constraints are created by foreach. it takes much time for the solver to solve all the External Constraints
DPI Randomization
constraints. Another simple approach is using a task to randomize each element. This
UVM Tutorial approach is 5X times faster than foreach. Controlability
Static Constraint
VMM Tutorial Constraint Expression
OVM Tutorial EXAMPLE: Variable Ordering
class Eth_pkt_82; Constraint Solver Speed
Easy Labs : SV
  rand byte Payload[] ; Randcase
Easy Labs : UVM   constraint size_c { Payload.size() inside {[46:1500]}; } Randsequence
  task randomize_foreach; Random Stability
Easy Labs : OVM
    foreach ( Payload[ i ] )  Array Randomization
Easy Labs : VMM     Payload[ i ] = 50 + $urandom % 50;// try with randomize( Payload[i]) with ..... Constraint Guards
AVM Switch TB   endtask Titbits
endclass
VMM Ethernet sample Report a Bug or Comment
program iterative; on This section - Your
  Eth_pkt_82 obj; input is what keeps
Verilog   initial Testbench.in improving
  begin with time!
Verification
    obj = new();
Verilog Switch TB     for(int i=0;i< 10000;i++)
Basic Constructs     begin
      void'(obj.randomize());
        obj.randomize_foreach();
    end
OpenVera   end
Constructs endprogram
Switch TB
RVM Switch TB In applications where some constraints are dependent on the array elements, the
RVM Ethernet sample following may help. call the randomization function in constraints, define proper
variable ordering.

EXAMPLE:
Specman E    class Eth_pkt;
Interview Questions        rand byte Payload[] ;
       rand byte size;
       bit dummy = 1;
      
       constraint dummy_c { dummy == randomize_size();}
       constraint size_c { size inside {[10:100]};}
       constraint order_c1 {solve size before dummy;}
       constraint order_c2 {solve dummy before Payload;}
      
       function bit randomize_size();
           Payload = new[size];

http://testbench.in/CR_21_ARRAY_RANDOMIZATION.html[9/26/2012 2:13:07 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

           randomize_size = 1;


           return randomize_size;
       endfunction
      
   endclass
  
   program iterative_88;
       Eth_pkt obj;
      
      initial
      begin
         obj = new();
         void'(obj.randomize());
         for(int i=0;i< 10;i++)
            begin
            void'(obj.randomize());
            $display(" Eth_pkt.size : %d  :: Payload.size() : %d
",obj.size,obj.Payload.size());
            for(int j=0;j<obj.Payload.size();j++)
            $write("%4d _",obj.Payload[j]);
            $display("");
         end
      end
   endprogram

In the above example, constraint order_c1 {solve size before dummy;} makes sure
that size is randomized before function ranomize_size() is called.

If constraints are dependent on the sum of the elements of the dynamic array. The
interesting elements are the new random variables which are created by current
randomization call. If you are not using any techinique to get the right size after
randomization sum() returns the sum of all the array elements .

EXAMPLE:
class dynamic_array_89;
   rand byte size;
   rand byte data[];
   constraint size_c { data.size() == size; size >= 0; }
   constraint sum_c  { data.sum()  < 1000;}
endclass

Do manually in a function and use it or just use { data.sum() with (item.index < size)
1000;}There is one more bug in the above code.The sum() method  returns a single
value of the same type as the array element type.So the sum returns only 8 bits in
this case.So a.sum() is allways less than 255 which is less than 1000 and allways the
constraint is satisfied which is not what is expected.

http://testbench.in/CR_21_ARRAY_RANDOMIZATION.html[9/26/2012 2:13:07 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

EXAMPLE:
program summ;
   dynamic_array obj = new();
   integer sum;

   initial
   begin
      sum =0;
      void'(obj.randomize());
      for(int i=0;i< obj.size ;i++)
         sum= sum+obj.data[i];
      $display(" Sum is %d ",sum);
   end
endprogram
 

Using y.sum with (item + 32'b0) will result in a 32 bit proper sum.

EXAMPLE:
class dynamic_array;
   rand integer size;
   rand reg [7:0] data[];
   constraint sum_c  { data.sum() == data[0];}
   constraint size_c { data.size() == size; size >1000 ;size < 2000; }

endclass

program summ;
   dynamic_array obj = new();
   integer sum;
   initial
   repeat(10)
      begin
      sum =0;
      void'(obj.randomize());
      for(int i=0;i< obj.size ;i++)
      begin
         sum= sum+obj.data[i];
      end
      $display(" Sum is %d obj.sum() %d",obj.data[0],obj.data.sum());
   end
endprogram

Randomization donot create the objects. So when a array of objects is randomized,


all the objects are pointing to null and randomization can not be done on null
objets.new() has to be called to creat objects then only randomize can be done on
it.So creat array of objects before calling the randomize.

EXAMPLE:
  class cls;
    rand integer Var;
  endclass
  
  class arr_obj;
     rand cls objcls [0:2];
  endclass
  
  program arr_obj_p_91;
     arr_obj obj = new() ;
     int i;
     initial
     begin
        if(obj.randomize())
        begin
           $display(" Randomization is done ");
           for(i=0;i<3;i++)
             if(obj.objcls[i] == null )
                $display( " obj.objcls == null ");
             else
                $display(" obj.objcls.Var : %d ", obj.objcls[i].Var );
        end
        else
        $display(" Randomization failed ");

http://testbench.in/CR_21_ARRAY_RANDOMIZATION.html[9/26/2012 2:13:07 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

     end
  endprogram
RESULTS:

  #  Randomization is done
  #  obj.objcls == null
  #  obj.objcls == null
  #  obj.objcls == null

  

In the following, objects are created during the creation of arr_obj. This can also be
done in pre_randomize. When dynamic arrays of objects are created, similar approach
has to be taken and size of the dynamic array has to be decided before the new() is
called, which makes no sense using the dynamic array of objects.

EXAMPLE:
   class cls;
      rand integer Var; 
   endclass
  
   class arr_obj; 
      rand cls objcls [0:2];
  
      function new();
         foreach(objcls[i])
         objcls[i]=new();
      endfunction
      
   endclass
  
   program arr_obj_p_91;
       arr_obj obj = new() ;
       int i;
       initial
           begin
           if(obj.randomize())
           begin
               $display(" Randomization is done ");
               for(i=0;i<3;i++)
                  if(obj.objcls[i] == null )
                     $display( " obj.objcls == null ");
                  else
                     $display(" obj.objcls.Var : %d ", obj.objcls[i].Var );
           end 
           else
              $display(" Randomization failed ");
       end
   endprogram
RESULTS:

  Randomization is done
  obj.objcls.Var :   733126180
  obj.objcls.Var :  -119008195
  obj.objcls.Var :   342785185

To create queue of objects,first length of the queue has to be randomized.Then


number of objects equal to length of queue.Delete the old elements in the
queue.Then push each object new objects in to the queue.Lastly randomize each
object.

EXAMPLE:
   class cls;
      rand integer Var;
   endclass
  
   class q_cls;
      rand cls obj[$];

http://testbench.in/CR_21_ARRAY_RANDOMIZATION.html[9/26/2012 2:13:07 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

      rand bit [2:0] length;
 
      function void pre_randomize();
         length = $urandom % 20 ;    // Compute the length of queue.
         obj     = {} ;               // Delet all the elements in the queue or .delet can be
used
         repeat(length)
         begin
            cls obj_loc;
            obj_loc = new();           // Creat new object.      
            obj.Push_back(obj_loc) ;   // insert it into queue.
         end
      endfunction
    endclass
 
   program q_obj_p_93;
   q_cls obj = new();
  
   initial
   begin
      if(obj.randomize())
      begin
         $display( "Randomization done");
         $write( " Length of q : %0d :::",obj.length);
         for(int i ;i< obj.length;i++)
         begin
             cls obj_temp;
             obj_temp = obj.obj.Pop_front();
             $write(" : %0d : ",obj_temp.Var);
         end
      end
      else
         $display( "Randomization failed");
   end
   endprogram
RESULT:

Randomization done
 Length of q : 6 ::: : 1474208060 :  : -1098913923 :  : 816460770 :  : 41501707 :  : -
1179418145 :  : -212817600 :

Some application like linked list needs to generate an array of random values which
are unique. foreach provides the solution,but the simples and the best solution is
assign all the elements in arrat with its index and use shuffel inside a task.shuffle()
randomizes the order of the elements in the array.Constraint solver is not used
hear,so the preformance is better.

EXAMPLE:
    class List;
       integer Pointer[5] ;
  
       task randomize_unique;
          foreach ( Pointer[ i ] ) 
             Pointer[ i ] = i;
          Pointer.shuffle();
       endtask
    endclass
    
    program Unique_rand_94;
     List obj;
    
    initial
    begin
       obj = new();
       obj.randomize_unique();
       for(int i=0;i< 5;i++)
       begin
          $display(" Pointer[%0d] = %d ",i,obj.Pointer[i]);
       end
    end
    endprogram

http://testbench.in/CR_21_ARRAY_RANDOMIZATION.html[9/26/2012 2:13:07 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

RESULT:

 Pointer[0] =           2
 Pointer[1] =           1
 Pointer[2] =           3
 Pointer[3] =           0
 Pointer[4] =           4

Using foreach in global constraints in the following way wont work currently. as the .
operator(dot) is not supported in foreach in LRM currently.

EXAMPLE:
class parent;
   rand byte a[0:9];
endclass

class child_96;
   rand parent P;
   rand byte a[0:9];
   constraint Not_supported { foreach(P.a[i]) P.a[i] == a[i];}
endclass

The correct way to write the above constraint is


constraint Supported { foreach(a[i]) a[i] == P.a[i];}

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CR_21_ARRAY_RANDOMIZATION.html[9/26/2012 2:13:07 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS CONSTRAINT GUARDS Index


Constrained Random
SystemVerilog Verification
Verification Constraint guards are predicate expressions that function as guards against the Verilog Crv
creation of constraints, and not as logical relations to be satisfied by the solver. Systemverilog Crv
Constructs These predicate expressions &&,|| and ! are evaluated before the constraints are Randomizing Objects
Interface solved. This enables users to write constraints that avoid errors due to nonexistent Random Variables
object handles or array indices out of bounds. Randomization Methods
OOPS Checker
Randomization There are 4 states when a  sub expression is evlauated. Constraint Block
0 FALSE Subexpression evaluates to FALSE. Inline Constraint
Functional Coverage Global Constraint
1 TRUE Subexpression evaluates to TRUE. Constraint Mode
Assertion
E ERROR Subexpression causes an evaluation error like null pointer. External Constraints
DPI R RANDOM Expression includes random variables and cannot be evaluated. Randomization
UVM Tutorial Controlability
If any of subexpression results ERROR,then randomization fails. Static Constraint
VMM Tutorial Constraint Expression
OVM Tutorial Variable Ordering
EXAMPLE:1 Constraint Solver Speed
Easy Labs : SV class SList_97; Randcase
Easy Labs : UVM   rand int n; Randsequence
  rand Slist_97 next; Random Stability
Easy Labs : OVM   constraint sort { n < next.n; } Array Randomization
Easy Labs : VMM endclass Constraint Guards
AVM Switch TB Titbits

VMM Ethernet sample In the Example 1, while sorting the elements of array in ascending order, if next is Report a Bug or Comment
null i.e for last element randomization fails. on This section - Your
input is what keeps
Verilog Testbench.in improving
EXAMPLE:2 with time!
Verification class SList_98;
Verilog Switch TB   rand int n;
  rand Slist_98 next;
Basic Constructs   constraint sort { if( next != null ) n < next.n; }
endclass

OpenVera
Constructs In Example 2, Even if next is null, constraint wont be generated so randomization will
never fail.
Switch TB
RVM Switch TB
EXAMPLE:3
RVM Ethernet sample class D;
  int x;
endclass
Specman E class C;
  rand int x, y;
Interview Questions   D a, b;
  constraint c1 { (x < y || a.x > b.x || a.x == 5 ) -> x+y == 10; }
endclass

In Example 3, the predicate subexpressions are (x < y), (a.x > b.x), and (a.x == 5),
which are all
connected by disjunction. Some possible cases are as follows:

Case 1: a is non-null, b is null, a.x is 5.


Because (a.x==5) is true, the fact that b.x generates an error does not result in an

http://testbench.in/CR_22_CONSTRAINT_GUARDS.html[9/26/2012 2:13:28 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

error.
The unconditional constraint (x+y == 10) is generated.

Case 2: a is null.
This always results in error, irrespective of the other conditions.

Case 3: a is non-null, b is non-null, a.x is 10, b.x is 20.


All the guard subexpressions evaluate to FALSE.
The conditional constraint (x<y) -> (x+y == 10) is generated.

EXAMPLE:4
class D;
  int x;
endclass
class C;
  rand int x, y;
  D a, b;
  constraint c1 { (x < y && a.x > b.x && a.x == 5 ) -> x+y == 10; }
endclass

In Example 4, the predicate subexpressions are (x < y), (a.x > b.x), and (a.x == 5),
which are all
connected by conjunction. Some possible cases are as follows:

Case 1: a is non-null, b is null, a.x is 6.


Because (a.x==5) is false, the fact that b.x generates an error does not result in an
error.
The constraint is eliminated.

Case 2: a is null
This always results in error, irrespective of the other conditions.

Case 3: a is non-null, b is non-null, a.x is 5, b.x is 2.


All the guard subexpressions evaluate to TRUE, producing constraint (x<y) -> (x+y ==
10).

EXAMPLE:5
class D;
  int x;
endclass
class C;
  rand int x, y;
  D a, b;
  constraint c1 { (x < y && (a.x > b.x || a.x ==5)) -> x+y == 10; }
endclass

http://testbench.in/CR_22_CONSTRAINT_GUARDS.html[9/26/2012 2:13:28 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

In Example 5, the predicate subexpressions are (x < y) and (a.x > b.x || a.x == 5),
which are connected
by disjunction. Some possible cases are as follows:

Case 1: a is non-null, b is null, a.x is 5.


The guard expression evaluates to (ERROR || a.x==5), which evaluat es to (ERROR ||
TRUE)
The guard subexpression evaluates to TRUE.
The conditional constraint (x<y) -> (x+y == 10) is generated.

Case 2: a is non-null, b is null, a.x is 8.


The guard expression evaluates to (ERROR || FALSE) and generates an error.

Case 3: a is null
This always results in error, irrespective of the other conditions.

Case 4: a is non-null, b is non-null, a.x is 5, b.x is 2.


All the guard subexpressions evaluate to TRUE.
The conditional constraint (x<y) -> (x+y == 10) is generated.

EXAMPLE:6

class A_108;
  rand integer arr[];
  constraint c { foreach( arr[i]) arr[i] == arr[i+1] ;}
endclass 

In Example 6, generates an error when i is the last element in the array.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CR_22_CONSTRAINT_GUARDS.html[9/26/2012 2:13:28 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS TITBITS Index


Constrained Random
SystemVerilog Verification
Verification The first constraint program which wrote randomized sucessfully but the results are Verilog Crv
not what expected. Systemverilog Crv
Constructs My constraint is to limit Var between 0 and 100. Randomizing Objects
Interface Random Variables
EXAMPLE: Randomization Methods
OOPS Checker
class Base;
Randomization   rand integer Var; Constraint Block
   constraint randge { 0< Var < 100 ;} Inline Constraint
Functional Coverage Global Constraint
endclass
Assertion Constraint Mode
program inhe_109; External Constraints
DPI Randomization
   Base obj;
UVM Tutorial    Controlability
   initial Static Constraint
VMM Tutorial Constraint Expression
   begin
OVM Tutorial       obj = new(); Variable Ordering
      for(int i=0 ; i < 100 ; i++) Constraint Solver Speed
Easy Labs : SV
         if(obj.randomize()) Randcase
Easy Labs : UVM             $display(" Randomization successful : Var = %0d ",obj.Var); Randsequence
         else Random Stability
Easy Labs : OVM
            $display("Randomization failed"); Array Randomization
Easy Labs : VMM    end Constraint Guards
AVM Switch TB endprogram Titbits

VMM Ethernet sample RESULTS: Report a Bug or Comment


on This section - Your
 Randomization successful : Var = 2026924861 input is what keeps
Verilog  Randomization successful : Var = -1198182564 Testbench.in improving
 Randomization successful : Var = 1119963834 with time!
Verification
 Randomization successful : Var = -21424360
Verilog Switch TB  Randomization successful : Var = -358373705
Basic Constructs  Randomization successful : Var = -345517999
 Randomization successful : Var = -1435493197
..etc
OpenVera
Constructs The mistake what I have done is simple,this resulted the constraint solver to solve the
Switch TB statement
(((0 < Var) < 100))
RVM Switch TB For the above equation, are the results are correct.
RVM Ethernet sample Then I changed the constraint to { 0< Var ;Var < 100 ;}
The solver considered the this constraint as (0 < Var) && (Var < 100); and solution are
correct.
Specman E To generate random values less then -10,the following may not work.
Interview Questions
EXAMPLE:
class Base_110;
   rand integer Var;
   constraint randge { Var + 10 <=  0 ;}
endclass

RESULTS:

 Randomization sucsessfull : Var = -1601810394


 Randomization sucsessfull : Var = 2147483646

http://testbench.in/CR_23_TITBITS.html[9/26/2012 2:13:37 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

 Randomization sucsessfull : Var = -335544322

Var = 2147483646 is not less -10, but the solver solved it using ((Var + 10) <= 0) i.e
((2147483646 + 10) <= 0) which is true
To solve this use the inside operator.
constraint randge { Var inside {[-10000:-10]};}
Make sure that constraint expression are not mixed up with signed and unsigned
variables.

#  Ran_Stb_1.Var : 4  
#  Ran_Stb_1.Var : 5  
#  Ran_Stb_1.Var : 1  
#  Ran_Stb_1.Var : 1  
#  Ran_Stb_1.Var : 0  
#  Ran_Stb_1.Var : 2  
#  Ran_Stb_1.Var : 2  
#  Ran_Stb_1.Var : 7  
#  Ran_Stb_1.Var : 6  
#  Ran_Stb_1.Var : 0  
Constraining Non Integral Data Types:

Constraints can be any SystemVerilog expression with variables and constants of


integral type (e.g.,
bit, reg, logic, integer, enum, packed struct).
To Constraint a real number, randomize integer and convert it to real as it is
required.

EXAMPLE:
class cls;
   rand integer Var;
endclass

class real_c;
   real r;
   rand integer i;
   rand integer j;
  
   function void post_randomize;
       r = $bitstoreal({i,j});
       $display("%e ",r);
   endfunction
  
endclass

program real_p_111;
   real_c obj = new();
   initial
      repeat(5)
         void'(obj.randomize());
endprogram

http://testbench.in/CR_23_TITBITS.html[9/26/2012 2:13:37 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

RESULT:

2.507685e-280
-1.188526e-07
9.658227e-297
-2.912335e+247
2.689449e+219

Saving Memory

In packet protocol application like PCI Express, the packets which are driven to the
DUV has to be manipulated and stored to compare with the actual packet which is
coming from DUV. If the packet size is large and number of packets are huge, it
occupies more momery. In verilog in this case the whole packet need to be stored.
HVL has more advantages w.r.t this case. We can store high level information like
packet size, CRC error, header. But functional verification needs to store the payload
for checking that the payload did not get corrupted. Major part of the storage taken
by the payload itself. If we can avoid storing the payload, we can save lot of storage
space.
The following technique assigns predictable random values to payload fields. Only the
start of the payload need to be stored.

EXAMPLE:
integer pkt_length;
byte payload[0:MAX];

task gen_payload(integer seed ,integer length);
integer temp_seed;
temp_seed = seed;
for(int i=0;i< length;i++)
begin
temp_seed = $random(temp_seed);
payload[i] = temp_seed;          
end
endtask

This is the task which checks whether payload is recived didnot get corrupted.

EXAMPLE:
task check_payload(integer seed,integer length);
integer temp_seed;
temp_seed = seed;
for(int i=0;i< length;i++)
begin
temp_seed = $random(temp_seed);
if(payload[i] != temp_seed)          
$display(" ERROR :: DATA MISMATCH ");
end
endtask

                

http://testbench.in/CR_23_TITBITS.html[9/26/2012 2:13:37 PM]


WWW.TESTBENCH.IN - Systemverilog Randomization

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CR_23_TITBITS.html[9/26/2012 2:13:37 PM]


WWW.TESTBENCH.IN - SystemVerilog Functional Coverage

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INTRODUCTION Index


Introduction
SystemVerilog Cover Group
Verification Systemverilog Functional Coverage Features Sample
Cover Points
Constructs Coverpoint Expression
Coverage of variables and expressions
Interface Generic Coverage Groups
Cross coverage Coverage Bins
OOPS Automatic and user-defined coverage bins Explicit Bin Creation
  -- Values, transitions, or cross products Transition Bins
Randomization
Filtering conditions at multiple levels Wildcard Bins
Functional Coverage Flexible coverage sampling Ignore Bins
Assertion   -- Events, Sequences, Procedural Illegal Bins
Directives to control and query coverage Cross Coverage
DPI Coverage Options
UVM Tutorial Coverage Methods
System Tasks
VMM Tutorial Cover Property
OVM Tutorial
Report a Bug or Comment
Easy Labs : SV
on This section - Your
Easy Labs : UVM input is what keeps
Easy Labs : OVM Testbench.in improving
with time!
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

Verilog
Verification
Verilog Switch TB
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/CO_01_INTRODUCTION.html[9/26/2012 2:13:44 PM]


WWW.TESTBENCH.IN - SystemVerilog Functional Coverage

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CO_01_INTRODUCTION.html[9/26/2012 2:13:44 PM]


WWW.TESTBENCH.IN - SystemVerilog Functional Coverage

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS COVER GROUP Index


Introduction
SystemVerilog Cover Group
Verification The covergroup construct encapsulates the specification of a coverage model. Each Sample
covergroup specification can include the following components: Cover Points
Constructs Coverpoint Expression
Interface A clocking event that synchronizes the sampling of coverage points Generic Coverage Groups
A set of coverage points Coverage Bins
OOPS Explicit Bin Creation
Cross coverage between coverage points Transition Bins
Randomization Optional formal arguments Wildcard Bins
Functional Coverage Coverage options Ignore Bins
Assertion Illegal Bins
Cross Coverage
DPI A Cover group is defined between key words covergroup &  endgroup. Coverage Options
UVM Tutorial A Covergroup Instance can be created using the new() operator. Coverage Methods
System Tasks
VMM Tutorial    covergroup cg; Cover Property
OVM Tutorial      ...
     ... Report a Bug or Comment
Easy Labs : SV      ... on This section - Your
Easy Labs : UVM    endgroup input is what keeps
   Testbench.in improving
Easy Labs : OVM    cg cg_inst = new; with time!
Easy Labs : VMM
AVM Switch TB The above example defines a covergroup named "cg". An instance of "cg" is declared
VMM Ethernet sample as "cg_inst" and created using the "new" operator.

Verilog
Verification
Verilog Switch TB
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/CO_02_COVER_GROUP.html[9/26/2012 2:13:52 PM]


WWW.TESTBENCH.IN - SystemVerilog Functional Coverage

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CO_02_COVER_GROUP.html[9/26/2012 2:13:52 PM]


WWW.TESTBENCH.IN - SystemVerilog Functional Coverage

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS SAMPLE Index


Introduction
SystemVerilog Coverage should be triggered to sample the coverage values. Sampling can be done Cover Group
Verification using Sample
Cover Points
Constructs Coverpoint Expression
Any event expression -edge, variable
Interface Generic Coverage Groups
End-point of a sequence Coverage Bins
OOPS Event can be omitted Explicit Bin Creation
Randomization
Calling sample() method. Transition Bins
Wildcard Bins
Functional Coverage Ignore Bins
Assertion   covergroup cg @(posedge clk); Illegal Bins
    ... Cross Coverage
DPI     ... Coverage Options
UVM Tutorial     ... Coverage Methods
  endgroup System Tasks
VMM Tutorial Cover Property
OVM Tutorial
The above example defines a covergroup named "cg". This covergroup will be Report a Bug or Comment
Easy Labs : SV automatically sampled each time there is a posedge on "clk" signal. on This section - Your
Easy Labs : UVM input is what keeps
Easy Labs : OVM Testbench.in improving
  covergroup cg; with time!
Easy Labs : VMM     ...
    ...
AVM Switch TB     ...
VMM Ethernet sample   endgroup
  
  cg cg_inst = new;
  
Verilog
  initial // or task or function or always block
Verification   begin
Verilog Switch TB     ...
    ...
Basic Constructs     cg_inst.sample();
    ...
    ...
OpenVera   end
Constructs
Switch TB Sampling can also be done by calling explicitly calling .sample() method in procedural
RVM Switch TB code. This is used when coverage sampling is required based on some calculations
rather than events.
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/CO_03_SAMPLE.html[9/26/2012 2:13:59 PM]


WWW.TESTBENCH.IN - SystemVerilog Functional Coverage

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CO_03_SAMPLE.html[9/26/2012 2:13:59 PM]


WWW.TESTBENCH.IN - SystemVerilog Functional Coverage

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS COVER POINTS Index


Introduction
SystemVerilog A covergroup can contain one or more coverage points. A coverage point can be an Cover Group
Verification integral variable or an integral expression. A coverage point creates a hierarchical Sample
scope, and can be optionally labeled. If the label is specified then it designates the Cover Points
Constructs name of the coverage point. Coverpoint Expression
Interface Generic Coverage Groups
Coverage Bins
OOPS Explicit Bin Creation
  program main;
Randomization     bit [0:2] y; Transition Bins
    bit [0:2] values[$]= '{3,5,6}; Wildcard Bins
Functional Coverage Ignore Bins
    
Assertion     covergroup cg; Illegal Bins
      cover_point_y : coverpoint y; Cross Coverage
DPI Coverage Options
    endgroup
UVM Tutorial      Coverage Methods
    cg cg_inst = new(); System Tasks
VMM Tutorial Cover Property
  
OVM Tutorial     initial
      foreach(values[i]) Report a Bug or Comment
Easy Labs : SV
      begin on This section - Your
Easy Labs : UVM         y = values[i]; input is what keeps
Easy Labs : OVM         cg_inst.sample(); Testbench.in improving
      end with time!
Easy Labs : VMM     
AVM Switch TB   endprogram
VMM Ethernet sample
In the above example, we are sampleing the cover point "y". The cover point is named
"cover_point_y" . In the Coverage report you will see this name. A cover group "cg" is
Verilog defined and its instance  "cg_inst" is created. The value of "y" is sampled when
Verification cg_inst.sample() method is called. Total possible values for Y are 0,1,2,3,4,5,6,7.  The
variable "y" is assigned only values 3,5,6.   The coverage engine should report that
Verilog Switch TB only 3 values are covered and there are 8 possible values.
Basic Constructs

Commands To Simulate And Get The Coverage Report:


OpenVera
VCS
Constructs
Switch TB
Compilation command:
RVM Switch TB vcs -sverilog -ntb_opts dtm filename.sv
RVM Ethernet sample Simulation Command:
./simv
Command to generate Coverage report: Coverage report in html format will be in the
./urgReport directory
Specman E urg -dir simv.vdb
Interview Questions

NCSIM

ncverilog -sv -access +rwc -coverage functional filename.sv


iccr iccr.cmd
iccr.cmd
load_test *
report_detail -instance -both -d *

http://testbench.in/CO_04_COVER_POINTS.html[9/26/2012 2:14:07 PM]


WWW.TESTBENCH.IN - SystemVerilog Functional Coverage

QUESTASIM

Create the library


vlib library_name

Compilation command
vlog work library_name filename.sv

Simulation Command:
vsim  library_name.module_top_name

Coverage will be saved in UCDB Format in Questasim

Case 1) By default in modelsim.ini file to Name of UCDB file will be threre, If it is


there, it will create one file  filename.ucdb

Case 2) Sometimes in modelsim.ini file UCDB File name will be commented in that
case we have to save UCDB File explicitly after vsim command
        Coverage save filename.ucdb

Once u are ready with UCDB File u need to generate coverage report from ucdb file
To generate only Functional coverage report
vcover cvg myreport.txt outfilename.ucdb

After running the above program, the coverage report will show,

VARIABLE  : cover_point_y
Expected : 8
Covered : 3
Percent: 37.50.

In the above report, the coverage percentage is calculated by Covered/Expected.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CO_04_COVER_POINTS.html[9/26/2012 2:14:07 PM]


WWW.TESTBENCH.IN - SystemVerilog Functional Coverage

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS COVERPOINT EXPRESSION Index


Introduction
SystemVerilog Coverpoint Expression Cover Group
Verification Sample
Cover Points
Constructs A coverage point can be an integral variable or an integral Expression. Coverpoint Expression
Interface SystemVerilog allows specifying the cover points in various ways. Generic Coverage Groups
Coverage Bins
OOPS Explicit Bin Creation
1)Using XMR
Randomization Transition Bins
Example: Wildcard Bins
Functional Coverage Ignore Bins
  Cover_xmr : coverpoint top.DUT.Submodule.bus_address;
Assertion Illegal Bins
Cross Coverage
DPI 2)Part select Coverage Options
UVM Tutorial Coverage Methods
Example: System Tasks
VMM Tutorial   Cover_part: coverpoint bus_address[31:2]; Cover Property
OVM Tutorial
3)Expression Report a Bug or Comment
Easy Labs : SV
on This section - Your
Easy Labs : UVM Example: input is what keeps
  Cocver_exp: coverpoint (a*b); Testbench.in improving
Easy Labs : OVM
with time!
Easy Labs : VMM 4)Function return value
AVM Switch TB Example:
VMM Ethernet sample   Cover_fun: coverpoint funcation_call();

5)Ref variable
Verilog
Example:
Verification   covergroup (ref int r_v) cg;
Verilog Switch TB     cover_ref: coverpoint  r_v;
  endgroup
Basic Constructs

OpenVera Coverage Filter


Constructs
The expression within the iff construct specifies an optional condition that disables
Switch TB coverage for that cover point. If the guard expression evaluates to false at a sampling
RVM Switch TB point, the coverage point is ignored.
RVM Ethernet sample For example:

  covergroup cg;
Specman E     coverpoint cp_varib iff(!reset);  // filter condition
  endgroup
Interview Questions

In the preceding example, cover point varible "cp_varib" is covered only if the value
reset is low.

http://testbench.in/CO_05_COVERPOINT_EXPRESSION.html[9/26/2012 2:14:17 PM]


WWW.TESTBENCH.IN - SystemVerilog Functional Coverage

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CO_05_COVERPOINT_EXPRESSION.html[9/26/2012 2:14:17 PM]


WWW.TESTBENCH.IN - SystemVerilog Functional Coverage

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS GENERIC COVERAGE GROUPS Index


Introduction
SystemVerilog Generic coverage groups can be written by passing their traits as arguments to the Cover Group
Verification coverage constructor. This allows creating a reusable coverage group which can be Sample
used in multiple places. Cover Points
Constructs Coverpoint Expression
Interface For example, To cover a array of specified index range. Generic Coverage
Groups
OOPS Coverage Bins
  covergroup  cg(ref int array, int low, int high ) @(clk);
Randomization     coverpoint// sample variable passed by reference Explicit Bin Creation
      { Transition Bins
Functional Coverage Wildcard Bins
       bins s = { [low : high] };
Assertion       } Ignore Bins
  endgroup Illegal Bins
DPI Cross Coverage
  
UVM Tutorial   int A, B; Coverage Options
  rgc1 = new( A, 0, 50 );// cover A in range 0 to 50 Coverage Methods
VMM Tutorial System Tasks
  rgc2 = new( B, 120, 600 );// cover B in range 120 to 600
OVM Tutorial Cover Property
Easy Labs : SV The example above defines a coverage group, gc, in which the signal to be sampled
as well as the extent of the coverage bins are specified as arguments. Later, two Report a Bug or Comment
Easy Labs : UVM instances of the coverage group are created; each instance samples a different signal on This section - Your
Easy Labs : OVM and covers a different range of values. input is what keeps
Testbench.in improving
Easy Labs : VMM with time!
AVM Switch TB
VMM Ethernet sample

Verilog
Verification
Verilog Switch TB
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/CO_06_GENERIC_COVERAGE_GROUPS.html[9/26/2012 2:14:25 PM]


WWW.TESTBENCH.IN - SystemVerilog Functional Coverage

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CO_06_GENERIC_COVERAGE_GROUPS.html[9/26/2012 2:14:25 PM]


WWW.TESTBENCH.IN - SystemVerilog Functional Coverage

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS COVERAGE BINS Index


Introduction
SystemVerilog Cover Group
Verification A coverage-point bin associates a name and a count with a set of values or a Sample
sequence of value transitions. If the bin designates a set of values, the count is Cover Points
Constructs incremented every time the coverage point matches one of the values in the set. If Coverpoint Expression
Interface the bin designates a sequence of value transitions, the count is incremented every Generic Coverage Groups
time the coverage point matches the entire sequence of value transitions. Coverage Bins
OOPS Explicit Bin Creation
Randomization Bins can be created implicitly or explicitly. Transition Bins
Wildcard Bins
Functional Coverage Ignore Bins
Assertion Implicit Bins Illegal Bins
Cross Coverage
DPI Coverage Options
While define cover point, if you do not specify any bins, then Implicit bins are
UVM Tutorial created. The number of bins creating can be controlled by auto_bin_max  parameter. Coverage Methods
System Tasks
VMM Tutorial Cover Property
OVM Tutorial Example for non enum cover point
Report a Bug or Comment
Easy Labs : SV
on This section - Your
Easy Labs : UVM   program main; input is what keeps
Easy Labs : OVM     bit [0:2] y; Testbench.in improving
    bit [0:2] values[$]= '{3,5,6}; with time!
Easy Labs : VMM     
AVM Switch TB     covergroup cg;
      cover_point_y : coverpoint y
VMM Ethernet sample                       { option.auto_bin_max = 4 ; }
    endgroup
    
Verilog     cg cg_inst = new();
Verification     initial
      foreach(values[i])
Verilog Switch TB       begin
Basic Constructs          y = values[i];
         cg_inst.sample();
      end
    
OpenVera   endprogram
Constructs
Switch TB
In the above example, the auto_bin_max is declared as 4. So, the total possible
RVM Switch TB values are divided in 4 parts and each part correspoits to one bin.
RVM Ethernet sample The total possible values for variable "y" are 8. They are divided in to 4 groups.

Bin[0]  for 0 and 1
Specman E Bin[1]  for 2 and 3
Interview Questions Bin[2]  for 4 and 5
Bin[3]  for 6 and 7

Varible Y is assigned values 3,5 and 6. Values 3,5 and 6 belongs to bins bin[1],bin[2]
and bin[3] respectively.  Bin[0] is not covered.

Coverage report:
--------------------
VARIABLE  : cover_point_y

http://testbench.in/CO_07_COVERAGE_BINS.html[9/26/2012 2:14:32 PM]


WWW.TESTBENCH.IN - SystemVerilog Functional Coverage

Expected : 4
Covered : 3
Percent:  75.00

Uncovered bins
------------------
auto[0:1]

Covered bins
------------------
auto[2:3]    
auto[4:5]    
auto[6:7]    

Example of enum data type:


For Enum data type, the numbers of bins are equal to the number of elements of
enum data type. The bin identifiers are the enum member name.

   typedef enum { A,B,C,D } alpha;
   program main;
       alpha y;
       alpha values[$]= '{A,B,C};
      
       covergroup cg;
           cover_point_y : coverpoint y;
       endgroup
      
       cg cg_inst = new();
       initial
          foreach(values[i])
          begin
             y = values[i];
             cg_inst.sample();
          end
  
   endprogram

In The above example, the variable "y" is enum data type and it can have 4 enum
members A,B,C and D. Variable Y is assigned only 3 Enum members A,B and C.

Coverage report:
---------------------
VARIABLE  : cover_point_y
Expected : 4
Covered : 3
Percent:  75.00

Uncovered bins
--------------------
auto_D    

Covered bins
--------------------
auto_C        
auto_B        
auto_A      

http://testbench.in/CO_07_COVERAGE_BINS.html[9/26/2012 2:14:32 PM]


WWW.TESTBENCH.IN - SystemVerilog Functional Coverage

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CO_07_COVERAGE_BINS.html[9/26/2012 2:14:32 PM]


WWW.TESTBENCH.IN - SystemVerilog Functional Coverage

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS EXPLICIT BIN CREATION Index


Introduction
SystemVerilog Cover Group
Verification  Explicit bin creation is recommended method. Not all values are interesting or Sample
relevant in a cover point, so when the user knows the exact values he is going to Cover Points
Constructs cover, he can use explicit bins. You can also name the bins. Coverpoint Expression
Interface Generic Coverage Groups
Coverage Bins
OOPS Explicit Bin Creation
   program main;
Randomization    bit [0:2] y; Transition Bins
   bit [0:2] values[$]= '{3,5,6}; Wildcard Bins
Functional Coverage Ignore Bins
  
Assertion    covergroup cg; Illegal Bins
      cover_point_y : coverpoint y { Cross Coverage
DPI Coverage Options
                       bins a = {0,1};  
UVM Tutorial                        bins b = {2,3};   Coverage Methods
                       bins c = {4,5};   System Tasks
VMM Tutorial Cover Property
                       bins d = {6,7};  
OVM Tutorial                        }
                         Report a Bug or Comment
Easy Labs : SV
   endgroup on This section - Your
Easy Labs : UVM    input is what keeps
Easy Labs : OVM    cg cg_inst = new(); Testbench.in improving
   initial with time!
Easy Labs : VMM       foreach(values[i])
AVM Switch TB       begin
         y = values[i];
VMM Ethernet sample          cg_inst.sample();
      end
  
Verilog    endprogram
Verification
Verilog Switch TB In the above example, bins are created explicitly. The bins are named a,b,c and d.
Basic Constructs

Coverage report:
-------------------
OpenVera VARIABLE  : cover_point_y
Constructs Expected : 4
Switch TB Covered : 3
Percent:  75.00
RVM Switch TB
RVM Ethernet sample Uncovered bins
--------------------
a  
Specman E Covered bins
Interview Questions --------------------
b        
c        
d        

Array Of Bins

To create a separate bin for each value (an array of bins) the square brackets, [],
must follow the bin name.

http://testbench.in/CO_08_EXPLICIT_BIN_CREATION.html[9/26/2012 2:14:40 PM]


WWW.TESTBENCH.IN - SystemVerilog Functional Coverage

   program main;
   bit [0:2] y;
   bit [0:2] values[$]= '{3,5,6};
  
   covergroup cg;
      cover_point_y : coverpoint y {
                       bins a[] = {[0:7]};  
                       }
                        
   endgroup
  
   cg cg_inst = new();
   initial
      foreach(values[i])
      begin
         y = values[i];
         cg_inst.sample();
      end
  
   endprogram

In the above example, bin a is array of 8 bins and each  bin associates to one number
between 0 to 7.

Coverage report:
--------------------
VARIABLE  : cover_point_y
Expected : 8
Covered : 3
Percent:  37.50

Uncovered bins
-------------------
a_0  
a_1  
a_2  
a_4  
a_7  

Covered bins
-------------------
a_3    
a_5    
a_6    

To create a fixed number of bins for a set of values, a number can be specified inside
the square brackets.

   program main;
   bit [0:3] y;
   bit [0:2] values[$]= '{3,5,6};
  
   covergroup cg;
      cover_point_y : coverpoint y {
                       bins a[4] = {[0:7]};  
                       }
                        
   endgroup
  
   cg cg_inst = new();
   initial
     foreach(values[i])
     begin

http://testbench.in/CO_08_EXPLICIT_BIN_CREATION.html[9/26/2012 2:14:40 PM]


WWW.TESTBENCH.IN - SystemVerilog Functional Coverage

       y = values[i];
       cg_inst.sample();
     end
  
   endprogram

In the above example, variable y is 4 bit width vector. Total possible values for this
vector are 16.
But in the cover point bins, we have giving the interested range as 0 to 7. So the
coverage report is calculated over the range 0 to 7 only.  In this example, we have
shown the number bins to be fixed to size 4.

Coverage report:
--------------------
VARIABLE  : cover_point_y
Expected : 4
Covered : 3
Percent:  75.00

Uncovered bins
-------------------
a[0:1]

Covered bins
------------------
a[2:3]      
a[4:5]      
a[6:7]      

Default Bin

The default specification defines a bin that is associated with none of the defined
value bins. The default bin catches the values of the coverage point that do not lie
within any of the defined bins. However, the coverage calculation for a coverage
point shall not take into account the coverage captured by the default bin.

   program main;
   bit [0:3] y;
   bit [0:2] values[$]= '{3,5,6};
  
   covergroup cg;
      cover_point_y : coverpoint y {
                       bins a[2] = {[0:4]};
                       bins d    = default;  
                       }
                        
   endgroup
  
   cg cg_inst = new();
   initial
     foreach(values[i])
     begin
        y = values[i];
        cg_inst.sample();
     end
  
   endprogram

In the above example, we have specified only 2 bins to cover values from 0 to 4. Rest
of values are covered in default bin <93>d<94> which  is not using in calculating the
coverage percentage.

Coverage report:
--------------------
VARIABLE  : cover_point_y
Expected : 2
Covered : 1

http://testbench.in/CO_08_EXPLICIT_BIN_CREATION.html[9/26/2012 2:14:40 PM]


WWW.TESTBENCH.IN - SystemVerilog Functional Coverage

Percent:  50.00

Uncovered bins
------------------
a[0:1]

Covered bins
----------------
a[2:4]  

Default  bin
-----------------
d  

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CO_08_EXPLICIT_BIN_CREATION.html[9/26/2012 2:14:40 PM]


WWW.TESTBENCH.IN - SystemVerilog Functional Coverage

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS TRANSITION BINS Index


Introduction
SystemVerilog Transitional functional point bin is used to examine the legal transitions of a value. Cover Group
Verification SystemVerilog allows to specifies one or more sets of ordered value transitions of the Sample
coverage point. Cover Points
Constructs Coverpoint Expression
Interface Type of Transitions: Generic Coverage Groups
Coverage Bins
OOPS Explicit Bin Creation
Single Value Transition
Randomization Transition Bins
Sequence Of Transitions Wildcard Bins
Functional Coverage Set Of Transitions Ignore Bins
Assertion Consecutive Repetitions Illegal Bins
Range Of Repetition Cross Coverage
DPI Goto Repetition Coverage Options
UVM Tutorial Non Consecutive Repetition Coverage Methods
System Tasks
VMM Tutorial Cover Property
 
OVM Tutorial
Report a Bug or Comment
Easy Labs : SV
Single Value Transition on This section - Your
Easy Labs : UVM input is what keeps
Easy Labs : OVM Single value transition is specified as: Testbench.in improving
value1 => value2 with time!
Easy Labs : VMM
AVM Switch TB     program main;
    bit [0:3] y;
VMM Ethernet sample     bit [0:2] values[$]= '{3,5,6};
    
    covergroup cg;
Verilog        cover_point_y : coverpoint y {
Verification                         bins tran_34 = (3=>4);
                        bins tran_56 = (5=>6);
Verilog Switch TB                         }
Basic Constructs                         
    endgroup
    
    cg cg_inst = new();
OpenVera     initial
Constructs        foreach(values[i])
Switch TB        begin
          y = values[i];
RVM Switch TB           cg_inst.sample();
RVM Ethernet sample        end
    
    endprogram

Specman E
Interview Questions In the above example, 2 bins are created for covering the transition of point "y" from
3 to 4 and other for 5 to 6.  The variable y is given the values and only the transition
5 to 6 is occurring.

Coverage report:
--------------------
VARIABLE  : cover_point_y
Expected : 2
Covered : 1
Percent:  50.00

http://testbench.in/CO_09_TRANSITION_BINS.html[9/26/2012 2:14:49 PM]


WWW.TESTBENCH.IN - SystemVerilog Functional Coverage

Uncovered bins
------------------
tran_34

Covered bins
----------------
tran_56

Sequence Of Transitions

A sequence of transitions is represented as:


value1 => value3 => value4 => value5

In this case, value1 is followed by value3, followed by value4 and followed by value5.
A sequence can be
of any arbitrary length.

   program main;
   bit [0:3] y;
   bit [0:2] values[$]= '{3,5,6};
  
   covergroup cg;
      cover_point_y : coverpoint y {
                       bins tran_345 = (3=>4>=5);
                       bins tran_356 = (3=>5=>6);
                       }
                        
   endgroup
  
   cg cg_inst = new();
   initial
      foreach(values[i])
      begin
        y = values[i];
        cg_inst.sample();
      end
  
   endprogram

In the above example, 2 bins re created for covering the transition of point "y" from 3
to 4 to 5 and other for  3 to 5 to 6.  The variable y is given the values and only the
transition 3 to 5 to 6 is occurring.

Coverage report:
--------------------
VARIABLE  : cover_point_y
Expected : 2
Covered : 1
Percent:  50.00

Uncovered bins
------------------
tran_345  

Covered bins
-----------------
tran_356  

Set Of Transitions

A set of transitions can be specified as:

http://testbench.in/CO_09_TRANSITION_BINS.html[9/26/2012 2:14:49 PM]


WWW.TESTBENCH.IN - SystemVerilog Functional Coverage

range_list1 => range_list2

    program main;
    bit [0:3] y;
    bit [0:2] values[$]= '{3,5,6};
    
    covergroup cg;
       cover_point_y : coverpoint y {
                        bins trans[] = (3,4=>5,6);
                        }
                        
    endgroup
    
    cg cg_inst = new();
    initial
       foreach(values[i])
       begin
          y = values[i];
          cg_inst.sample();
       end
    
    endprogram

In the above example, bin trans creates 4 bin for covering 3=>5,4=>5,3=>6 and 4=>6.

Coverage report:
--------------------
VARIABLE  : cover_point_y
Expected : 4
Covered : 1
Percent:  25.00

Uncovered bins
------------------
tran_34_to_56:3->6  
tran_34_to_56:4->5  
tran_34_to_56:4->6  

Covered bins
----------------
tran_34_to_56:3->5  

Consecutive Repetitions

Consecutive repetitions of transitions are specified using


trans_item [* repeat_range ]

Here, trans_item is repeated for repeat_range times. For example,


   3 [* 5]
is the same as
   3=>3=>3=>3=>3

    program main;
    bit [0:3] y;
    bit [0:2] values[$]= '{3,3,3,4,4};
    
    covergroup cg;
       cover_point_y : coverpoint y {
                        bins trans_3 = (3[*5]);
                        bins trans_4 = (4[*2]);
                        }
                        
    endgroup
    
    cg cg_inst = new();
    initial
       foreach(values[i])
       begin

http://testbench.in/CO_09_TRANSITION_BINS.html[9/26/2012 2:14:49 PM]


WWW.TESTBENCH.IN - SystemVerilog Functional Coverage

          y = values[i];
          cg_inst.sample();
       end
    
    endprogram

Coverage report:
--------------------
VARIABLE  : cover_point_y
Expected : 2
Covered : 1
Percent:  50.00

Uncovered bins
------------------
trans_3

Covered bins
----------------
trans_4

Range Of Repetition

An example of a range of repetition is:


  3 [* 3:5]
is the same as
  3=>3=>3, 3=>3=>3=>3, 3=>3=>3=>3=>3

   program main;
   bit [0:3] y;
   bit [0:2] values[$]= '{4,5,3,3,3,3,6,7};
  
   covergroup cg;
     cover_point_y : coverpoint y {
                      bins trans_3[] = (3[*3:5]);
                      }
                      
   endgroup
  
   cg cg_inst = new();
   initial
      foreach(values[i])
      begin
         y = values[i];
         cg_inst.sample();
      end
  
   endprogram

In the above example,  only the sequence 3=>3=>3=>3 is  generated. Other expected


sequences 3=>3=>3 and 3=>3=>3=>3=>3 are not generated.

Coverage report:
--------------------
VARIABLE  : cover_point_y
Expected : 3
Covered : 1
Percent:  33.33

Uncovered bins
------------------
tran_3:3[*3]
tran_3:3[*5]

Covered bins
----------------
tran_3:3[*4]  

http://testbench.in/CO_09_TRANSITION_BINS.html[9/26/2012 2:14:49 PM]


WWW.TESTBENCH.IN - SystemVerilog Functional Coverage

            

Goto Repetition

The goto repetition is specified using: trans_item [-> repeat_range]. The required
number of occurrences of a particular value is specified by the repeat_range. Any
number of sample points can occur before the first occurrence of the specified value
and any number of sample points can occur between each occurrence of the specified
value. The transition following the goto repetition must immediately follow the last
occurrence of the repetition.
For example:
  3 [-> 3]
is the same as
 ...=>3...=>3...=>3

where the dots (...) represent any transition that does not contain the value 3.

A goto repetition followed by an additional value is represented as follows:


  1 => 3 [ -> 3] => 5
is the same as
  1...=>3...=>3...=>3 =>5

    program main;
    bit [0:3] y;
    bit [0:2] values[$]= '{1,6,3,6,3,6,3,5};
    
    covergroup cg;
       cover_point_y : coverpoint y {
                        bins trans_3 = (1=>3[->3]=>5);
                        }
                        
    endgroup
    
    cg cg_inst = new();
    initial
       foreach(values[i])
       begin
          y = values[i];
          cg_inst.sample();
       end
    
    endprogram

Coverage report:
--------------------
VARIABLE  : cover_point_y
Expected : 1
Covered : 1
Percent:  100.00

Non Consecutive Repetition

The nonconsecutive repetition is specified using: trans_item [= repeat_range]. The


required number of occurrences of a particular value is specified by the repeat_range.
Any number of sample points can occur before the first occurrence of the specified
value and any number of sample points can occur between each occurrence of the
specified value. The transition following the nonconsecutive repetition may occur
after any number of sample points so long as the repetition value does not occur
again.

For example:
   3 [= 2]
is same as
   ...=>3...=>3

A nonconsecutive repetition followed by an additional value is represented as follows:


   1 => 3 [=2] => 5
is the same as
   1...=>3...=>3...=>5

http://testbench.in/CO_09_TRANSITION_BINS.html[9/26/2012 2:14:49 PM]


WWW.TESTBENCH.IN - SystemVerilog Functional Coverage

    program main;
    bit [0:3] y;
    bit [0:2] values[$]= '{1,6,3,6,3,6,5};
    
    covergroup cg;
       cover_point_y : coverpoint y {
                        bins trans_3 = (1=>3[=2]=>5);
                        }
                        
    endgroup
    
    cg cg_inst = new();
    initial
       foreach(values[i])
       begin
          y = values[i];
          cg_inst.sample();
       end
    
    endprogram

Coverage report:
--------------------
VARIABLE  : cover_point_y
Expected : 1
Covered : 1
Percent:  100.00

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CO_09_TRANSITION_BINS.html[9/26/2012 2:14:49 PM]


WWW.TESTBENCH.IN - SystemVerilog Functional Coverage

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS WILDCARD BINS Index


Introduction
SystemVerilog Cover Group
Verification By default, a value or transition bin definition can specify 4-state values. Sample
When a bin definition includes an X or Z, it indicates that the bin count should only be Cover Points
Constructs incremented when the sampled value has an X or Z in the same bit positions. Coverpoint Expression
Interface The wildcard bins definition causes all X, Z, or ? to be treated as wildcards for 0 or 1 Generic Coverage Groups
(similar to the ==? operator). Coverage Bins
OOPS Explicit Bin Creation
For example:
Randomization Transition Bins
   wildcard bins g12_16 = { 4'b11?? }; Wildcard Bins
Functional Coverage Ignore Bins
Assertion The count of bin g12_16 is incremented when the sampled variable is between 12 and Illegal Bins
16: Cross Coverage
DPI Coverage Options
UVM Tutorial     1100 1101 1110 1111 Coverage Methods
System Tasks
VMM Tutorial Cover Property
   program main;
OVM Tutorial    reg [0:3] y;
   reg [0:3] values[$]= '{ 4'b1100,4'b1101,4'b1110,4'b1111}; Report a Bug or Comment
Easy Labs : SV
   on This section - Your
Easy Labs : UVM    covergroup cg; input is what keeps
Easy Labs : OVM       cover_point_y : coverpoint y { Testbench.in improving
                       wildcard bins g12_15 = { 4'b11?? } ; with time!
Easy Labs : VMM                        }
AVM Switch TB                         
   endgroup
VMM Ethernet sample   
   cg cg_inst = new();
   initial
Verilog       foreach(values[i])
Verification       begin
         y = values[i];
Verilog Switch TB          cg_inst.sample();
Basic Constructs       end
  
   endprogram
OpenVera Coverage report:
Constructs --------------------
Switch TB VARIABLE  : cover_point_y
Expected : 1
RVM Switch TB Covered : 1
RVM Ethernet sample Percent:  100.00
Covered bin
---------------
Specman E g12_15
Interview Questions Number of times g12_15 hit : 4  

Similarly, transition bins can define wildcard bins.


For example:

wildcard bins T0_3 = (2'b0x => 2'b1x);

The count of transition bin T0_3 is incremented for the following transitions (as if by

http://testbench.in/CO_10_WILDCARD_BINS.html[9/26/2012 2:14:57 PM]


WWW.TESTBENCH.IN - SystemVerilog Functional Coverage

(0,1=>2,3)):

00 => 10 , 00 => 11,  01 => 10 , 01 => 11

   program main;
   reg [0:1] y;
   reg [0:1] values[$]= '{ 2'b00,2'b01,2'b10,2'b11};
  
   covergroup cg;
      cover_point_y : coverpoint y {
                       wildcard bins trans = (2'b0X => 2'b1X );
                       }
                        
   endgroup
  
   cg cg_inst = new();
   initial
      foreach(values[i])
      begin
         y = values[i];
         cg_inst.sample();
      end
  
   endprogram

Coverage report:
--------------------
VARIABLE  : cover_point_y
Expected : 1
Covered : 1
Percent:  100.00

Covered bin
---------------
trans
Number of times trans hit : 1  (01 => 10)

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CO_10_WILDCARD_BINS.html[9/26/2012 2:14:57 PM]


WWW.TESTBENCH.IN - SystemVerilog Functional Coverage

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS IGNORE BINS Index


Introduction
SystemVerilog A set of values or transitions associated with a coverage-point can be explicitly Cover Group
Verification excluded from coverage by specifying them as ignore_bins. Sample
Cover Points
Constructs Coverpoint Expression
Interface    program main; Generic Coverage Groups
   bit [0:2] y; Coverage Bins
OOPS Explicit Bin Creation
   bit [0:2] values[$]= '{1,6,3,7,3,4,3,5};
Randomization    Transition Bins
   covergroup cg; Wildcard Bins
Functional Coverage Ignore Bins
      cover_point_y : coverpoint y {
Assertion                        ignore_bins ig = {1,2,3,4,5}; Illegal Bins
                       } Cross Coverage
DPI Coverage Options
                        
UVM Tutorial    endgroup Coverage Methods
   System Tasks
VMM Tutorial Cover Property
   cg cg_inst = new();
OVM Tutorial    initial
      foreach(values[i]) Report a Bug or Comment
Easy Labs : SV
      begin on This section - Your
Easy Labs : UVM          y = values[i]; input is what keeps
Easy Labs : OVM          cg_inst.sample(); Testbench.in improving
      end with time!
Easy Labs : VMM   
AVM Switch TB    endprogram
VMM Ethernet sample In the above program,  total possible values for y are 0 to 7.  Ignore_bins specified to
Ignored values between 1 to 5. So the Expected values are 0,6 and 7. Out of these
expected values, only 6 and 7 are generated.
Verilog
Verification
Coverage report:
Verilog Switch TB --------------------
Basic Constructs VARIABLE  : cover_point_y
Expected : 3
Covered : 2
Percent:  66.66
OpenVera
Constructs Uncovered bins
Switch TB ------------------
auto[0]
RVM Switch TB
RVM Ethernet sample
Excluded/Illegal bins
-------------------------
ig      
Specman E auto[1]
Interview Questions auto[2]
auto[3]
auto[4]
auto[5]

Covered bins
----------------
auto[6]      
auto[7]      

http://testbench.in/CO_11_IGNORE_BINS.html[9/26/2012 2:15:07 PM]


WWW.TESTBENCH.IN - SystemVerilog Functional Coverage

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CO_11_IGNORE_BINS.html[9/26/2012 2:15:07 PM]


WWW.TESTBENCH.IN - SystemVerilog Functional Coverage

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS ILLEGAL BINS Index


Introduction
SystemVerilog A set of values or transitions associated with a coverage-point can be marked as Cover Group
Verification illegal by specifying them as illegal_bins.  All values or transitions associated with Sample
illegal bins are excluded from coverage. If an illegal value or transition occurs, a Cover Points
Constructs runtime error is issued. Coverpoint Expression
Interface Generic Coverage Groups
Coverage Bins
OOPS Explicit Bin Creation
   program main;
Randomization    bit [0:2] y; Transition Bins
   bit [0:2] values[$]= '{1,6,3,7,3,4,3,5}; Wildcard Bins
Functional Coverage Ignore Bins
  
Assertion    covergroup cg; Illegal Bins
      cover_point_y : coverpoint y { Cross Coverage
DPI Coverage Options
                       illegal_bins ib = {7};
UVM Tutorial                        } Coverage Methods
                         System Tasks
VMM Tutorial Cover Property
   endgroup
OVM Tutorial   
   cg cg_inst = new(); Report a Bug or Comment
Easy Labs : SV
   initial on This section - Your
Easy Labs : UVM       foreach(values[i]) input is what keeps
Easy Labs : OVM       begin Testbench.in improving
         y = values[i]; with time!
Easy Labs : VMM          cg_inst.sample();
AVM Switch TB       end
  
VMM Ethernet sample    endprogram

Result:
Verilog ------------
Verification ** ERROR **
Illegal state bin ib of coverpoint cover_point_y in
Verilog Switch TB covergroup cg got hit with value 0x7
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/CO_12_ILLEGAL_BINS.html[9/26/2012 2:15:14 PM]


WWW.TESTBENCH.IN - SystemVerilog Functional Coverage

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CO_12_ILLEGAL_BINS.html[9/26/2012 2:15:14 PM]


WWW.TESTBENCH.IN - SystemVerilog Functional Coverage

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS CROSS COVERAGE Index


Introduction
SystemVerilog Cross allows keeping track of information which is received simultaneous on more Cover Group
Verification than one cover point. Cross coverage is specified using the cross construct. Sample
Cover Points
Constructs Coverpoint Expression
Interface     program main; Generic Coverage Groups
    bit [0:1] y; Coverage Bins
OOPS Explicit Bin Creation
    bit [0:1] y_values[$]= '{1,3};
Randomization      Transition Bins
    bit [0:1] z; Wildcard Bins
Functional Coverage Ignore Bins
    bit [0:1] z_values[$]= '{1,2};
Assertion      Illegal Bins
    covergroup cg; Cross Coverage
DPI Coverage Options
        cover_point_y : coverpoint y ;
UVM Tutorial         cover_point_z : coverpoint z ; Coverage Methods
        cross_yz : cross cover_point_y,cover_point_z ;                   System Tasks
VMM Tutorial Cover Property
    endgroup
OVM Tutorial     
    cg cg_inst = new(); Report a Bug or Comment
Easy Labs : SV
    initial on This section - Your
Easy Labs : UVM        foreach(y_values[i]) input is what keeps
Easy Labs : OVM        begin Testbench.in improving
           y = y_values[i]; with time!
Easy Labs : VMM            z = z_values[i];
AVM Switch TB            cg_inst.sample();
       end
VMM Ethernet sample     
    endprogram

Verilog
Verification In the above program, y has can have 4 values 0,1,2 and 3 and similarly z can have 4
values 0,1,2 and 3. The cross product of the y and z will be 16 values
Verilog Switch TB (00),(01),(02),(03),(10),(11)........(y,z)......(3,2)(3,3) .
Basic Constructs Only combinations (11) and (32) are generated.

Cross coverage report:  cover points are not shown.


OpenVera
Constructs Covered bins
Switch TB -----------------
cover_point_y   cover_point_z  
RVM Switch TB auto[3]          auto[2]      
RVM Ethernet sample auto[1]          auto[1]      

Specman E User-Defined Cross Bins


Interview Questions
User-defined bins for cross coverage are defined using bin select expressions.

Consider the following example code:

   int i,j;
   covergroup ct;
      coverpoint i { bins i[] = { [0:1] }; }
      coverpoint j { bins j[] = { [0:1] }; }
      x1: cross i,j;
      x2: cross i,j {

http://testbench.in/CO_13_CROSS_COVERAGE.html[9/26/2012 2:15:22 PM]


WWW.TESTBENCH.IN - SystemVerilog Functional Coverage

          bins i_zero = binsof(i) intersect { 0 };
      }
   endgroup

Cross x1 has the following bins:


<i[0],j[0]>
<i[1],j[0]>
<i[0],j[1]>
<i[1],j[1]>
Cross x2 has the following bins:
i_zero
<i[1],j[0]>
<i[1],j[1]>

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CO_13_CROSS_COVERAGE.html[9/26/2012 2:15:22 PM]


WWW.TESTBENCH.IN - SystemVerilog Functional Coverage

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS COVERAGE OPTIONS Index


Introduction
SystemVerilog Options control the behavior of the covergroup, coverpoint, and cross. Cover Group
Verification There are two types of options: Sample
Cover Points
Constructs Coverpoint Expression
those that are specific to an instance of a covergroup and
Interface Generic Coverage Groups
those that specify an option for the covergroup type as a whole. Coverage Bins
OOPS Explicit Bin Creation
Randomization Transition Bins
Weight Wildcard Bins
Functional Coverage Ignore Bins
Syntax : weight= number Illegal Bins
Assertion default value: 1 Cross Coverage
DPI Coverage Options
Description : Coverage Methods
UVM Tutorial If set at the covergroup syntactic level, it specifies the weight of this covergroup System Tasks
VMM Tutorial instance for computing the overall instance coverage of the simulation. If set at the Cover Property
coverpoint (or cross) syntactic level, it specifies the weight of a coverpoint (or cross)
OVM Tutorial
for computing the instance coverage of the enclosing covergroup.  The specified
Report a Bug or Comment
Easy Labs : SV weight shall be a non-negative integral value.
on This section - Your
Easy Labs : UVM input is what keeps
Easy Labs : OVM Testbench.in improving
Goal
with time!
Easy Labs : VMM
Syntax :goal=number
AVM Switch TB default value: 100
VMM Ethernet sample
Description :
 Specifies the target goal for a covergroup instance or for a coverpoint or a cross of an
instance.
Verilog
Verification
Verilog Switch TB
Name

Basic Constructs Syntax :name=string


default value:unique name

OpenVera Description :
Specifies a name for the covergroup instance. If unspecified, a unique name for each
Constructs instance is automatically generated by the tool.
Switch TB
RVM Switch TB
Comment
RVM Ethernet sample
Syntax :comment=string
default value: ""
Specman E
Description :
Interview Questions A comment that appears with a covergroup instance or with a coverpoint or cross of
the covergroup instance. The comment is saved in the coverage database and included
in the coverage report.

At_least

Syntax :at_least=number
default value: 1

Description :

http://testbench.in/CO_14_COVERAGE_OPTIONS.html[9/26/2012 2:15:33 PM]


WWW.TESTBENCH.IN - SystemVerilog Functional Coverage

 Minimum number of hits for each bin. A bin with a hit count that is less than number
is not considered covered.

Detect_overlap

Syntax :detect_overlap=Boolean
default value:  0

Description :
When true, a warning is issued if there is an overlap between the range list (or
transition list) of two bins of a coverpoint.

Auto_bin_max

Syntax :auto_bin_max=number
default value:  64

Description :
 Maximum number of automatically created bins when no bins are explicitly defined
for a coverpoint.

Cross_num_print_missing

Syntax :cross_num_print_missing=number
default value: 0

Description :
 Number of missing (not covered) cross product bins that shall be saved to the
coverage database and printed in the coverage report.

Per_instance

Syntax :per_instance=Boolean
default value: 0

Description :
 Each instance contributes to the overall coverage information for the covergroup
type. When true, coverage information for this covergroup instance shall be saved in
the coverage database and included in the coverage report. When false,
implementations are not required to save instance-specific information.

Get_inst_coverage

Syntax :get_inst_coverage=Boolean
default value:  0

Description :
 Only applies when the merge_instances type option is set . Enables the tracking of
per instance coverage with the get_inst_coverage built-in method. When false, the
value returned by get_inst_coverage shall equal the value returned by get_coverage

Following Table summarizes the syntactical level (covergroup, coverpoint, or cross) in


which type options can be specified.

http://testbench.in/CO_14_COVERAGE_OPTIONS.html[9/26/2012 2:15:33 PM]


WWW.TESTBENCH.IN - SystemVerilog Functional Coverage

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CO_14_COVERAGE_OPTIONS.html[9/26/2012 2:15:33 PM]


WWW.TESTBENCH.IN - SystemVerilog Functional Coverage

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS COVERAGE METHODS Index


Introduction
SystemVerilog The following coverage methods are provided for the covergroup. These methods can Cover Group
Verification be invoked procedurally at any time. Sample
Cover Points
Constructs Coverpoint Expression
Interface void sample(): Generic Coverage Groups
Description : Triggers sampling of the covergroup Coverage Bins
OOPS Explicit Bin Creation
Randomization Transition Bins
real get_coverage() Wildcard Bins
Functional Coverage real get_coverage(ref int, ref int)   Ignore Bins
Description : Calculates type coverage number (0...100) Illegal Bins
Assertion The get_coverage() method returns the cumulative (or type) coverage, which Cross Coverage
DPI considers the contribution of all instances of a particular coverage item. and it is a Coverage Options
static method that is available on both types (via the :: operator) and instances (using Coverage Methods
UVM Tutorial the "." operator). System Tasks
VMM Tutorial Cover Property
The get_coverage()  method both accept an optional set of arguments, a pair of int
OVM Tutorial
values passed by reference. When the optional arguments are specified, the
Report a Bug or Comment
Easy Labs : SV get_coverage() method assign to the first argument the value of the covered bins, and
on This section - Your
to the second argument the number of bins for the given coverage item. These two
Easy Labs : UVM input is what keeps
values correspond to the numerator and the denominator used for calculating the
Easy Labs : OVM Testbench.in improving
particular coverage number (i.e., the return value before scaling by 100).
with time!
Easy Labs : VMM
real get_inst_coverage()
AVM Switch TB real get_inst_coverage(ref int, ref int)
VMM Ethernet sample Description : Calculates the coverage number (0...100)
get_inst_coverage() method returns the coverage of the specific instance on which it
is invoked, thus, it can only be invoked via the "." operator.
Verilog The get_inst_coverage() method both accept an optional set of arguments, a pair of
Verification int values passed by reference. When the optional arguments are specified, the
Verilog Switch TB get_inst_coverage() method assign to the first argument the value of the covered bins,
and to the second argument the number of bins for the given coverage item. These
Basic Constructs two values correspond to the numerator and the denominator used for calculating the
particular coverage number (i.e., the return value before scaling by 100).

OpenVera void set_inst_name(string)


Constructs Description : Sets the instance name to the given string
Switch TB void start()
RVM Switch TB Description : Starts collecting coverage information
RVM Ethernet sample
void stop()
Description : Stops collecting coverage information

Specman E
Interview Questions

http://testbench.in/CO_15_COVERAGE_METHODS.html[9/26/2012 2:15:42 PM]


WWW.TESTBENCH.IN - SystemVerilog Functional Coverage

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CO_15_COVERAGE_METHODS.html[9/26/2012 2:15:42 PM]


WWW.TESTBENCH.IN - SystemVerilog Functional Coverage

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS SYSTEM TASKS Index


Introduction
SystemVerilog Cover Group
Verification SystemVerilog provides the following system tasks and functions to help manage Sample
coverage data collection. Cover Points
Constructs Coverpoint Expression
Interface $set_coverage_db_name ( name ) : Generic Coverage Groups
 Sets the filename of the coverage database into which coverage information is saved Coverage Bins
OOPS Explicit Bin Creation
at the end of a simulation run.
Randomization Transition Bins
Wildcard Bins
Functional Coverage $load_coverage_db ( name ) : Ignore Bins
 Load from the given filename the cumulative coverage information for all coverage Illegal Bins
Assertion group types. Cross Coverage
DPI Coverage Options
UVM Tutorial
$get_coverage ( ) : Coverage Methods
 Returns as a real number in the range 0 to 100 the overall coverage of all coverage System Tasks
VMM Tutorial group types. This number is computed as described above. Cover Property
OVM Tutorial
Report a Bug or Comment
Easy Labs : SV
on This section - Your
Easy Labs : UVM input is what keeps
Easy Labs : OVM Testbench.in improving
with time!
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

Verilog
Verification
Verilog Switch TB
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/CO_16_SYSTEM_TASKS.html[9/26/2012 2:15:49 PM]


WWW.TESTBENCH.IN - SystemVerilog Functional Coverage

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CO_16_SYSTEM_TASKS.html[9/26/2012 2:15:49 PM]


WWW.TESTBENCH.IN - SystemVerilog Functional Coverage

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS COVER PROPERTY Index


Introduction
SystemVerilog Cover Group
Verification Cover statement can be used to monitor sequences and other behavioral aspects of Sample
the design. The tools can gather information about the evaluation and report the Cover Points
Constructs results at the end of simulation. When the property for the cover statement is Coverpoint Expression
Interface successful, the pass statements can specify a coverage function, such as monitoring Generic Coverage Groups
all paths for a sequence. The pass statement shall not include any concurrent assert, Coverage Bins
OOPS Explicit Bin Creation
assume or cover statement. A cover property creates a single cover point.
Randomization Transition Bins
Coverage results are divided into two: coverage for properties, coverage for Wildcard Bins
Functional Coverage Ignore Bins
sequences.
Assertion For sequence coverage, the statement appears as: Illegal Bins
Cross Coverage
DPI Coverage Options
Cover property ( sequence_expr ) statement_or_null
UVM Tutorial Coverage Methods
Cover Property Results System Tasks
VMM Tutorial Cover Property
OVM Tutorial The results of coverage statement for a property shall contain:
Number of times attempted Report a Bug or Comment
Easy Labs : SV
on This section - Your
Easy Labs : UVM
Number of times succeeded
input is what keeps
Number of times failed Testbench.in improving
Easy Labs : OVM Number of times succeeded because of vacuity with time!
Easy Labs : VMM
In addition, statement_or_null is executed every time a property succeeds.
AVM Switch TB
VMM Ethernet sample Vacuity rules are applied only when implication operator is used. A property succeeds
non-vacuously only if the consequent of the implication contributes to the success.

Verilog
Cover Sequence Results
Verification
Verilog Switch TB Results of coverage for a sequence shall include:
Number of times attempted
Basic Constructs
Number of times matched (each attempt can generate multiple matches)

In addition, statement_or_null gets executed for every match. If there are multiple
OpenVera matches at the same time, the statement gets executed multiple times, one for each
Constructs match.
Switch TB
It is recommended to cover sequences and not properties and its easy to convert a
RVM Switch TB property into a sequence if required.
RVM Ethernet sample
Coverage property can be declared in

Specman E A design or a separate module


Interview Questions Packages
Interfaces
Program block

Cover properties are not allowed in  class.

Comparison Of Cover Property And Cover Group.

Cover groups can reference data sets where as cover property references a temporal
expression.

http://testbench.in/CO_17_COVER_PROPERTY.html[9/26/2012 2:15:58 PM]


WWW.TESTBENCH.IN - SystemVerilog Functional Coverage

Cover group can be triggered using .sample method ()


Cover property dont have this option.

Cover group has multiple bins options.


Cover property has only one bin.

Cover group cannot handle complex temporal relationships.


Cover properties can cover complex temporal expressions.

Cover group automatically handles the crosses.


Cover properties cannot do crosses.

Cover group has lot of filtering options.


Cover property has no specific filtering constructs but it can be filtered.

Cover properties cannot be used in classes.


Cover groups can be used in classes. So, cover groups can reference the variables in
class.

Cover groups are most useful at a higher level of abstractions where as cover property
makes sense to use when we want to work at low level signals.

We can mix cover group and cover property to gain the OO and temporal advantages.
Using properties for temporal expressions and trigger the cover group.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CO_17_COVER_PROPERTY.html[9/26/2012 2:15:58 PM]


WWW.TESTBENCH.IN - System Verilog Assertion - SVA

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INTRODUCTION Index


Introduction
SystemVerilog Event Simulation
Verification SystemVerilog adds features to specify assertions of a system. An assertion specifies a Assertion Types
behavior of the system. Assertions are primarily used to validate the behavior of a Assertion System Tasks
Constructs design. In addition, assertions can be used to provide functional coverage and Concurrent Assertion
Interface generate input stimulus for validation. Layers
Sequences
OOPS Properties
The evaluation of the assertions is guaranteed to be equivalent between simulation,
Randomization which is event-based, and formal verification, which is cycle-based. Verification Directive
Functional Coverage
SystemVerilog allows assertions to communicate information to the test bench and Report a Bug or Comment
Assertion allows the test bench to react to the status of assertions without requiring a separate on This section - Your
application programming interface (API) of any kind input is what keeps
DPI Testbench.in improving
UVM Tutorial with time!
VMM Tutorial Advantages Of Assertion:
OVM Tutorial Improving Observability.
Easy Labs : SV Reduces the debug time.
Bugs can be found earlier and are more isolated.
Easy Labs : UVM Controllable severity level.
Easy Labs : OVM Can interact with C functions.
Describe the Documentation and Specification of the design.
Easy Labs : VMM
AVM Switch TB
What Assertions Can Verify:
VMM Ethernet sample

Assertions can be used to capture the information about various level of properties.
Verilog conceptual : can be used to verify systemlevel properties which are more
Verification architectural level.
design     : These expresses unit level properties.
Verilog Switch TB programming: More specified at RTL level.
Basic Constructs  1)conditional: It checks the some conditinal to be true using boolean expressions.
 2)sequence   : Checks whether the properties arr true using temporal expression.
 3)signal     : Checks on signal types.
     a)x detection :Can be used to detect unconnected ports or undriven signal.
OpenVera      b)encoding types: Checks whether the encoding is violated.
Constructs          1)onehot  
Switch TB          2)gray code
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/AS_01_INTRODUCTION.html[9/26/2012 2:16:07 PM]


WWW.TESTBENCH.IN - System Verilog Assertion - SVA

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/AS_01_INTRODUCTION.html[9/26/2012 2:16:07 PM]


WWW.TESTBENCH.IN - System Verilog Assertion - SVA

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS EVENT SIMULATION Index


Introduction
SystemVerilog Event Simulation
Verification The Problem of race condition exists if the SVA is sampling the signals exactly at Assertion Types
specified event. So in SystemVerilog , the language has very clear semantics to avoid Assertion System Tasks
Constructs race condition while evaluating SVA.   Concurrent Assertion
Interface Layers
Sequences
OOPS Properties
Randomization Verification Directive
Functional Coverage Report a Bug or Comment
Assertion on This section - Your
input is what keeps
DPI Testbench.in improving
UVM Tutorial with time!
VMM Tutorial
OVM Tutorial
Easy Labs : SV
Easy Labs : UVM
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

Verilog
Verification
Verilog Switch TB
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB In SV, a new region is added before Active region called preponed.  So sampling for
SVA is done in preponed region. No assignments are not done in preponed region.
RVM Ethernet sample Signals are stable from previous timeslot and they are occurring before active and
NBA ,so the race condition is avoided by this new preponed region. Look at the
diagram, regions which are in light cyan color are for SVA.
Specman E         
IN preponed region only sampling is done , the evaluation of these sampled values are
Interview Questions done in another region called observed region. Observed region occurs after NBA
region. Even though the assignments are done in active ,inactive,NBA region, these
updates are not used in observed region. Only signals sample in preponed region are
used in observed region. Observed region occurs before reactive region where the
testbench executes.

But in immediate assertions, the updated values in previous regions of current time
slot are used in observed region.

http://testbench.in/AS_02_EVENT_SIMULATION.html[9/26/2012 2:16:17 PM]


WWW.TESTBENCH.IN - System Verilog Assertion - SVA

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/AS_02_EVENT_SIMULATION.html[9/26/2012 2:16:17 PM]


WWW.TESTBENCH.IN - System Verilog Assertion - SVA

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS ASSERTION TYPES Index


Introduction
SystemVerilog Event Simulation
Verification There are two types of assertions. Assertion Types
Immediate assertions are useful for checking combinational expression. These are Assertion System Tasks
Constructs similar to if and else statement but with assertion control. Immediate assertions Concurrent Assertion
Interface follow simulation event semantics for their execution and are executed like a Layers
statement in a procedural block. Sequences
OOPS Properties
Randomization Verification Directive
Functional Coverage Report a Bug or Comment
Assertion on This section - Your
input is what keeps
DPI Testbench.in improving
UVM Tutorial with time!
VMM Tutorial
OVM Tutorial
Easy Labs : SV
Easy Labs : UVM
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

Verilog
Verification
Verilog Switch TB
EXAMPLE:
Basic Constructs time t;
always @(posedge clk)
if (state == REQ)
OpenVera assert (req1 || req2);
else begin
Constructs
t = $time;
Switch TB #5 $error("assert failed at time %0t",t);
RVM Switch TB end

RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/AS_03_ASSERTION_TYPES.html[9/26/2012 2:16:24 PM]


WWW.TESTBENCH.IN - System Verilog Assertion - SVA

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/AS_03_ASSERTION_TYPES.html[9/26/2012 2:16:24 PM]


WWW.TESTBENCH.IN - System Verilog Assertion - SVA

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS ASSERTION SYSTEM TASKS Index


Introduction
SystemVerilog Event Simulation
Verification Because the assertion is a statement that something must be true, the failure of an Assertion Types
assertion shall have a Assertion System Tasks
Constructs severity associated with it. By default, the severity of an assertion failure is error. Concurrent Assertion
Interface Other severity levels can Layers
be specified by including one of the following severity system tasks in the fail Sequences
OOPS Properties
statement:
Randomization Verification Directive
 $fatal is a run-time fatal.
Functional Coverage Report a Bug or Comment
 $error is a run-time error.
Assertion  $warning is a run-time warning, which can be suppressed in a tool-specific manner. on This section - Your
 $info indicates that the assertion failure carries no specific severity. input is what keeps
DPI Testbench.in improving
UVM Tutorial with time!
VMM Tutorial
Assertion Control System Tasks:
OVM Tutorial
Easy Labs : SV SystemVerilog provides three system tasks to control assertions.
Easy Labs : UVM $assertoff shall stop the checking of all specified assertions until a subsequent
Easy Labs : OVM $asserton. An assertion that is already executing, including execution of the pass or
fail statement, is not affected.
Easy Labs : VMM
AVM Switch TB $assertkill shall abort execution of any currently executing specified assertions and
then stop the checking of all specified assertions until a subsequent $asserton.
VMM Ethernet sample
$asserton shall reenable the execution of all specified assertions. When invoked with
no arguments, the system task shall apply to all assertions. When the task is specified
Verilog with arguments, the first argument indicates levels of the hierarchy, consistent with
Verification the corresponding argument to the Verilog $dumpvars system task. Subsequent
arguments specify which scopes of the model to control. These arguments can specify
Verilog Switch TB entire modules or individual assertions.
Basic Constructs

Boolean System Function:


OpenVera
Constructs $countones : Returns the numbers of 1's in a bit vector.
Switch TB $past      : Returns the values of the past.
$stable    : If the Signal is stable, then it returns 1.
RVM Switch TB $isunknown : If th X is seen in expression , then it returns 1.
RVM Ethernet sample $rose      : returns true if the LSB of the expression changed to 1. Otherwise, it
returns false.
$fell      : returns true if the LSB of the expression changed to 0. Otherwise, it returns
false.
Specman E $onehot    : returns true if only 1 bit of the expression is high.
Interview Questions $onehot0   : returns true if at most 1 bit of the expression is high.

What is the difference between $rose and posedge?


posedge returns event where as $rose returns a boolean value. Events cannot be used
in expression, $rose can be used.

http://testbench.in/AS_04_ASSERTION_SYSTEM_TASKS.html[9/26/2012 2:16:32 PM]


WWW.TESTBENCH.IN - System Verilog Assertion - SVA

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/AS_04_ASSERTION_SYSTEM_TASKS.html[9/26/2012 2:16:32 PM]


WWW.TESTBENCH.IN - System Verilog Assertion - SVA

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS CONCURRENT ASSERTION LAYERS Index


Introduction
SystemVerilog Event Simulation
Verification Concurrent assertions describe behavior that spans over time. Unlike immediate Assertion Types
assertions, the evaluation model is based on a clock so that a concurrent assertion is Assertion System Tasks
Constructs evaluated only at the occurrence of a clock tick. Concurrent Assertion
Interface Layers
There are 4 layers in  concurrent assertions. They are Sequences
OOPS Properties
Randomization Boolean expressions. Verification Directive
Functional Coverage
Sequence expression.
Property declaration. Report a Bug or Comment
Assertion Verification directives. on This section - Your
input is what keeps
DPI Testbench.in improving
UVM Tutorial with time!
VMM Tutorial
OVM Tutorial
Easy Labs : SV
Easy Labs : UVM
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

Verilog
Verification
Verilog Switch TB
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB These layering concept allows to build hierarchical constructs so its easy to maintain
them.
RVM Ethernet sample

Specman E
Boolean Expressions:
Interview Questions
Boolean expression doesn't consume time. The result of the expression is 1,0,x & z. If
the result is 1, then the expression is true , else if the expression is 0,x or z , it is
false. Concurrent assertions use boolean expressions along with temporal expressions.
Immediate assertions use only boolean expressions.

Integral data types such as int,integer,reg,bit,byte,logic,array( elements


only),structs,function return values are allowed in boolean expressions. Complex data
types like classes,smart quesus, dynamic arrays, associative arrays are not allowed.

http://testbench.in/AS_05_CONCURRENT_ASSERTION_LAYERS.html[9/26/2012 2:16:39 PM]


WWW.TESTBENCH.IN - System Verilog Assertion - SVA

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/AS_05_CONCURRENT_ASSERTION_LAYERS.html[9/26/2012 2:16:39 PM]


WWW.TESTBENCH.IN - System Verilog Assertion - SVA

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS SEQUENCES Index


Introduction
SystemVerilog Event Simulation
Verification Boolean logic doenot have the concept of time. Temporal logic is boolean logic with Assertion Types
time as one more dimention. Sequence allows us to define temporal nature of the Assertion System Tasks
Constructs signals using temporal expressions. Concurrent Assertion
Interface Layers
Sequences can be composed by concatenation, analogous to a concatenation of lists. Sequences
OOPS Properties
The concatenation specifies a delay, using ##, from the end of the first sequence until
Randomization the beginning of the second sequence. Verification Directive
## indicates cycle delay.
Functional Coverage Report a Bug or Comment
Assertion on This section - Your
input is what keeps
DPI Testbench.in improving
Fixed Delay:
UVM Tutorial with time!
VMM Tutorial A ## followed by a number specifies the delay from the current clock tick to the
beginning of the sequence that follows.
OVM Tutorial
Easy Labs : SV EXAMPLE:
req ##2 gnt
Easy Labs : UVM
Easy Labs : OVM This specifies that req shall be true on the current clock tick, and gnt shall be true on
the second subsequent clock tick
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

Verilog
Verification
Verilog Switch TB
Basic Constructs

Zero Delay:
OpenVera
Constructs The delay ##0 indicates that the beginning of the second sequence is at the same
Switch TB clock tick as the end of the first sequence. This can also be archived using boolean
expressions && .
RVM Switch TB
RVM Ethernet sample EXAMPLE:
sig1 ##0 sig2

Specman E This specifies that sig1 shall be true on the current clock tick, and sig2 shall be true
Interview Questions on the same clock tick.

http://testbench.in/AS_06_SEQUENCES.html[9/26/2012 2:16:48 PM]


WWW.TESTBENCH.IN - System Verilog Assertion - SVA

Constant Range Delay:

A ##[n:m] followed by a range specifies the delay from the current clock tick to the
beginning of the sequence that follows.

EXAMPLE:
req ##[2:5] ack

This specifies that ack shall be true ,2-5 cycles after req. It creates multiple
subsequence threads. This resulst in multiple hits or fails.
Sub sequences created by range delay in above expressions:
 req ##2 ack
 req ##3 ack
 req ##4 ack
 req ##5 ack

Unbounded Delay Range:

The $ token is used to indicate the end of simulation.


##[n:$] specifies that delay from between n cycles later and till the end of
simulation.

EXAMPLE:
req##[4:$] ack;

This specifies that ack must be true atleast 4 cycles later .

Repetation Operators:

The number of iterations of a repetition can either be specified by exact count or be

http://testbench.in/AS_06_SEQUENCES.html[9/26/2012 2:16:48 PM]


WWW.TESTBENCH.IN - System Verilog Assertion - SVA

required to fall within a finite range. If specified by exact count, then the number of
iterations is defined by a non-negative integer constant expression. If required to fall
within a finite range, then the minimum number of iterations is defined by a non-
negative integer constant expression; and the maximum number of iterations either is
defined by a non-negative integer constant expression or is $, indicating a finite, but
unbounded, maximum.

Consecutive Repetition:

Consecutive repetition specifies finitely many iterative matches of the operand


sequence, with a delay of one clock tick from the end of one match to the beginning
of the next. The overall repetition sequence matches at the end of the last iterative
match of the operand.

EXAMPLE:
REQ[*4]

This example specifies that ack shell come after req comes 4 times consecutively.

Goto Repetition :

Goto repetition specifies finitely many iterative matches of the operand boolean
expression, with a delay of one or more clock ticks from one match of the operand to
the next successive match and no match of the operand strictly in between. The
overall repetition sequence matches at the last iterative match of the operand.

EXAMPLE:
req[->3]##1 ack

This example specifies that ack shell come after req comes 3 times with no gap
between thw last req and ack.

Nonconsecutive Repetition:

Nonconsecutive repetition specifies finitely many iterative matches of the operand


boolean expression, with a delay of one or more clock ticks from one match
of the operand to the next successive match and no match of the operand strictly in
between. The overall repetition sequence matches at or after the last iterative match
of the operand, but before any later match of the operand.

EXAMPLE:
req[=3]##1 ack

This example specifies that ack shell come after req comes 4 times with gap between
thw last req and ack.

http://testbench.in/AS_06_SEQUENCES.html[9/26/2012 2:16:48 PM]


WWW.TESTBENCH.IN - System Verilog Assertion - SVA

Sequence And :

Sequence must start and can end at the any time. Match is done after last sequence is
ended.

EXAMPLE:
Seq1 and seq2

Sequence Or:

Sequence must start at the same time and can end at any time. Match is done at both
the sequences ends.

EXAMPLE:
seq1 or seq2

Sequence Intersect:

sequences must start at the same time and end at same tine. Match is done at the end
time.

EXAMPLE:
Seq1 intersect seq2

http://testbench.in/AS_06_SEQUENCES.html[9/26/2012 2:16:48 PM]


WWW.TESTBENCH.IN - System Verilog Assertion - SVA

Sequence Within

One sequence can fully contain another sequence

EXAMPLE:
Seq1 within seq2

Sequence First_match:

Matches only the first match and ignores other matches.

EXAMPLE:
first_match(seq1)

Sequence Throughout

The throughout operator requires a boolean to be true throughout a sequence.

EXAMPLE:
A throughout seq1

http://testbench.in/AS_06_SEQUENCES.html[9/26/2012 2:16:48 PM]


WWW.TESTBENCH.IN - System Verilog Assertion - SVA

Sequence Ended:

The end point of a sequence is reached whenever the ending clock tick of a match of
the sequence is reached, regardless of the starting lock tick of the match. The
reaching of the end point can be tested by using the method ended.

EXAMPLE:
sequence e1;
@(posedge sysclk) $rose(ready) ##1 proc1 ##1 proc2 ;
endsequence
sequence rule;
@(posedge sysclk) reset ##1 inst ##1 e1.ended ##1 branch_back;
endsequence

Operator Precedence Associativy:

Operator precedence and associativity are listed in the following Table . The highest
precedence is listed first.

        

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/AS_06_SEQUENCES.html[9/26/2012 2:16:48 PM]


WWW.TESTBENCH.IN - System Verilog Assertion - SVA

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PROPERTIES Index


Introduction
SystemVerilog Event Simulation
Verification A property defines a behavior of the design. A property can be used for verification as Assertion Types
an assumption, a checker, or a coverage specification. Assertion System Tasks
Constructs Sequences are often used to construct properties. usage of sequences in properties Concurrent Assertion
Interface brakes down the complexity. Sequence can be reused across various properties. Layers
Sequences
OOPS Properties
A property can be declared in any of the following:
Randomization  A module Verification Directive
 An interface
Functional Coverage Report a Bug or Comment
 A program
Assertion  A clocking block on This section - Your
 A package input is what keeps
DPI Testbench.in improving
 A compilation-unit scope
UVM Tutorial with time!
VMM Tutorial
Properties constructs:
OVM Tutorial Disable iff
Easy Labs : SV Implication (if ..else)
overlapping implication (|->)
Easy Labs : UVM Non overlapping implication(||->)
Easy Labs : OVM not
Easy Labs : VMM
AVM Switch TB
EXAMPLE:
VMM Ethernet sample property rule6_with_type(bit x, bit y);
     ##1 x   |->   ##[2:10] y;
//antecedent |->   consequent
Verilog endproperty
Verification
Verilog Switch TB The left-hand operand sequence_expr is called the antecedent, while the right-hand
Basic Constructs operand property_expr is called the consequent.

if antecedent is false, then consequent is not cared and property is considered as


vacuous success.
OpenVera if antecedent is True and if consequent is false then property is considered as false.
Constructs if antecedent is True and if consequent is true then property is considered as true.
Switch TB
RVM Switch TB
RVM Ethernet sample
Overlap Implication:

Consequent expression is evaluated on the same clock of antecedent.


Specman E
Interview Questions
EXAMPLE:
a |-> b

http://testbench.in/AS_07_PROPERTIES.html[9/26/2012 2:16:58 PM]


WWW.TESTBENCH.IN - System Verilog Assertion - SVA

Non Overlapping Implication

Consequent expression is evaluated on the next clock of antecedent

EXAMPLE:
a ||-> b

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/AS_07_PROPERTIES.html[9/26/2012 2:16:58 PM]


WWW.TESTBENCH.IN - System Verilog Assertion - SVA

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS VERIFICATION DIRECTIVE Index


Introduction
SystemVerilog Event Simulation
Verification A property on its own is never evaluated for checking an expression. It must be used Assertion Types
within a verification statement for this to occur. A verification statement states the Assertion System Tasks
Constructs verification function to be performed on the property. Concurrent Assertion
Interface          Layers
The statement can be one of the following: Sequences
OOPS
1)assert to specify the property as a checker to ensure that the property holds for the Properties
Randomization design Verification Directive
2)assume to specify the property as an assumption for the environment
Functional Coverage Report a Bug or Comment
3)cover to monitor the property evaluation for coverage
Assertion on This section - Your
input is what keeps
DPI Testbench.in improving
A concurrent assertion statement can be specified in any of the following:
UVM Tutorial 1) An always block or initial block as a statement, wherever these blocks can appear with time!
VMM Tutorial 2) A module
3) An interface
OVM Tutorial 4) A program
Easy Labs : SV
Easy Labs : UVM Assert:
Easy Labs : OVM
The assert statement is used to enforce a property as a checker. When the property
Easy Labs : VMM for the assert statement is evaluated to be true, the pass statements of the action
AVM Switch TB block are executed. Otherwise, the fail statements of the action_block are executed.
VMM Ethernet sample
EXAMPLE:
a1_assertion:assert property ( @(posedge clk) req inside {0, 1} ) ;
Verilog property proto_assertion ;
Verification @(posedge clk) req |-> req[*1:$] ##0 ack;
endproperty
Verilog Switch TB
Basic Constructs Assume:

The environment must be constrained so that the properties that are assumed shall
hold. Like an assert property, an assumed property must be checked and reported if
OpenVera it fails to hold. There is no requirement on the tools to report successes of the
Constructs assumed properties.
Switch TB
RVM Switch TB EXAMPLE:
RVM Ethernet sample a1:assume property ( @(posedge clk) req dist {0:=40, 1:=60} ) ;
property proto ;
@(posedge clk) req |-> req[*1:$] ##0 ack;
endproperty
Specman E
Interview Questions Cover Statement:

To monitor sequences and other behavioral aspects of the design for coverage, the
same syntax is used with the cover statement. The tools can gather information about
the evaluation and report the results at the end of simulation. When the property for
the cover statement is successful, the pass statements can specify a coverage
function, such as monitoring all paths for a sequence. The pass statement shall not
include any concurrent assert, assume, or cover statement.
        
Coverage results are divided into two categories: coverage for properties and
coverage for sequences.

http://testbench.in/AS_08_VERIFICATION_DIRECTIVE.html[9/26/2012 2:17:07 PM]


WWW.TESTBENCH.IN - System Verilog Assertion - SVA

Coverage for sequences:


 Number of attempts
 Number of matches
 Multiple matches per attempt are all counted

Coverage for properties:


 Number of attempts
 Number of passes
 Number of vacuous passes
 Number of failures

Expect Statement:

The expect statement is a procedural blocking statement that allows waiting on a


property evaluation. The syntax of the expect statement accepts a named property or
a property declaration. The expect statement accepts the same syntax used to assert
a property. An expect statement causes the executing process to block until the given
property succeeds or fails. The statement following the expect is scheduled to
execute after processing the Observe region in which the property completes its
evaluation. When the property succeeds or fails, the process unblocks, and the
property stops being evaluated

EXAMPLE:
program tst;
initial begin
# 200ms;
expect( @(posedge clk) a ##1 b ##1 c ) else $error( "expect failed" );
ABC: ...
end
endprogram

Binding:

To facilitate verification separate from design, it is possible to specify properties and


bind them to specific modules or instances. The following are some goals of providing
this feature:
 It allows verification engineers to verify with minimum changes to the design code
and files.
 It allows a convenient mechanism to attach verification intellectual Protocol (VIP) to
a module or an instance.
 No semantic changes to the assertions are introduced due to this feature. It is
equivalent to writing properties external to a module, using hierarchical path names.

The bind directive can be specified in any of the following:


 A module
 An interface
 A compilation-unit scope

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/AS_08_VERIFICATION_DIRECTIVE.html[9/26/2012 2:17:07 PM]


WWW.TESTBENCH.IN - System Verilog Assertion - SVA

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/AS_08_VERIFICATION_DIRECTIVE.html[9/26/2012 2:17:07 PM]


WWW.TESTBENCH.IN - Systemverilog DPI

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INTRODUCTIONS Index


Introductions
SystemVerilog What Is Dpi-C ? Layers
Verification Import
From long time , Users have needes a simple way of communication to foreign Naming
Constructs languages from verilog. VPI and PLI are not easy interfaces to Use . Users need Export
Interface detailed knowledge of PLI and VPI even for a simple program. Most of the time, users Pure And Context
do not need the sophisticated capabilities of VPI and PLI. DPI also permits C/C++ code Data Types
OOPS Arrays
to wait for Verilog events and C/C++ tasks and functions can be disabledfrom
Randomization SystemVerilog. Passing Structs And
SystemVerilog introduces a new foreign language interface called the Direct Unions
Functional Coverage Arguments Type
Programming Interface (DPI). The DPI provides a very simple, straightforward, and
Assertion efficient way to connect SystemVerilog and foreign language code unlike PLI or VPI.   Disablie
DPI Report a Bug or Comment
DPI developed based on the donations from Synopsys "DirectC interface".
UVM Tutorial on This section - Your
VMM Tutorial DPI consists of two separate layers: the SystemVerilog layer and a foreign language input is what keeps
layer. Both sides of DPI-C are fully isolated. Which programming language is actually Testbench.in improving
OVM Tutorial used as the foreign language is transparent and irrelevant for the System-Verilog side with time!
Easy Labs : SV of this interface. Neither the SystemVerilog compiler nor the foreign language
compiler is required to analyze the source code in the others language. Different
Easy Labs : UVM programming languages can be used and supported with the same intact
Easy Labs : OVM SystemVerilog layer.
Easy Labs : VMM DPI-C follows the principle of a black box: the specification and the implementation
AVM Switch TB of a component are clearly separated, and the actual implementation is transparent
to the rest of the system. Therefore, the actual programming language of the
VMM Ethernet sample implementation is also transparent, although this standard defines only C linkage
semantics. The separation between SystemVerilog code and the foreign language is
based on using functions as the natural encapsulation unit in SystemVerilog.
Verilog
Verification
Verilog Switch TB
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/DP_01_INTRODUCTIONS.html[9/26/2012 2:17:14 PM]


WWW.TESTBENCH.IN - Systemverilog DPI

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/DP_01_INTRODUCTIONS.html[9/26/2012 2:17:14 PM]


WWW.TESTBENCH.IN - Systemverilog DPI

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS LAYERS Index


Introductions
SystemVerilog Two Layers Of Dpi-C Layers
Verification Import
DPI-C consists of two separate layers: the SystemVerilog layer and a foreign language Naming
Constructs layer. The SystemVerilog layer does not depend on which programming language is Export
Interface actually used as the foreign language. Although different programming languages can Pure And Context
be supported and used with the intact SystemVerilog layer, SystemVerilog defines a Data Types
OOPS Arrays
foreign language layer only for the C programming language. Nevertheless,
Randomization SystemVerilog code shall look identical and its semantics shall be unchanged for any Passing Structs And
foreign language layer. Unions
Functional Coverage Arguments Type
Assertion Disablie
DPI Dpi-C Systemverilog Layer
Report a Bug or Comment
UVM Tutorial on This section - Your
VMM Tutorial The SystemVerilog side of DPI-C does not depend on the foreign programming input is what keeps
language. In particular, the actual function call protocol and argument passing Testbench.in improving
OVM Tutorial mechanisms used in the foreign language are transparent and irrelevant to with time!
Easy Labs : SV SystemVerilog. SystemVerilog code shall look identical regardless of what code the
foreign side of the interface is using. The semantics of the SystemVerilog side of the
Easy Labs : UVM interface is independent from the foreign side of the interface.
Easy Labs : OVM
The SystemVerilog DPI-C allows direct inter-language function calls between
Easy Labs : VMM SystemVerilog and any foreign programming language with a C function call protocol
AVM Switch TB and linking model:
VMM Ethernet sample
Functions implemented in C and given import declarations in SystemVerilog can be
called from SystemVerilog; such functions are referred to as imported functions.

Verilog Functions implemented in SystemVerilog and specified in export declarations can


Verification be called from C; such functions are referred to as exported functions.
Verilog Switch TB
Tasks implemented in SystemVerilog and specified in export declarations can be
Basic Constructs called from C; such functions are referred to as exported tasks.

Functions implemented in C that can be called from SystemVerilog and can in turn
OpenVera call exported tasks; such functions are referred to as imported tasks.
Constructs
Switch TB Dpi-C Foreign Language Layer
RVM Switch TB
The foreign language layer of the interface (which is transparent to SystemVerilog)
RVM Ethernet sample shall specify how actual arguments are passed, how they can be accessed from the
foreign code, how SystemVerilog-specific data types (such as logic and packed) are
represented, and how they are translated to and from some predefined C-like types.
Specman E
Interview Questions

http://testbench.in/DP_02_LAYERS.html[9/26/2012 2:17:22 PM]


WWW.TESTBENCH.IN - Systemverilog DPI

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/DP_02_LAYERS.html[9/26/2012 2:17:22 PM]


WWW.TESTBENCH.IN - Systemverilog DPI

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS IMPORT Index


Introductions
SystemVerilog Import Methods Layers
Verification Import
Methods implemented in C and given import declarations in SystemVerilog can be Naming
Constructs called from SystemVerilog, such methods are referred to as imported Export
Interface methods.Imported tasks or functions are similar to SystemVerilog tasks or functions. Pure And Context
Imported tasks or functions can have zero or more formal input, output, and inout Data Types
OOPS Arrays
arguments.
Randomization Imported tasks always return an int result as part of the DPI-C disable protocol and, Passing Structs And
thus, are declared in foreign code as int functions. We will discusses about the DPI-C Unions
Functional Coverage Arguments Type
disable protocol in following sections.
Assertion Imported functions can return a result or be defined as void functions. Disablie
DPI Report a Bug or Comment
The syntax import method:
UVM Tutorial on This section - Your
import {"DPI" | "DPI-C"} [context | pure] [c_identifier input is what keeps
VMM Tutorial
=] [function|task] [function_identifier|task_identifier] ([tf_port_list]); Testbench.in improving
OVM Tutorial with time!
Easy Labs : SV Steps To Write Import Metyhods
Easy Labs : UVM In SV Code
Easy Labs : OVM Step1 : Import the C function
Easy Labs : VMM
   import "DPI-C" string_sv2c=task string_sv2c();
AVM Switch TB
VMM Ethernet sample Step2 :  Invoke the Importted C function

   initial
   begin
Verilog        string_sv2c();
Verification    end
Verilog Switch TB
In C code:
Basic Constructs Step3: Define the Imported function

   void string_sv2c(){
OpenVera         printf(" C: Hellow from C ");
   }
Constructs
Switch TB
RVM Switch TB Full Example:

RVM Ethernet sample CODE: SV_file


   program main;
       string str;
Specman E       
       import "DPI-C" string_sv2c=task string_sv2c();
Interview Questions       
       initial
       begin
            string_sv2c();
       end
      
   endprogram

CODE: C_file
     #include "svdpi.h"

http://testbench.in/DP_03_IMPORT.html[9/26/2012 2:17:29 PM]


WWW.TESTBENCH.IN - Systemverilog DPI

    
     void string_sv2c(){
          printf(" C: Hellow from C ");
     }

RESULTS

C: Hellow from C

EXAMPLE: optional default arguments

Standard C Functions

Users can also call the standared C functions.

EXAMPLE:
    import "DPI" function chandle malloc(int size); 
    import "DPI" function void free(chandle ptr); 

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/DP_03_IMPORT.html[9/26/2012 2:17:29 PM]


WWW.TESTBENCH.IN - Systemverilog DPI

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS NAMING Index


Introductions
SystemVerilog Global Name Layers
Verification Import
Every task or function imported to SystemVerilog must eventually resolve to a global Naming
Constructs symbol. Similarly, every task or function exported from SystemVerilog defines a global Export
Interface symbol. Global names of imported and exported tasks and functions must be unique Pure And Context
(no overloading is allowed ) and shall follow C conventions for naming; specifically, Data Types
OOPS Arrays
such names must start with a letter or underscore, and they can be followed by
Randomization alphanumeric characters or underscores. Passing Structs And
Unions
Functional Coverage Arguments Type
Assertion EXAMPLE Disablie
DPI   export "DPI-C" foo_plus = function \foo+ ; // "foo+" exported as "foo_plus"
  import "DPI-C" init_1 = function void \init[1] (); // "init_1" is a linkage name Report a Bug or Comment
UVM Tutorial on This section - Your
Local Name input is what keeps
VMM Tutorial
Testbench.in improving
OVM Tutorial If a global name is not explicitly given, it shall be the same as the SystemVerilog task with time!
Easy Labs : SV or function name.
Easy Labs : UVM EXAMPLE:
Easy Labs : OVM   export "DPI-C" function foo; 
Easy Labs : VMM Sv Keyword As Linkage Name
AVM Switch TB
If a C method is named same as the SystemVerilog Keyword, then use a leading
VMM Ethernet sample backslash ( \ ) character to create the linkage identifier.

EXAMPLE:
Verilog   import "DPI-C" \begin = function void \init[2] (); // "begin" is a linkage name
Verification
Verilog Switch TB
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/DP_04_NAMING.html[9/26/2012 2:17:37 PM]


WWW.TESTBENCH.IN - Systemverilog DPI

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/DP_04_NAMING.html[9/26/2012 2:17:37 PM]


WWW.TESTBENCH.IN - Systemverilog DPI

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS EXPORT Index


Introductions
SystemVerilog Export Methods Layers
Verification Import
Methods implemented in SystemVerilog and specified in export declarations can be Naming
Constructs called from C, such methods are referred to as exported methods. Export
Interface Pure And Context
Data Types
OOPS Arrays
Steps To Write Export Methods
Randomization Passing Structs And
In SV Code : Unions
Functional Coverage Arguments Type
Setp1: Export the systemverilog function
Assertion Disablie
DPI   export "DPI-C" function export_func;
Report a Bug or Comment
UVM Tutorial on This section - Your
Step2: Define the systemverilog function
input is what keeps
VMM Tutorial
Testbench.in improving
  function void export_func();
OVM Tutorial with time!
      $display("SV: Hello from SV ");
Easy Labs : SV   endfunction
Easy Labs : UVM
Easy Labs : OVM In C code :
Easy Labs : VMM Step3: Export the Systemverilog function
AVM Switch TB    extern void export_func(void);
VMM Ethernet sample

Step4: Invoke the systemverilog function


Verilog
   void import_func()
Verification    {
Verilog Switch TB        export_func();
   }
Basic Constructs

Full Example:
OpenVera
Constructs
CODE: SV_file.sv
Switch TB     program main;
RVM Switch TB     
        export "DPI-C" function export_func;
RVM Ethernet sample         import "DPI-C" function void import_func();
        
        function void export_func();
Specman E              $display("SV: Hello from SV ");
        endfunction
Interview Questions         
        initial 
        begin
           import_func();
        end
    
    endprogram

CODE: C_file.c
    #include "stdio.h"

http://testbench.in/DP_05_EXPORT.html[9/26/2012 2:17:44 PM]


WWW.TESTBENCH.IN - Systemverilog DPI

    #include "vc_hdrs.h"
    #include "svdpi.h"
    
    extern void export_func(void);
    
    void import_func()
    {
          export_func();
    }

RESULTS:

SV: Hello from SV

Blocking Export Dpi Task

SV Dpi allows C to call a SystemVerilog method which consumes time.

CODE:SV_file.sv
     program main;
    
         export "DPI-C" task export_task;
         import "DPI-C" context task import_task();
        
         task export_task();
             $display("SV: Entered the export function . wait for some time : %0d
",$time);
             #100;
             $display("SV: After waiting %0d",$time); 
         endtask
        
         initial
         begin
            $display("SV: Before calling import function %0d",$time);
            import_task();
            $display("SV: After  calling import function %0d",$time);
         end
    
     endprogram 
CODE: C_file.c
    extern void export_task();
    
    void import_task()
    {
        printf(" C: Before calling export function\n");
        export_task();
        printf(" C: After  calling export function\n");
    } 
RESULTS

SV: Before calling import function 0


 C: Before calling export function
SV: Entered the export function . wait for some time : 0
SV: After waiting 100
 C: After  calling export function
SV: After  calling import function 100

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/DP_05_EXPORT.html[9/26/2012 2:17:44 PM]


WWW.TESTBENCH.IN - Systemverilog DPI

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/DP_05_EXPORT.html[9/26/2012 2:17:44 PM]


WWW.TESTBENCH.IN - Systemverilog DPI

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PURE AND CONTEXT Index


Introductions
SystemVerilog Pure Function Layers
Verification Import
A function whose result depends solely on the values of its input arguments and with Naming
Constructs no side effects can be specified as pure. This can usually allow for more optimizations Export
Interface and thus can result in improved simulation performance. Pure And Context
Data Types
OOPS Arrays
A pure function call can be safely eliminated if its result is not needed or if the
Randomization previous result for the same values of input arguments is available somehow and can Passing Structs And
be reused without needing to recalculate. Only nonvoid functions with no output or Unions
Functional Coverage Arguments Type
inout arguments can be specified as pure.
Assertion Disablie
DPI Specifically, a pure function is assumed not to directly or indirectly (i.e., by calling
other functions) perform the following: Report a Bug or Comment
UVM Tutorial Perform any file operations. on This section - Your
input is what keeps
VMM Tutorial Read or write anything in the broadest possible meaning, including input/output,
Testbench.in improving
environment variables, objects from the operating system or from the program or
OVM Tutorial with time!
other processes, shared memory, sockets, etc.
Easy Labs : SV Access any persistent data, like global or static variables.
Easy Labs : UVM
Easy Labs : OVM Context Function
Easy Labs : VMM
Some DPI imported tasks or functions or other interface functions called from them
AVM Switch TB require that the context of their call be known. The SystemVerilog context of DPI
VMM Ethernet sample export tasks and functions must be known when they are called, including when they
are called by imports. When an import invokes the svSetScope utility prior to calling
the export, it sets the context explicitly. Otherwise, the context will be the context
of the instantiated scope where the import declaration is located.
Verilog
Verification
Verilog Switch TB CODE: SV_file_1.sv
   module module_1;
Basic Constructs   
       import "DPI-C" context function void import_func();
       export "DPI-C" function export_func;
OpenVera       
       module_2 instance_1();
Constructs
      
Switch TB        initial 
RVM Switch TB            import_func();
      
RVM Ethernet sample        function void export_func();
           $display("SV: My scope is %m \n");
       endfunction
Specman E       
   endmodule 
Interview Questions
CODE: SV_file_2.sv
   module module_2;
  
   import "DPI-C" context function void import_func();
   export "DPI-C" function export_func;
  
   initial
       import_func();
  
   function void export_func();

http://testbench.in/DP_06_PURE_AND_CONTEXT.html[9/26/2012 2:17:52 PM]


WWW.TESTBENCH.IN - Systemverilog DPI

       $display("SV: My Scope is %m \n");


   endfunction
  
   endmodule 
CODE:C_file.c

   #include "svdpi.h"
   #include "stdio.h"
  
   extern void export_func(void);
    
   void import_func()
   {
        printf(" C: Im called fronm Scope ::   %s \n\n
",svGetNameFromScope(svGetScope() ));
        
        export_func();
   }

RESULTS

 C: Im called fronm Scope ::   module_1.instance_1

 SV: My Scope is module_1.instance_1.export_func

 C: Im called fronm Scope ::   module_1

 SV: My scope is module_1.export_func

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/DP_06_PURE_AND_CONTEXT.html[9/26/2012 2:17:52 PM]


WWW.TESTBENCH.IN - Systemverilog DPI

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS DATA TYPES Index


Introductions
SystemVerilog Layers
Verification The SystemVerilog DPI supports only SystemVerilog data types, which are the data Import
types that can cross the boundary between SystemVerilog and a foreign language in Naming
Constructs both the direction. On the other hand, the data types used in C code shall be C types. Export
Interface A value that is passed through the DPI is specified in SystemVerilog code as a value of Pure And Context
SystemVerilog data type, while the same value is declared C code as a value of C data Data Types
OOPS Arrays
type. Therefore, a pair of matching type definitions is required to pass a value
Randomization through DPI, the SystemVerilog definition and the C definition. Passing Structs And
Unions
Functional Coverage Arguments Type
The following SystemVerilog types are the only permitted types for formal arguments
Assertion of import and export tasks or functions: Disablie
DPI Report a Bug or Comment
void, byte, shortint, int, longint, real, shortreal, chandle, and string
UVM Tutorial on This section - Your
Scalar values of type bit and logic
input is what keeps
VMM Tutorial Packed arrays, structs, and unions composed of types bit and logic. Every packed Testbench.in improving
OVM Tutorial type is eventually equivalent to a packed one-dimensional array. On the foreign with time!
language side of the DPI, all packed types are perceived as packed one-dimensional
Easy Labs : SV arrays regardless of their declaration in the SystemVerilog code.
Easy Labs : UVM Enumeration types interpreted as the type associated with that enumeration
Types constructed from the supported types with the help of the constructs: struct
Easy Labs : OVM
, union , Unpacked array , typedef
Easy Labs : VMM
AVM Switch TB
Mapping data types

VMM Ethernet sample

Verilog
Verification
Verilog Switch TB
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Passing Logic Datatype
Interview Questions
The DPI defines the canonical representation of packed 2-state (type svBitVecVal) and
4-state arrays (type svBitVecVal). svLogicVecVal is fully equivalent to type
s_vpi_vecval, which is used to represent 4-state logic in VPI.

http://testbench.in/DP_07_DATA_TYPES.html[9/26/2012 2:18:00 PM]


WWW.TESTBENCH.IN - Systemverilog DPI

CODE:SV_file.sv
    program main;
      logic a;
      import "DPI" function void show(logic a);
         initial begin
            a = 1'b0;
            show(a);
            a = 1'b1;
            show(a);
            a = 1'bX;
            show(a);
            a = 1'bZ;
            show(a);
          end
    endprogram
    
CODE: C_file.v
    #include <stdio.h>
    #include <svdpi.h>
    
    void show(svLogic a){
       if(a == 0)
        printf(" a is 0 \n"); 
       else if(a == 1)
        printf(" a is 1 \n"); 
       else if(a == 2)
        printf(" a is x \n"); 
       else if(a == 3)
        printf(" a is z \n"); 
    
    }
RESULTS

 a is 0
 a is 1
 a is z
 a is x

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/DP_07_DATA_TYPES.html[9/26/2012 2:18:00 PM]


WWW.TESTBENCH.IN - Systemverilog DPI

http://testbench.in/DP_07_DATA_TYPES.html[9/26/2012 2:18:00 PM]


WWW.TESTBENCH.IN - Systemverilog DPI

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS ARRAYS Index


Introductions
SystemVerilog Open Arrays Layers
Verification Import
The size of the packed dimension, the unpacked dimension, or both dimensions can Naming
Constructs remain unspecified,such cases are referred to as open arrays (or unsized arrays). Export
Interface Open arrays allow the use of generic code to handle different sizes. Formal arguments Pure And Context
in SystemVerilog can be specified as open arrays solely in import declarations, Data Types
OOPS Arrays
exported. SystemVerilog functions cannot have formal arguments specified as open
Randomization arrays. Passing Structs And
Unions
Functional Coverage Arguments Type
OpenArrays are good for generic programming, since C language doesn't have concept
Assertion of parameterizable arguments. Standared query and library functions are provided to Disablie
DPI determine array information to acess array elements.
Report a Bug or Comment
UVM Tutorial on This section - Your
EXAMPLE: open arrays input is what keeps
VMM Tutorial
Testbench.in improving
OVM Tutorial CODE:SV_file.sv with time!
Easy Labs : SV
      program main;
Easy Labs : UVM       
Easy Labs : OVM            int fxd_arr_1[8:3];  
           int fxd_arr_2[12:1];  
Easy Labs : VMM           
AVM Switch TB            import "DPI-C" context function void pass_array(input int dyn_arr[] );
          
VMM Ethernet sample            initial
           begin
              for (int i = 3; i<=8 ; i++)
Verilog               begin
Verification                    fxd_arr_1[i] = $random() ;  
                 $display("SV:fxd_arr_1  %0d %d ",i, fxd_arr_1[i] );
Verilog Switch TB               end
Basic Constructs           
              $display("\n Passing fxd_arr_1 to C \n");
              pass_array( fxd_arr_1 );
            
OpenVera               for (int i = 1; i<=12 ; i++)
Constructs               begin
Switch TB                    fxd_arr_2[i] = $random() ;  
                   $display("SV: fxd_arr_2 %0d %d ",i, fxd_arr_2[i] );
RVM Switch TB               end
RVM Ethernet sample           
              $display("\n Passing fxd_arr_2 to C \n");
              pass_array( fxd_arr_2 );  
           end
Specman E       endprogram
Interview Questions
CODE: C_file.c

      #include <stdio.h>
      #include <svdpi.h>
      
      void pass_array(const svOpenArrayHandle dyn_arr ) {  
        int i;
        
        printf("Array Left %d, Array Right %d
\n\n", svLeft(dyn_arr,1), svRight(dyn_arr, 1) );

http://testbench.in/DP_08_ARRAYS.html[9/26/2012 2:18:08 PM]


WWW.TESTBENCH.IN - Systemverilog DPI

        for (i= svRight(dyn_arr,1); i <= svLeft(dyn_arr,1); i++) {
             printf("C: %d %d \n", i,  *(int*)svGetArrElemPtr1(dyn_arr, i) );
        }
        printf("\n\n");
      
      }

RESULTS:

SV:fxd_arr_1  3   303379748
SV:fxd_arr_1  4 -1064739199
SV:fxd_arr_1  5 -2071669239
SV:fxd_arr_1  6 -1309649309
SV:fxd_arr_1  7   112818957
SV:fxd_arr_1  8  1189058957

 Passing fxd_arr_1 to C

Array Left 8, Array Right 3

C: 3 303379748
C: 4 -1064739199
C: 5 -2071669239
C: 6 -1309649309
C: 7 112818957
C: 8 1189058957

SV: fxd_arr_2 1 -1295874971


SV: fxd_arr_2 2 -1992863214
SV: fxd_arr_2 3    15983361
SV: fxd_arr_2 4   114806029
SV: fxd_arr_2 5   992211318
SV: fxd_arr_2 6   512609597
SV: fxd_arr_2 7  1993627629
SV: fxd_arr_2 8  1177417612
SV: fxd_arr_2 9  2097015289
SV: fxd_arr_2 10  -482925370
SV: fxd_arr_2 11  -487095099
SV: fxd_arr_2 12  -720121174

 Passing fxd_arr_2 to C

Array Left 12, Array Right 1

C: 1 -1295874971
C: 2 -1992863214
C: 3 15983361
C: 4 114806029
C: 5 992211318
C: 6 512609597
C: 7 1993627629
C: 8 1177417612
C: 9 2097015289
C: 10 -482925370
C: 11 -487095099
C: 12 -720121174

Packed Arrays

A packed array is represented as an array of one or more elements (of type


svBitVecVal for 2-state values and svLogicVecVal for 4-state values), each element
representing a group of 32 bits.

CODE:SV_file.sv
      program main;

http://testbench.in/DP_08_ARRAYS.html[9/26/2012 2:18:08 PM]


WWW.TESTBENCH.IN - Systemverilog DPI

           import "DPI-C" function void get_nums(output logic [15:0] nums[10]);

           logic [15:0] nums[10];

           initial begin
               get_nums(nums);
               foreach (nums[i]) $display(i,nums[i]);
           end
      endprogram

CODE:C_file.c
      #include "svdpi.h"

      void fib(svLogicVecVal nums[10]) {
          int i;
          for (i=0; i<10; i++) {
              nums[i] = i ;
          }
      }

RESULTS:

0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9

Linearized And Normalized


Arrays use normalized ranges for the packed [n-1:0] and the unpacked part [0:n-1]

For example, if SV code defines an array as follows:

logic [2:3][1:3][2:0] b [1:10][31:0];

Then C code would see it as defined like this:

logic [17:0] b [0:9][0:31];

Array Querying Functions

svLeft()   shall return the left bound (MSB) of the dimension.

svRight() shall return the right bound (LSB) of the dimension.

svLow() shall return the minimum of left index and right index of the dimension.

svHigh() shall return the maximum of left index and right index of the dimension.

svIncrement() shall return 1 if left index is greater than or equal to right index and
-1 if left index is less than right index.

svLength() shall return the number of elements in the dimension, which is


equivalent to high index - low index + 1.

svDimensions() shell return  total number of dimensions in the array

CODE: SV_file.sv
    program main;
    
        int fxd_arr_1[8:3];  
        int fxd_arr_2[1:13];  

http://testbench.in/DP_08_ARRAYS.html[9/26/2012 2:18:08 PM]


WWW.TESTBENCH.IN - Systemverilog DPI

        
        import "DPI-C" context function void pass_array(input int dyn_arr[] );
        
        initial
        begin
             $display("\n Passing fxd_arr_1 to C \n");
             pass_array( fxd_arr_1 );
             $display("\n Passing fxd_arr_2 to C \n");
             pass_array( fxd_arr_2 );  
        end
        
    endprogram
CODE: C_file.c
    #include <stdio.h>
    #include <svdpi.h>
    
    void pass_array(const svOpenArrayHandle dyn_arr ) {  
          printf("Array Pointer is %x \n", svGetArrayPtr(dyn_arr) );
          printf(" Lower  index %d \n",    svLow(dyn_arr,1));
          printf(" Higher index %d \n",    svHigh(dyn_arr, 1) );
          printf(" Left   index %d \n",    svLeft(dyn_arr,1), svRight(dyn_arr, 1) );
          printf(" Right  index %d \n",    svRight(dyn_arr, 1) );
          printf(" Length of array %d \n", svLength(dyn_arr,1) ); 
          printf(" Incremental %d \n",svIncrement(dyn_arr,1));
          printf("Dimentions of Array %d \n", svDimensions(dyn_arr )); 
          printf("Size of Array in bytes %d \n", svSizeOfArray(dyn_arr)  );  
    }

RESULTS:

 Passing fxd_arr_1 to C

Array Pointer is 80fdc58


 Lower  index 3
 Higher index 8
 Left   index 8
 Right  index 3
 Length of array 6
 Incremental 1
Dimentions of Array 1
Size of Array in bytes 24

 Passing fxd_arr_2 to C

Array Pointer is 80fdc70


 Lower  index 1
 Higher index 13
 Left   index 1
 Right  index 13
 Length of array 13
 Incremental -1
Dimentions of Array 1
Size of Array in bytes 52

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/DP_08_ARRAYS.html[9/26/2012 2:18:08 PM]


WWW.TESTBENCH.IN - Systemverilog DPI

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PASSING STRUCTS AND UNIONS Index


Introductions
SystemVerilog Passing Structure Example Layers
Verification Import
DPI allows to pass the structs and Unions . This can be done by passing pointers or by Naming
Constructs packing. Export
Interface Pure And Context
In the following example, a "struct" is passed from SystemVerilog to C and also from C Data Types
OOPS Arrays
to Systemverilog using import and export functions.  While passing the "struct" data
Randomization type, the data is packed in to array and passed from SV to C and then the array is Passing Structs And
decoded back to Struct in C. The same when the Struct is passed from C to Unions
Functional Coverage Arguments Type
SystemVerilog.
Assertion Disablie
DPI Report a Bug or Comment
CODE: C_file.c
UVM Tutorial on This section - Your
     #include "stdio.h" input is what keeps
VMM Tutorial
     #include "vc_hdrs.h" Testbench.in improving
OVM Tutorial      #include "svdpi.h" with time!
Easy Labs : SV     
     extern "C" {
Easy Labs : UVM     
Easy Labs : OVM       
     typedef struct{
Easy Labs : VMM        int  a;
AVM Switch TB        int  b;
       char c;
VMM Ethernet sample     
     } C_struct;
      
Verilog      extern void export_func(svBitVec32 x[3] );
Verification       
     void import_func()
Verilog Switch TB      {
Basic Constructs          C_struct  s_data;
         unsigned int arr[3];
        
         s_data.a = 51;
OpenVera          s_data.b = 242;
Constructs          s_data.c = 35;
Switch TB         
         printf( "C : s_data.a = %d\n", s_data.a );
RVM Switch TB          printf( "C : s_data.b = %d\n", s_data.b );
RVM Ethernet sample          printf( "C : s_data.c = %d\n\n", s_data.c );
      
         arr[0] =  s_data.a ;
         arr[1] =  s_data.b ;
Specman E          arr[2] =  s_data.c ;
Interview Questions       
         export_func(arr);
      
     }
     }
    
CODE: SV_file.sv
    
     program main;
      
         export "DPI-C" function export_func;

http://testbench.in/DP_09_PASSING_STRUCTS_AND_UNIONS.html[9/26/2012 2:18:17 PM]


WWW.TESTBENCH.IN - Systemverilog DPI

         import "DPI-C" function void import_func();
          
         typedef struct packed{
           int  a;
           int  b;
           byte  c;
         } SV_struct;
          
         function void export_func(input int arr[3]);
        
            SV_struct s_data;
            
             s_data.a = arr[0];
             s_data.b = arr[1];
             s_data.c = arr[2];
        
             $display("SV: s_data.a = %0d", s_data.a );
             $display("SV: s_data.b = %0d", s_data.b );
             $display("SV: s_data.c = %0d \n", s_data.c );
         endfunction
          
         initial 
         begin
            import_func();
         end
    
     endprogram

RESULTS:

C : s_data.a = 51
C : s_data.b = 242
C : s_data.c = 35

SV: s_data.a = 51
SV: s_data.b = 242
SV: s_data.c = 35

Passing Openarray Structs

CODE: C_file.c

#include "svdpi.h" 

typedef struct {int p; int q} PkdStru; 

void send2c(const svOpenArrayHandle dyn_arr) 

 int i;
 PkdStru Sele;      
     printf("\n \n Array Left %d, Array Right %d
\n\n", svLeft(dyn_arr,1), svRight(dyn_arr, 1) );
     for (i= svLeft(dyn_arr,1); i <= svRight(dyn_arr,1); i++) {
         Sele = *(PkdStru*)svGetArrElemPtr1(dyn_arr, i);
         printf("C : %d : [%d,%d]\n",i, Sele.q,Sele.p );
     }
     printf("\n\n");

CODE: SV_file.sv

program open_array_struct (); 
  
  typedef struct packed { int p; int q; } PkdStru; 
  
  import "DPI-C" function void send2c (input PkdStru arr []); 
  

http://testbench.in/DP_09_PASSING_STRUCTS_AND_UNIONS.html[9/26/2012 2:18:17 PM]


WWW.TESTBENCH.IN - Systemverilog DPI

  PkdStru arr_data [0:4]; 


  
  initial begin 

    foreach (arr_data[i]) begin
      arr_data[i] = {$random,$random};
      $display("SV: %0d : [%0d,%0d]",i,arr_data[i].p,arr_data[i].q);
    end    
    send2c(arr_data); 
  end 
    
endprogram 

RESULTS:

SV: 0 : [303379748,-1064739199]
SV: 1 : [-2071669239,-1309649309]
SV: 2 : [112818957,1189058957]
SV: 3 : [-1295874971,-1992863214]
SV: 4 : [15983361,114806029]

 
 Array Left 0, Array Right 4

C : 0 : [303379748,-1064739199]
C : 1 : [-2071669239,-1309649309]
C : 2 : [112818957,1189058957]
C : 3 : [-1295874971,-1992863214]
C : 4 : [15983361,114806029]

Passing Union Example

CODE:SV_file
    module m;
    
        typedef bit [2:0] A;
        
        typedef union packed { A a; S s; } U;
        U u;
        A a;
        
        // Import function takes three arguments
        import "DPI-C" function void foo8(input A fa, input U fu);
        
        initial begin
            a = 3'b100;
            u.a = 3'b100;
            foo8(a, u);
        end
    
    endmodule
    
CODE:C_file
    
    #include "svdpi.h"
    
    void foo8(
    const svBitVecVal* fa,
    const svBitVecVal* fu)
    {
        printf("fa is %d,  fu is %d\n", *fa,  *fu);
    }
    

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/DP_09_PASSING_STRUCTS_AND_UNIONS.html[9/26/2012 2:18:17 PM]


WWW.TESTBENCH.IN - Systemverilog DPI

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/DP_09_PASSING_STRUCTS_AND_UNIONS.html[9/26/2012 2:18:17 PM]


WWW.TESTBENCH.IN - Systemverilog DPI

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS ARGUMENTS TYPE Index


Introductions
SystemVerilog Layers
Verification What You Specify Is What You Get Import
Naming
Constructs For input and inout arguments, the temporary variable is initialized with the value of Export
Interface the actual argument with the appropriate coercion. For output or inout arguments, Pure And Context
the value of the temporary variable is assigned to the actual argument with the Data Types
OOPS Arrays
appropriate conversion. Arguments specified in SystemVerilog as input must not be
Randomization modified by the foreign language code. The initial values of formal arguments Passing Structs And
specified in SystemVerilog as output are undetermined and implementation Unions
Functional Coverage Arguments Type
dependent.
Assertion Disablie
DPI Report a Bug or Comment
Pass By Ref
UVM Tutorial on This section - Your
VMM Tutorial For arguments passed by reference, a reference (a pointer) to the actual data object input is what keeps
is passed. In the case of packed data, a reference to a canonical data object is Testbench.in improving
OVM Tutorial passed. The actual argument is usually allocated by a caller. The caller can also pass a with time!
Easy Labs : SV reference to an object already allocated somewhere else, for example, its own
formal argument passed by reference. If an argument of type T is passed by
Easy Labs : UVM reference, the formal argument shall be of type T*. Packed arrays are passed using a
Easy Labs : OVM pointer to the appropriate canonical type definition, either svLogicVecVal* or
svBitVecVal*.
Easy Labs : VMM
AVM Switch TB
Pass By Value
VMM Ethernet sample
Only small values of formal input arguments are passed by value. Function results are
also directly passed by value. The user needs to provide the C type equivalent to the
Verilog SystemVerilog type of a formal argument if an argument is passed by value.
Verification
Verilog Switch TB Passing String
Basic Constructs
The layout of SystemVerilog string objects is implementation dependent. However,
when a string value is passed from SystemVerilog to C, implementations shall ensure
that all characters in the string are laid out in memory per C string conventions,
OpenVera including a trailing null character present at the end of the C string.
Constructs
Switch TB
Example : Passing String From Sv To C
RVM Switch TB
RVM Ethernet sample CODE: SV_file.sv
     program main;
         string str;
        
Specman E          import "DPI-C" string_sv2c=task string_sv2c(string str);
Interview Questions         
         initial
         begin
             str = " HELLO: This string is created in SystemVerilog \n" ;
             string_sv2c(str);
         end
        
     endprogram
    
CODE: C_file.c
     #include "svdpi.h"

http://testbench.in/DP_10_ARGUMENTS_TYPE.html[9/26/2012 2:18:26 PM]


WWW.TESTBENCH.IN - Systemverilog DPI

     int string_sv2c(const char* str){
    
         printf(" C: %s",str);
         return 0;      
    
     }

RESULTS

 C:  HELLO: This string is created in SystemVerilog

Example: Passing String From C To Sv

From the Data type mapping table, a SystemVerilog "String" is mapped to "const char*"
in C. In the Following example, string "HELLO: This string is created in C" is assigned
to a string and passed as return value to function import "string_c2sv" and this import
function is called in SystemVerilog.

CODE: SV_file.v
     program main;
          string str;
          import "DPI-C" context function string string_c2sv();
          
          initial
          begin
              str = string_c2sv();
              $display(" SV: %s ",str);
          end
          
     endprogram
    
CODE: C_file.c
     #include "svdpi.h"
    
     const char*  string_c2sv(void) {
         char* str;
         str = " HELLO: This string is created in C ";
         return str;
     }

RESULTS:

SV: HELLO: This string is created in C

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/DP_10_ARGUMENTS_TYPE.html[9/26/2012 2:18:26 PM]


WWW.TESTBENCH.IN - Systemverilog DPI

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS DISABLIE Index


Introductions
SystemVerilog Disable Dpi-C Tasks And Functions Layers
Verification Import
It is possible for a disable statement to disable a block that is currently executing a Naming
Constructs mixed language call  chain. When a DPI import task or function is disabled, the C code Export
Interface is required to follow a simple disable protocol. The protocol gives the C code the Pure And Context
opportunity to perform any necessary resource cleanup, such as closing open file Data Types
OOPS Arrays
handles, closing open VPI handles, or freeing heap memory.
Randomization Passing Structs And
The protocol is composed of the following items: Unions
Functional Coverage Arguments Type
a) When an exported task returns due to a disable, it must return a value of 1.
Assertion Otherwise, it must return 0. Disablie
DPI b) When an imported task returns due to a disable, it must return a value of 1.
Report a Bug or Comment
Otherwise, it must return 0.
UVM Tutorial on This section - Your
c) Before an imported function returns due to a disable, it must call the API input is what keeps
VMM Tutorial function svAckDisabledState(). Testbench.in improving
OVM Tutorial d) Once an imported task or function enters the disabled state, it is illegal for the with time!
current function invocation to make any further calls to exported tasks or functions.
Easy Labs : SV
Easy Labs : UVM
Easy Labs : OVM Include Files
Easy Labs : VMM
Applications that use the DPI with C code usually need this main include file. The
AVM Switch TB include file svdpi.h defines the types for canonical representation of 2-state (bit) and
VMM Ethernet sample 4-state (logic) values and passing references to SystemVerilog data objects. The file
also provides function headers and defines a number of helper macros and constants.
The content of svdpi.h does not depend on any particular implementation; all
simulators shall use the same file.
Verilog
Verification
Verilog Switch TB
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/DP_11_DISABLIE.html[9/26/2012 2:18:33 PM]


WWW.TESTBENCH.IN - Systemverilog DPI

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/DP_11_DISABLIE.html[9/26/2012 2:18:33 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS ASIC DESIGN Index


Asic Design
SystemVerilog Bottle Neck In Asic Flow
Verification The term Asic stands for Application Specific Integrated Circuit. Is an integrated Functional Verification
circuit (IC) customized for a particular use, rather than intended for general-purpose Need
Constructs use.  Generally an ASIC design will be undertaken for a product that will have a large Testbench
Interface production run, and the ASIC may contain a very large part of the electronics needed Linear Testbench
on a single integrated circuit. As feature sizes have shrunk and design tools improved Linear Random
OOPS Testbench
over the years, the complexity in an ASIC has grown from 5,000 over 100 million gates
Randomization How To Check The
Results
Functional Coverage Self Checking Testbenchs
Assertion How To Get Scenarios
Which We Never Thought
DPI How To Check Whether
UVM Tutorial The Testbench Has
Satisfactorily Exercised
VMM Tutorial The Design
OVM Tutorial Types Of Code Coverage
Statement Coverage
Easy Labs : SV
Block Coverage
Easy Labs : UVM Conditional Coverage
Branch Coverage
Easy Labs : OVM
Path Coverage
Easy Labs : VMM Toggle Coverage
AVM Switch TB Fsm Coverage
Make Your Goal 100
VMM Ethernet sample Percent Code Coverage
Nothing Less
Functional Coverage
Verilog Coverage Driven
Constraint Random
Verification
Verification Architecture
Verilog Switch TB Phases Of Verification
Ones Counter Example
Basic Constructs Mrd Verification Plan
A Marketing Requirements Document (MRD) outlines the requirements a new product. Report a Bug or Comment
OpenVera Engineers use an MRD to create the product.  Marketing requirement document covers on This section - Your
market needs, the customer value proposition, and product functionality. It is input is what keeps
Constructs
developed by the Marketing team and upper management. Testbench.in improving
Switch TB
with time!
RVM Switch TB
Architecture Specification
RVM Ethernet sample

The architect based on the MRD specification, develops the overall architecture of the
Specman E chip.  This is a very high level plan.  Architecture Specification includes functional
descriptions of each module, Properties and weights.
Interview Questions

Design Specification

The designers and architects sit together to come up with detailed design documents.
Design strategies, design partitions, type of memories to use, etc.

Verification Plan

A Verification specification is called a Verification/test plan. The verification

http://testbench.in/TS_01_ASIC_DESIGN.html[9/26/2012 2:18:42 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

engineer goes through all the above documents and prepares verification plan to
verify the design.

Rtl Design

RTL stands for Register Transfer Level. The designer starts implementing the RTL
design in HDL like verilog or VHDL.

Functional Verification

The verification engineers starts developing TestBench and verifies whether the DUT
works according to specification or not.

Synthesis

Synthesis is the process of taking a design written in a hardware description language,


compiling it into a net list of interconnected gates which are selected from a user-
provided library of various gates.  The design after synthesis is a gate-level design.

Physical Design

Physical design process includes logic partitioning, floor planning, global routing,
detailed routing, compaction, and performance-driven layout. PD team transforms net
list representation of a system into layout representation.

Timing Analysis

Static timing analysis is an important step in analyzing the performance of a design. In


the Timing analysis Setup time, hold time ,recovery time ,removal time , Clock
latency, clock skew, clock uncertainty etc checks are done.

Tapeout

This is the final stage of the design cycle of integrated circuits. Once all the checks
are done, the design is ready to be sent to Foundry.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TS_01_ASIC_DESIGN.html[9/26/2012 2:18:42 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS BOTTLE NECK IN ASIC FLOW Index


Asic Design
SystemVerilog Bottle Neck In Asic
Verification What is Bottle neck in the asic design flow? Flow
Functional Verification
Constructs Verification  consumes 50% to 70% of the effort of design cycle and is on the critical Need
Interface path in the design flow of multimillion gate ASICs, so verification became the main Testbench
bottleneck in the design process.  The functional verification bottleneck is an effect Linear Testbench
OOPS Linear Random
of rising the design abstraction level. Majority of ASICs require at least one re-spin
Randomization with 71% of re-spins are due to functional bugs. Testbench
How To Check The
Functional Coverage Results
Assertion Self Checking Testbenchs
How To Get Scenarios
DPI Which We Never Thought
UVM Tutorial How To Check Whether
The Testbench Has
VMM Tutorial Satisfactorily Exercised
OVM Tutorial The Design
Types Of Code Coverage
Easy Labs : SV
Statement Coverage
Easy Labs : UVM Block Coverage
Conditional Coverage
Easy Labs : OVM
Branch Coverage
Easy Labs : VMM Path Coverage
AVM Switch TB Toggle Coverage
Fsm Coverage
VMM Ethernet sample Make Your Goal 100
Percent Code Coverage
Nothing Less
Verilog Functional Coverage
Coverage Driven
Verification
Constraint Random
Verilog Switch TB Verification Architecture
Phases Of Verification
Basic Constructs
Ones Counter Example
Verification Plan

OpenVera Report a Bug or Comment


Constructs on This section - Your
input is what keeps
Switch TB
Testbench.in improving
RVM Switch TB with time!
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/TS_02_BOTTLE_NECK_IN_ASIC_FLOW.html[9/26/2012 2:18:49 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TS_02_BOTTLE_NECK_IN_ASIC_FLOW.html[9/26/2012 2:18:49 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS FUNCTIONAL VERIFICATION NEED Index


Asic Design
SystemVerilog Bottle Neck In Asic Flow
Verification Why we need functional verification? Functional Verification
Need
Constructs To build confidence and stay in business. Testbench
Interface A primary purpose for functional verification is to detect failures so that bugs can be Linear Testbench
identified and corrected before it gets shipped to costumer.  If RTL designer makes a Linear Random
OOPS Testbench
mistake in designing or coding, this results as a bug in the Chip. If this bug is
Randomization executed, in certain situations the system will produce wrong results, causing a How To Check The
failure. Not all mistakes will necessarily result in failures. The bug in the dead code Results
Functional Coverage Self Checking Testbenchs
will never result in failure. A single mistake may result in a wide range of failure
Assertion symptoms. Not all bugs are caused by coding errors. There are possibilities that error How To Get Scenarios
may in the specification itself. Sometimes miscommunications between teams may Which We Never Thought
DPI How To Check Whether
lead to wrong design.
UVM Tutorial The Testbench Has
Satisfactorily Exercised
VMM Tutorial The Design
Example of coding error: 
OVM Tutorial      Types Of Code Coverage
     1 reg [1:0] state; Statement Coverage
Easy Labs : SV
     2 Block Coverage
Easy Labs : UVM      3 parameter zero=0, one=1, two=2, three=3; Conditional Coverage
     4 Branch Coverage
Easy Labs : OVM
     5 always @(state)  Path Coverage
Easy Labs : VMM      6     begin Toggle Coverage
AVM Switch TB      7          case (State) Fsm Coverage
     8               zero: Make Your Goal 100
VMM Ethernet sample      9                    out = 4'b0000; Percent Code Coverage
     10               one: Nothing Less
     11                   out = 4'b0001; Functional Coverage
Verilog      12               two: Coverage Driven
     13                   out = 4'b0010; Constraint Random
Verification
     14             three: Verification Architecture
Verilog Switch TB      15                   out = 4'b0100; Phases Of Verification
     16            default: Ones Counter Example
Basic Constructs
     17                   out = 4'b0000; Verification Plan
     18          endcase
     19     end Report a Bug or Comment
OpenVera      on This section - Your
Constructs      input is what keeps
Testbench.in improving
Switch TB
There is a coding error in the preceding example. Designer declared "state" in the with time!
RVM Switch TB line-1. Later in the code it is reference in the line-5. In the line-7 also, the designer
RVM Ethernet sample intention is to refer "state". But mistakenly he typed "State".  Verilog is a case-
sensitive language, and variable "State" and "state" are different and this will produce
wrong results.
Specman E
Interview Questions

http://testbench.in/TS_03_FUNCTIONAL_VERIFICATION_NEED.html[9/26/2012 2:18:57 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TS_03_FUNCTIONAL_VERIFICATION_NEED.html[9/26/2012 2:18:57 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS TESTBENCH Index


Asic Design
SystemVerilog Bottle Neck In Asic Flow
Verification What is TestBench? Functional Verification
Need
Constructs TestBench mimic the environment in which the design will reside. It checks whether Testbench
Interface the RTL Implementation meets the design spec or not.  This Environment creates Linear Testbench
invalid and unexpected as well as valid and expected conditions to test the design. Linear Random
OOPS Testbench
Randomization How To Check The
Results
Functional Coverage Self Checking Testbenchs
Assertion How To Get Scenarios
Which We Never Thought
DPI How To Check Whether
UVM Tutorial The Testbench Has
Satisfactorily Exercised
VMM Tutorial The Design
OVM Tutorial Types Of Code Coverage
Statement Coverage
Easy Labs : SV
Block Coverage
Easy Labs : UVM Conditional Coverage
Branch Coverage
Easy Labs : OVM
Path Coverage
Easy Labs : VMM Toggle Coverage
AVM Switch TB Fsm Coverage
Make Your Goal 100
VMM Ethernet sample Percent Code Coverage
Nothing Less
Functional Coverage
Verilog Coverage Driven
Constraint Random
Verification
Verification Architecture
Verilog Switch TB Phases Of Verification
Ones Counter Example
Basic Constructs
Verification Plan

Report a Bug or Comment


OpenVera on This section - Your
Constructs input is what keeps
Testbench.in improving
Switch TB
with time!
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/TS_04_TESTBENCH.html[9/26/2012 2:19:07 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TS_04_TESTBENCH.html[9/26/2012 2:19:07 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS LINEAR TESTBENCH Index


Asic Design
SystemVerilog Bottle Neck In Asic Flow
Verification Linear TestBench is the simplest, fastest and easiest way of writing testbenchs. This Functional Verification
became novice verification engineer choice.  It is also slowest way to execute Need
Constructs stimulus. Typically, linear testbenchs are written in the VHDL or Verilog.  In this Testbench
Interface TestBench, simple linear sequence of test vectors is mentioned. Stimulus code like Linear Testbench
this is easy to generate translating a vector file with a Perl script, for example.   Linear Random
OOPS Testbench
Small models like simple state machine or adder can be verified with this approach.
Randomization The following code snippet shows linear TestBench. The code snippet shows some How To Check The
input combination only. This is also bad for simulator performance as the simulator Results
Functional Coverage Self Checking Testbenchs
must evaluate and schedule a very large number of events. This reduces simulation
Assertion performance in proportion to the size of the stimulus process. How To Get Scenarios
Which We Never Thought
DPI How To Check Whether
Typically, linear testbenchs perform the following tasks:
UVM Tutorial The Testbench Has
  Instantiate the design under test (DUT) Satisfactorily Exercised
VMM Tutorial The Design
  Stimulate the DUT by applying test vectors. Types Of Code Coverage
OVM Tutorial
  Output results waveform window or to a terminal for visual inspection manually. Statement Coverage
Easy Labs : SV
Block Coverage
Easy Labs : UVM Conditional Coverage
Branch Coverage
Easy Labs : OVM Example: Linear TestBench Path Coverage
Easy Labs : VMM    module adder(a,b,c); //DUT code start   Toggle Coverage
       input [15:0] a;               Fsm Coverage
AVM Switch TB        input [15:0] b;             Make Your Goal 100
VMM Ethernet sample        output [16:0] c;               Percent Code Coverage
       Nothing Less
       assign c = a + b;             Functional Coverage
       Coverage Driven
Verilog    endmodule            //DUT code end   Constraint Random
Verification                              Verification Architecture
Verilog Switch TB    module top();        //TestBench code start       Phases Of Verification
        reg [15:0] a;                 Ones Counter Example
Basic Constructs         reg [15:0] b;               Verification Plan
        wire [16:0] c;                
                                     Report a Bug or Comment
OpenVera         adder DUT(a,b,c);   //DUT Instantiation             on This section - Your
                                   input is what keeps
Constructs
        initial                       Testbench.in improving
Switch TB         begin                       with time!
RVM Switch TB               a = 16'h45;           //apply the stimulus          
              b = 16'h12;                
RVM Ethernet sample               #10 $display(" a=%0d,b=%0d,c=%0d",a,b,c); 
        //send the output to terminal for visual inspection    
        end                                                          
Specman E    endmodule            //TestBench code end

Interview Questions
To test all possible scenarios which are known to us, it is not an easy task.
Development time increases exponentially as the number of scenarios increases and
maintain them is nightmare. Instead of listing out all the possible scenarios, pickup
some randomly and check the DUT.

NOTE TO NO VOICE ENGINEERS:

  Generally tendency of any novice engineer is to see the outputs in the waveform
viewer. Waveform viewers are for debugging designs, not for testbench.  Most of the

http://testbench.in/TS_05_LINEAR_TESTBENCH.html[9/26/2012 2:19:14 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

operation in TestBench executes in zero time, where waveform viewer will not be
helpful. All the examples in the book outputs messages to terminal for analyzing its
behavior.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TS_05_LINEAR_TESTBENCH.html[9/26/2012 2:19:14 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS LINEAR RANDOM TESTBENCH Index


Asic Design
SystemVerilog Bottle Neck In Asic Flow
Verification Random TestBench don't use Hardcoded values like linear testbenchs.  Input stimulus Functional Verification
is generated using random values.  In Verilog, system function $random provides a Need
Constructs mechanism for generating random numbers. The function returns a new 32-bit Testbench
Interface random number each time it is called. These test cases are not easily readable and Linear Testbench
are also not reusable. New tests have to be created when the specification or design Linear Random
OOPS Testbench
changes, to accommodate the changes.  The main disadvantage of this testing is that
Randomization we never know what random values are generated and it may waste simulation cycles How To Check The
by generating same values again and again.   Results
Functional Coverage Self Checking Testbenchs
Assertion How To Get Scenarios
EXAMPLE: Linear Random TestBench Which We Never Thought
DPI How To Check Whether
     module adder(a,b,c); //DUT code start  
UVM Tutorial          input [15:0] a,b;               The Testbench Has
         output [16:0] c;               Satisfactorily Exercised
VMM Tutorial The Design
         assign c = a + b;            
OVM Tutorial      endmodule            //DUT code end   Types Of Code Coverage
                               Statement Coverage
Easy Labs : SV
     module top();        //TestBench code start       Block Coverage
Easy Labs : UVM           reg [15:0] a;                 Conditional Coverage
          reg [15:0] b;               Branch Coverage
Easy Labs : OVM
          wire [16:0] c;                 Path Coverage
Easy Labs : VMM                                      Toggle Coverage
AVM Switch TB          adder DUT(a,b,c);   //DUT Instantiation             Fsm Coverage
                                     Make Your Goal 100
VMM Ethernet sample          initial                       Percent Code Coverage
         repeat(100) begin                       Nothing Less
               a = $random;    //apply random stimulus           Functional Coverage
Verilog                b = $random;                 Coverage Driven
               #10 $display(" a=%0d,b=%0d,c=%0d",a,b,c);  Constraint Random
Verification
         end                                                           Verification Architecture
Verilog Switch TB      endmodule            //TestBench code end Phases Of Verification
Ones Counter Example
Basic Constructs
Verification Plan

Report a Bug or Comment


OpenVera on This section - Your
Constructs input is what keeps
Testbench.in improving
Switch TB
with time!
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/TS_06_LINEAR_RANDOM_TESTBENCH.html[9/26/2012 2:19:22 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TS_06_LINEAR_RANDOM_TESTBENCH.html[9/26/2012 2:19:22 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS HOW TO CHECK THE RESULTS Index


Asic Design
SystemVerilog Bottle Neck In Asic Flow
Verification How does a Verification engineer check whether the results obtained from the Functional Verification
simulation match the original specification of the design?  For simple testbenchs like Need
Constructs the above, output is displayed in waveform window or messages are sent to terminal Testbench
Interface for visual checking.  Visually checking   is the oldest and most labor intensive Linear Testbench
technique. The quality of the verification depends on the determination and Linear Random
OOPS Testbench
dedication of the individual who is doing the checking. It is not practical to verify a
Randomization complex model merely by examining the waveform or text file. Whenever a change is How To Check The
made to the DUT to add a new feature or to fix a bug, same amount of effort needs Results
Functional Coverage Self Checking Testbenchs
to be deployed to check the simulation results.  
Assertion How To Get Scenarios
Which We Never Thought
DPI How To Check Whether
UVM Tutorial The Testbench Has
Satisfactorily Exercised
VMM Tutorial The Design
OVM Tutorial Types Of Code Coverage
Statement Coverage
Easy Labs : SV
Block Coverage
Easy Labs : UVM Conditional Coverage
Branch Coverage
Easy Labs : OVM
Path Coverage
Easy Labs : VMM Toggle Coverage
AVM Switch TB Fsm Coverage
Make Your Goal 100
VMM Ethernet sample Percent Code Coverage
Nothing Less
Functional Coverage
Verilog Coverage Driven
Constraint Random
Verification
Verification Architecture
Verilog Switch TB Phases Of Verification
Ones Counter Example
Basic Constructs
Verification Plan

Report a Bug or Comment


OpenVera on This section - Your
Constructs input is what keeps
Testbench.in improving
Switch TB
with time!
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/TS_07_HOW_TO_CHECK_THE_RESULTS.html[9/26/2012 2:19:30 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TS_07_HOW_TO_CHECK_THE_RESULTS.html[9/26/2012 2:19:30 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS SELF CHECKING TESTBENCHS Index


Asic Design
SystemVerilog Bottle Neck In Asic Flow
Verification A self-checking TestBench checks expected results against actual results obtained Functional Verification
from the simulation. Although Self-checking testbenchs require considerably more Need
Constructs effort during the initial test bench creation phase, this technique can dramatically Testbench
Interface Reduce the amount of effort needed to re-check a design after a change has been Linear Testbench
made to the DUT. Debugging time is significantly shortened by useful error-tracking Linear Random
OOPS Testbench
information that can be built into the TestBench to show where a design fails.
Randomization How To Check The
Results
Functional Coverage Self Checking
Assertion Testbenchs
How To Get Scenarios
DPI Which We Never Thought
UVM Tutorial How To Check Whether
The Testbench Has
VMM Tutorial Satisfactorily Exercised
OVM Tutorial The Design
Types Of Code Coverage
Easy Labs : SV
Statement Coverage
Easy Labs : UVM Block Coverage
Conditional Coverage
Easy Labs : OVM A self-checking TestBench has two major parts, the input blocks and output blocks. Branch Coverage
Easy Labs : VMM Input block consist of stimulus and driver to drive the stimulus to DUT. The output Path Coverage
block consists of monitor to collect the DUT outputs and verify them. Toggle Coverage
AVM Switch TB
Fsm Coverage
VMM Ethernet sample All the above approaches require the test writer to create an explicit test for each Make Your Goal 100
feature of the design.   Verification approach in which each feature is written in a Percent Code Coverage
separate test case file is called directed verification. Nothing Less
Verilog Functional Coverage
Coverage Driven
Verification EXAMPLE:  adder example Constraint Random
Verilog Switch TB      module adder(a,b,c); //DUT code start   Verification Architecture
         input [15:0] a,b;               Phases Of Verification
Basic Constructs          output [16:0] c;               Ones Counter Example
Verification Plan
         assign c = a + b;            
OpenVera Report a Bug or Comment
Constructs      endmodule            //DUT code end   on This section - Your
                               input is what keeps
Switch TB      module top();        //TestBench code start       Testbench.in improving
RVM Switch TB           reg [15:0] a;                 with time!
          reg [15:0] b;              
RVM Ethernet sample           wire [16:0] c;                
                                      
          adder DUT(a,b,c);   //DUT Instantiation            
Specman E                                     
          initial                      
Interview Questions           repeat(100) begin                      
                a = $random;    //apply random stimulus          
                b = $random;                
                #10 
                $display(" a=%0d,b=%0d,c=%0d",a,b,c); 
                if( a + b != c)     // monitor logic.
                    $display(" *ERROR* ");
          end                                                          
     endmodule            //TestBench code end

http://testbench.in/TS_08_SELF_CHECKING_TESTBENCHS.html[9/26/2012 2:19:38 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TS_08_SELF_CHECKING_TESTBENCHS.html[9/26/2012 2:19:38 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS HOW TO GET SCENARIOS WHICH WE NEVER THOUGHT Index


Asic Design
SystemVerilog Bottle Neck In Asic Flow
Verification In Directed verification, the Verification Environment has mechanism to send the Functional Verification
Stimulus to DUT and collect the responses and check the responses. The Stimulus is Need
Constructs generated in Tests case.  Directed testbenchs may also use a limited amount of Testbench
Interface randomization, often by creating random data values rather than simply filling in Linear Testbench
each data element with a predetermined value.  Each test case verifies specific Linear Random
OOPS Testbench
feature of the design. This becomes tedious when the design complexity increases.  As
Randomization circuit How To Check The
Results
Functional Coverage Self Checking Testbenchs
complexity increases, it becomes more difficult to create patterns that fully exercise
Assertion the design.  Test case maintenance become harder and time consuming. How To Get Scenarios
Which We Never
DPI Thought
UVM Tutorial How To Check Whether
The Testbench Has
VMM Tutorial Satisfactorily Exercised
OVM Tutorial The Design
Types Of Code Coverage
Easy Labs : SV
Statement Coverage
Easy Labs : UVM Block Coverage
Conditional Coverage
Easy Labs : OVM
Branch Coverage
Easy Labs : VMM Path Coverage
AVM Switch TB Toggle Coverage
Fsm Coverage
VMM Ethernet sample Make Your Goal 100
Percent Code Coverage
Nothing Less
Verilog Functional Coverage
Coverage Driven
Verification
Constraint Random
Verilog Switch TB Verification Architecture
Phases Of Verification
Basic Constructs
Ones Counter Example
Verification Plan
In Directed Verification, test writer has to list out each feature.  Test writer can't
OpenVera think of all possible potential bug scenarios and there are chances that Bugs will
Report a Bug or Comment
escape.  With these approaches, the bugs lurking in these corners hide until late in
Constructs on This section - Your
the development cycle, or aren't found at all until product is taped out.
input is what keeps
Switch TB
Testbench.in improving
Solution to the above problems is Constraint random verification. Using constraint
RVM Switch TB with time!
random verification, the stimulus required to verify test features are generated
RVM Ethernet sample automatically.  Test writer specifies set of specification, and the TestBench
automatically creates solution space and picks up scenarios from the solution space.

Constraint random verification also reduces manual effort and code for individual
Specman E
tests.  As the scenarios are generated automatically by the TestBench, the number of
Interview Questions test case files gets reduced.  In Directed verification, some of the tests share similar
logic, if the engineer has to change the logic which is common to certain group of
tests, then he has to edit all the test case files and it is time consuming.  But in
Constraint random verification, the number of tests case files will be very less, so
changes will be mostly in environment and minimal.

Directed verification with a fairly simple TestBench, verification engineers can start
finding bugs in simulation almost immediately even before the TestBench is fully
completed.  With a constrained-random verification environment, there is an up-front
cost that must be invested before the first test can be run. Constraint-based
generators can be easily converted into checkers if required.

http://testbench.in/TS_09_HOW_TO_GET_SCENARIOS_WHICH_WE_NEVER_THOUGHT.html[9/26/2012 2:19:47 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

Generating fully randomly is meaningless as it may generate invalid scenarios and it


may also regenerate the same scenario again and again wasting potential simulation
time. A User must define data structures, which represent stimulus applied to the DUT
input. Next, constraints must be defined to guide the random generator. Using
constraint, the solution space is defined, and randomization picks up scenarios
randomly from the solution space.  Constraints act as knobs in the TestBench which
control the generator's randomness.

The main disadvantage of constraint random verification is we never know how well
the DUT is verified.  If verification engineer  can get the information about the logic in
DUT which is not verified, he can further constraint the randomization or write
directed testcases to exercise the unverified logic.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TS_09_HOW_TO_GET_SCENARIOS_WHICH_WE_NEVER_THOUGHT.html[9/26/2012 2:19:47 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS HOW TO CHECK WHETHER THE TESTBENCH HAS SATISFACTORILY Index


Asic Design
EXERCISED THE DESIGN Bottle Neck In Asic Flow
SystemVerilog
Verification Functional Verification
Need
Constructs Code coverage is used to measure the efficiency of verification implementation. It Testbench
provides a quantitative measurement of the testing space. It describes the degree to Linear Testbench
Interface which the source code of a DUT has been tested. It is also referred as structural Linear Random
OOPS coverage. Testbench
Randomization How To Check The
Code coverage answers the questions like Results
Functional Coverage    Have all the branches in " Case ", "if" have been entered? Self Checking Testbenchs
Assertion    Have all the conditions in "if","case" statement is simulated? How To Get Scenarios
   Have all the variables have been toggles? Which We Never Thought
DPI    Have all the statements of the RTL code have been exercised? How To Check Whether
UVM Tutorial    Have all the states in the FSM has been entered and all the legal transitions The Testbench Has
exercised? Satisfactorily Exercised
VMM Tutorial The Design
   Have all the paths within a block have been exercised?
OVM Tutorial Types Of Code Coverage
Statement Coverage
Easy Labs : SV
By applying code coverage analysis techniques to hardware description languages, Block Coverage
Easy Labs : UVM verification efficiency was improved by enabling a verification engineer to isolate Conditional Coverage
areas of un-tested HDL code. The verification engineer  examine a coverage report, Branch Coverage
Easy Labs : OVM
seeks out the low values and understands why that particular code hasn't been tested Path Coverage
Easy Labs : VMM fully and writes more tests or directs randomness to cover the untested areas where Toggle Coverage
AVM Switch TB there may be a possibility of bug hiding. Fsm Coverage
Make Your Goal 100
VMM Ethernet sample Percent Code Coverage
No additional coding is required to get 100 percent code coverage , the tool would
automatically show the item as covered if the required test Nothing Less
scenario(s)/combination(s) is(are) exercised. Functional Coverage
Verilog Coverage Driven
In unit level verification, a module by module is verified in its own test environment Constraint Random
Verification
to prove that the logic, control, and data paths are functionally correct. The goal of Verification Architecture
Verilog Switch TB module level verification is to ensure that the component/unit being tested conforms Phases Of Verification
to its specifications and is ready to be integrated with other subcomponents of the Ones Counter Example
Basic Constructs
product. Code coverage becomes a criterion for finishing unit level testing as it needs Verification Plan
to verify every feature of component/unit. In sub-system level /system level, the
goal is to ensure that the interfaces among the units are correct and the units work Report a Bug or Comment
OpenVera together to execute the functionality correctly. In sub system level /system level on This section - Your
Constructs testing, code coverage may not be useful as the verification is not targeted at all the input is what keeps
features of the unit.   Testbench.in improving
Switch TB
with time!
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/TS_10_HOW_TO_CHECK_WHETHER_THE_TESTBENCH_HAS_SATISFACTORILY_EXERCISED_THE_DESIGN.html[9/26/2012 2:19:57 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TS_10_HOW_TO_CHECK_WHETHER_THE_TESTBENCH_HAS_SATISFACTORILY_EXERCISED_THE_DESIGN.html[9/26/2012 2:19:57 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS TYPES OF CODE COVERAGE Index


Asic Design
SystemVerilog Bottle Neck In Asic Flow
Verification There are a number of coverage criteria, they are: Functional Verification
Need
Constructs Testbench
  Statement coverage /line coverage
Interface Linear Testbench
  Block/segment coverage Linear Random
OOPS   Conditional coverage Testbench
Randomization
  Branch coverage How To Check The
  Toggle coverage Results
Functional Coverage   Path coverage Self Checking Testbenchs
Assertion   Fsm coverage How To Get Scenarios
Which We Never Thought
DPI
The following example is considered while explaining code coverage types in further How To Check Whether
UVM Tutorial sections. The Testbench Has
Satisfactorily Exercised
VMM Tutorial The Design
OVM Tutorial EXAMPLE Types Of Code
     1 Coverage
Easy Labs : SV
     2  module dut(); Statement Coverage
Easy Labs : UVM      3      reg a,b,c,d,e,f; Block Coverage
     4  Conditional Coverage
Easy Labs : OVM
     5      initial Branch Coverage
Easy Labs : VMM      6      begin Path Coverage
AVM Switch TB      7          #5 a = 0; Toggle Coverage
     8          #5 a = 1; Fsm Coverage
VMM Ethernet sample      9      end Make Your Goal 100
     10     Percent Code Coverage
     11     always @(posedge a) Nothing Less
Verilog      12     begin Functional Coverage
     13          c = b && a; Coverage Driven
Verification
     14          if(c && f) Constraint Random
Verilog Switch TB      15            b = e; Verification Architecture
     16          else  Phases Of Verification
Basic Constructs
     17            e = b; Ones Counter Example
     18           Verification Plan
     19          case(c)
OpenVera      20            1:f = 1; Report a Bug or Comment
Constructs      21            0:f = 0; on This section - Your
     22            default : f = 0; input is what keeps
Switch TB
     23          endcase Testbench.in improving
RVM Switch TB      24           with time!
RVM Ethernet sample      25     end
     26 endmodule

Specman E
Interview Questions

http://testbench.in/TS_11_TYPES_OF_CODE_COVERAGE.html[9/26/2012 2:20:04 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TS_11_TYPES_OF_CODE_COVERAGE.html[9/26/2012 2:20:04 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS STATEMENT COVERAGE Index


Asic Design
SystemVerilog Bottle Neck In Asic Flow
Verification Statement coverage, also known as line coverage is the easiest understandable type Functional Verification
of coverage. This is required to be 100% for every project.  From N lines of code and Need
Constructs according to the applied stimulus how many statements (lines) are covered in the Testbench
Interface simulation is measured by statement coverage. If a DUT is 10 lines long and 8 lines of Linear Testbench
them were exercised in a test run, then the DUT has line coverage of 80%. Line Linear Random
OOPS Testbench
coverage includes continuous assignment statements, Individual procedural
Randomization statements, Procedural statement blocks, Procedural statement block types, How To Check The
Conditional statement and Branches for conditional statements. It considers only it Results
Functional Coverage Self Checking Testbenchs
the executable statements and statements which are not executable like module,
Assertion endmodule, comments, timescale etc are not covered. How To Get Scenarios
Which We Never Thought
DPI How To Check Whether
Statement coverage report of the above example:
UVM Tutorial The Testbench Has
  Satisfactorily Exercised
VMM Tutorial The Design
OVM Tutorial    There are total 12 statements at lines 5,7,8,11,13,14,15,17,19,20,21,22 Types Of Code Coverage
   Statement Coverage
Easy Labs : SV
   Covered 9 statements. They are at lines Block Coverage
Easy Labs : UVM    5,7,8,11,13,14,17,19,22 Conditional Coverage
   Branch Coverage
Easy Labs : OVM
   Uncovered 3 statements. They are at line Path Coverage
Easy Labs : VMM    15,20,21 Toggle Coverage
AVM Switch TB    Fsm Coverage
   Coverage percentage: 75.00 (9/12) Make Your Goal 100
VMM Ethernet sample Percent Code Coverage
Nothing Less
  Functional Coverage
Verilog Coverage Driven
Constraint Random
Verification
Verification Architecture
Verilog Switch TB Phases Of Verification
Ones Counter Example
Basic Constructs
Verification Plan

Report a Bug or Comment


OpenVera on This section - Your
Constructs input is what keeps
Testbench.in improving
Switch TB
with time!
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/TS_12_STATEMENT_COVERAGE.html[9/26/2012 2:20:12 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TS_12_STATEMENT_COVERAGE.html[9/26/2012 2:20:12 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS BLOCK COVERAGE Index


Asic Design
SystemVerilog Bottle Neck In Asic Flow
Verification The nature of the statement and block coverage looks somewhat same. The Functional Verification
difference is that block coverage considers branched blocks of if/else, case branches, Need
Constructs wait, while, for etc.  Analysis of block coverage reveals the dead code in RTL. Testbench
Interface Linear Testbench
Block coverage report of the above example: Linear Random
OOPS Testbench
Randomization How To Check The
Results
Functional Coverage Self Checking Testbenchs
   There are total 9 blocks at lines
Assertion    5,7,8,11,15,17,20,21,22 How To Get Scenarios
   Which We Never Thought
DPI How To Check Whether
   Covered 6 blocks. They are at lines
UVM Tutorial    5,7,8,11,17,22 The Testbench Has
   Satisfactorily Exercised
VMM Tutorial The Design
   Uncovered 3 blocks. They are at line
OVM Tutorial    15,20,21 Types Of Code Coverage
   Statement Coverage
Easy Labs : SV
   Coverage percentage: 66.67 (6/9) Block Coverage
Easy Labs : UVM Conditional Coverage
Branch Coverage
Easy Labs : OVM
Path Coverage
Easy Labs : VMM Toggle Coverage
AVM Switch TB Fsm Coverage
Make Your Goal 100
VMM Ethernet sample Percent Code Coverage
Nothing Less
Functional Coverage
Verilog Coverage Driven
Constraint Random
Verification
Verification Architecture
Verilog Switch TB Phases Of Verification
Ones Counter Example
Basic Constructs
Verification Plan

Report a Bug or Comment


OpenVera on This section - Your
Constructs input is what keeps
Testbench.in improving
Switch TB
with time!
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/TS_13_BLOCK_COVERAGE.html[9/26/2012 2:20:20 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TS_13_BLOCK_COVERAGE.html[9/26/2012 2:20:20 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS CONDITIONAL COVERAGE Index


Asic Design
SystemVerilog Bottle Neck In Asic Flow
Verification Conditional coverage also called as expression coverage, will reveals how the Functional Verification
variables or sub-expressions in conditional statements are evaluated. Expressions with Need
Constructs logical operators are only considered.. The downside is that the conditional coverage Testbench
Interface measure doesn't take into consideration how the Boolean value was gotten from the Linear Testbench
conditions. Conditional coverage is the ratio of no. of cases checked to the total no. Linear Random
OOPS Testbench
of cases present. Suppose one expression having Boolean expression like AND or OR, so
Randomization entries which is given to that expression to the total possibilities is called expression How To Check The
coverage. Results
Functional Coverage Self Checking Testbenchs
Assertion How To Get Scenarios
     Conditional coverage report of the previous example: Which We Never Thought
DPI How To Check Whether
     At  LINE   13    
UVM Tutorial      Combinations of STATEMENT   c = (b && a) The Testbench Has
      B =  0  and a =   0  is  Covered Satisfactorily Exercised
VMM Tutorial The Design
      B =  0  and a =   1  is  Covered
OVM Tutorial       B =  1  and a =   0  is  Not Covered Types Of Code Coverage
      b =  1  and a =   1  is  Not Covered Statement Coverage
Easy Labs : SV
     Block Coverage
Easy Labs : UVM      At LINE   14 combinations of STATEMENT   if ((c && f)) Conditional Coverage
      C =  0  and  f = 0  is Covered Branch Coverage
Easy Labs : OVM
      C =  0  and  f = 1  is Not Covered Path Coverage
Easy Labs : VMM       C =  1  and  f = 0  is Not Covered Toggle Coverage
AVM Switch TB       C =  1  and  f = 1  is Not Covered Fsm Coverage
     Make Your Goal 100
VMM Ethernet sample      Total possible combinations: 8 Percent Code Coverage
     Total combinations executed: 3 Nothing Less
Functional Coverage
Verilog Coverage Driven
Constraint Random
Verification
Verification Architecture
Verilog Switch TB Phases Of Verification
Ones Counter Example
Basic Constructs
Verification Plan

Report a Bug or Comment


OpenVera on This section - Your
Constructs input is what keeps
Testbench.in improving
Switch TB
with time!
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/TS_14_CONDITIONAL_COVERAGE.html[9/26/2012 2:20:28 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TS_14_CONDITIONAL_COVERAGE.html[9/26/2012 2:20:28 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS BRANCH COVERAGE Index


Asic Design
SystemVerilog Bottle Neck In Asic Flow
Verification Branch coverage which is also called as Decision coverage report s the true or false of Functional Verification
the conditions like if-else, case and the ternary operator (? :) statements. For an "if" Need
Constructs statement, decision coverage will report whether the "if" statement is evaluated in Testbench
Interface both true and false cases, even if "else" statement doesn't exist. Linear Testbench
Linear Random
OOPS Testbench
Randomization How To Check The
   Branch coverage report of the example: Results
Functional Coverage Self Checking Testbenchs
  
Assertion    At line 15 branch b = e;    not covered       How To Get Scenarios
   At line 17 branch e = b;    covered Which We Never Thought
DPI How To Check Whether
   At line 20 branch 1: f = 1; not covered
UVM Tutorial    At line 21 branch 0: f = 0; covered The Testbench Has
   At line 22 branch default: f = 0; not covered Satisfactorily Exercised
VMM Tutorial The Design
  
OVM Tutorial    Coverage percentage: 40.00 (2/5) Types Of Code Coverage
Statement Coverage
Easy Labs : SV
Block Coverage
Easy Labs : UVM Conditional Coverage
Branch Coverage
Easy Labs : OVM
Path Coverage
Easy Labs : VMM Toggle Coverage
AVM Switch TB Fsm Coverage
Make Your Goal 100
VMM Ethernet sample Percent Code Coverage
Nothing Less
Functional Coverage
Verilog Coverage Driven
Constraint Random
Verification
Verification Architecture
Verilog Switch TB Phases Of Verification
Ones Counter Example
Basic Constructs
Verification Plan

Report a Bug or Comment


OpenVera on This section - Your
Constructs input is what keeps
Testbench.in improving
Switch TB
with time!
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/TS_15_BRANCH_COVERAGE.html[9/26/2012 2:20:37 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TS_15_BRANCH_COVERAGE.html[9/26/2012 2:20:37 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PATH COVERAGE Index


Asic Design
SystemVerilog Bottle Neck In Asic Flow
Verification Path coverage represents yet another interesting measure. Due to conditional Functional Verification
statements like if-else, case in the design different path is created which diverts the Need
Constructs flow of stimulus to the specific path. Testbench
Interface Linear Testbench
Linear Random
OOPS Testbench
Randomization How To Check The
Results
Functional Coverage Self Checking Testbenchs
Assertion How To Get Scenarios
Which We Never Thought
DPI How To Check Whether
UVM Tutorial The Testbench Has
Satisfactorily Exercised
VMM Tutorial The Design
OVM Tutorial Types Of Code Coverage
Statement Coverage
Easy Labs : SV
Block Coverage
Easy Labs : UVM Conditional Coverage
Branch Coverage
Easy Labs : OVM
Path Coverage
Easy Labs : VMM Toggle Coverage
AVM Switch TB Fsm Coverage
Make Your Goal 100
VMM Ethernet sample Percent Code Coverage
Nothing Less
Functional Coverage
Verilog Coverage Driven
Path coverage is considered to be more complete than branch coverage because it Constraint Random
Verification can detect the errors related to the sequence of operations. As mentioned in the Verification Architecture
above figure path will be decided according to the if-else statement According to the Phases Of Verification
Verilog Switch TB
applied stimulus the condition which is satisfied only under those expressions will Ones Counter Example
Basic Constructs execute, the path will be diverted according to that. Path coverage is possible in Verification Plan
always and function blocks . Path created by more than one block is not
covered.  Analysis of path coverage report is not so easy task.
Report a Bug or Comment
OpenVera on This section - Your
Constructs input is what keeps
Testbench.in improving
Switch TB     Path coverage report of the example:
with time!
    
RVM Switch TB
    Path 1 : 15,20  Not Covered
RVM Ethernet sample     Path 2 : 15,21  Not Covered
    Path 3:  15,22  Not Covered
    Path 4:  17,20  Not Covered
    Path 5 : 17,21  Covered
Specman E
    Path 6 : 17,22  Not Covered
Interview Questions     
    Total possible paths : 6
    Total covered path : 1
    Path coverage Percentage : 16.67  (1/6)

http://testbench.in/TS_16_PATH_COVERAGE.html[9/26/2012 2:20:44 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TS_16_PATH_COVERAGE.html[9/26/2012 2:20:44 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS TOGGLE COVERAGE Index


Asic Design
SystemVerilog Bottle Neck In Asic Flow
Verification It makes assures that how many times variables and nets toggled? Toggle coverage Functional Verification
could be as simple as the ratio of nodes toggled to the total number of nodes. Need
Constructs Testbench
Interface X or Z --> 1 or H Linear Testbench
X or Z --> 0 or L Linear Random
OOPS Testbench
1 or H --> X or Z
Randomization 0 or L --> X or Z How To Check The
Results
Functional Coverage Self Checking Testbenchs
Above example shows the signal changes from one level to another. All types of
Assertion transitions mentioned above are not interested. Only 1->0 and 0->1 are important. How To Get Scenarios
Toggle coverage will show which signal did not change the state. Toggle coverage will Which We Never Thought
DPI How To Check Whether
not consider zero-delay glitches.   This is very useful in gate level simulation.
UVM Tutorial The Testbench Has
Satisfactorily Exercised
VMM Tutorial The Design
Toggle coverage report of the example:
OVM Tutorial Types Of Code Coverage
 Name Toggled   1->0    0->1     Statement Coverage
Easy Labs : SV
   a    No        No      Yes     Block Coverage
Easy Labs : UVM    b    No        No      No       Conditional Coverage
   c    No        No      No       Branch Coverage
Easy Labs : OVM
   d    No        No      No       Path Coverage
Easy Labs : VMM    e    No        No      No       Toggle Coverage
AVM Switch TB    f    No        No      No       Fsm Coverage
Make Your Goal 100
VMM Ethernet sample Percent Code Coverage
Nothing Less
Functional Coverage
Verilog Coverage Driven
Constraint Random
Verification
Verification Architecture
Verilog Switch TB Phases Of Verification
Ones Counter Example
Basic Constructs
Verification Plan

Report a Bug or Comment


OpenVera on This section - Your
Constructs input is what keeps
Testbench.in improving
Switch TB
with time!
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/TS_17_TOGGLE_COVERAGE.html[9/26/2012 2:20:52 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TS_17_TOGGLE_COVERAGE.html[9/26/2012 2:20:52 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS FSM COVERAGE Index


Asic Design
SystemVerilog Bottle Neck In Asic Flow
Verification It is the most complex type of code coverage, because it works on the behavior of the Functional Verification
design. Using Finite state machine coverage, all bugs related to finite state machine Need
Constructs design can be found. In this coverage we look for how many times states are visited, Testbench
Interface transited and how many sequence are covered in a Finite state machine.   Linear Testbench
Linear Random
OOPS Testbench
Randomization How To Check The
State Coverage: Results
Functional Coverage Self Checking Testbenchs
Assertion How To Get Scenarios
It gives the coverage of no. of states visited over the total no. of states. Suppose you Which We Never Thought
DPI How To Check Whether
have N number of states and state machines transecting is in between only N-2 states
UVM Tutorial then coverage will give alert that some states are uncovered. It is advised that all the The Testbench Has
states must be covered. Satisfactorily Exercised
VMM Tutorial The Design
OVM Tutorial Types Of Code Coverage
Transition Coverage: Statement Coverage
Easy Labs : SV
Block Coverage
Easy Labs : UVM Conditional Coverage
It will count the no. of transition from one state to another and it will compare it with Branch Coverage
Easy Labs : OVM
other total no. of transition. Total no. of transition is nothing but all possible no. of Path Coverage
Easy Labs : VMM transition which is present in the finite state machine. Possible transition = no. of Toggle Coverage
AVM Switch TB states * no. of inputs. Fsm Coverage
Make Your Goal 100
VMM Ethernet sample Percent Code Coverage
EXAMPLE of FSM: Nothing Less
    module fsm (clk, reset, in); Functional Coverage
Verilog        input        clk, reset, in; Coverage Driven
       reg    [1:0] state; Constraint Random
Verification
     Verification Architecture
Verilog Switch TB        parameter s1 = 2'b00; parameter s2 = 2'b01; Phases Of Verification
       parameter s3 = 2'b10; parameter s4 = 2'b11; Ones Counter Example
Basic Constructs
     Verification Plan
       always @(posedge clk or posedge reset)
       begin Report a Bug or Comment
OpenVera           if (reset)  state <= s1; on This section - Your
Constructs           else  case (state) input is what keeps
         s1:if (in == 1'b1) state <= s2; Testbench.in improving
Switch TB
            else state <= s3; with time!
RVM Switch TB          s2: state <= s4; 
RVM Ethernet sample          s3: state <= s4; 
         s4: state <= s1; 
                endcase
        end
Specman E     endmodule
Interview Questions     
    module testbench();
       reg clk,reset,in;
      
       fsm dut(clk,reset,in);
      
       initial
          forever #5 clk = ~clk;
      
       initial
       begin

http://testbench.in/TS_18_FSM_COVERAGE.html[9/26/2012 2:20:59 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

          clk =0;in = 0;


          #2 reset = 0;#2 reset = 1;
          #21 reset = 0;#9 in = 0;
          #9 in = 1;#10 $finish;
       end
    
    endmodule

    FSM coverage report for the above example:


    
    // state coverage results
    s1                                | Covered
    s2                                | Not Covered
    s3                                | Covered
    s4                                | Covered
    // state transition coverage results
    s1->s2                            | Not Covered
    s1->s3                            | Covered
    s2->s1                            | Not Covered
    s2->s4                            | Not Covered
    s3->s1                            | Not Covered
    s3->s4                            | Covered
    s4->s1                            | Covered

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TS_18_FSM_COVERAGE.html[9/26/2012 2:20:59 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS MAKE YOUR GOAL 100 PERCENT CODE COVERAGE NOTHING LESS Index
Asic Design
SystemVerilog Bottle Neck In Asic Flow
Verification Never set your goal to anything less than 100% code coverage. Anything less than 100% Functional Verification
is a slippery slope. If you set your goal to 98% , may be the most important feature Need
Constructs like reset of the system may be in the untested part of2%.  If the verification engineer Testbench
Interface sets the code coverage goal to 95% to facilitate the 5% the unused untestable legacy Linear Testbench
code, there are chances that the unused legacy code gets executed and the 5% holes Linear Random
OOPS Testbench
may be in the important code.  100% code coverage provides advantages not only in
Randomization reducing the bug count but also in making it easier to make significant changes to How To Check The
existing code base to remove uncover able areas like the unused legacy blocks in RTL Results
Functional Coverage Self Checking Testbenchs
code.  
Assertion How To Get Scenarios
Dont Be Fooled By The Code Coverage Report Which We Never Thought
DPI How To Check Whether
UVM Tutorial Highly covered code isn't necessarily free of defects, although it's certainly less likely The Testbench Has
to contain them. By definition, code coverage is limited to the design code. It doesn't Satisfactorily Exercised
VMM Tutorial The Design
know anything about what design supposed to do. Even If a feature is not
OVM Tutorial implemented in design, code coverage can report 100% coverage.  It is also impossible Types Of Code Coverage
to determine whether we tested all possible values of a feature using code coverage. Statement Coverage
Easy Labs : SV
For example, randomization may not generate packets with all possible lengths, this Block Coverage
Easy Labs : UVM cannot be reported by code coverage.. Code coverage is unable to tell much about Conditional Coverage
how well you have covered your logic -- only whether you've executed each line/block Branch Coverage
Easy Labs : OVM
etc at least once. Code coverage does not provide information about your test bench Path Coverage
Easy Labs : VMM randomization quality and it does not report what caused the line execution/state Toggle Coverage
AVM Switch TB transition etc.  Analysis of code coverage require knowledge of design to find which Fsm Coverage
features are not verified which is time consuming and out of scope of verification Make Your Goal 100
VMM Ethernet sample engineer.  If the analysis is done at higher level of abstraction, it would be easier for Percent Code Coverage
the test writer to identify the missed serious which is not possible by code Nothing Less
coverage.  So if the code coverage is less than 100%, it means there is more work to Functional Coverage
Verilog do, if it is 100%, it doesn't mean that the verification is complete. Coverage Driven
Constraint Random
Verification
Verification Architecture
Verilog Switch TB When To Stop Testing? Phases Of Verification
Ones Counter Example
Basic Constructs
Verification Plan
It's getting harder to figure out when to stop testing as the complexity of the protocol
is increasing. In directed test environment, for each point mentioned in test plan, Report a Bug or Comment
OpenVera there will be a separate test case file. So if there are 100 points in test plan, then the on This section - Your
Constructs engineer has to write 100 test case files. After writing and executing the 100 test input is what keeps
case files, we can say that "all the points in test plan are verified" and we can stop Testbench.in improving
Switch TB
testing. with time!
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/TS_19_MAKE_YOUR_GOAL_100_PERCENT_CODE_COVERAGE_NOTHING_LESS.html[9/26/2012 2:21:07 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TS_19_MAKE_YOUR_GOAL_100_PERCENT_CODE_COVERAGE_NOTHING_LESS.html[9/26/2012 2:21:07 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS FUNCTIONAL COVERAGE Index


Asic Design
SystemVerilog Bottle Neck In Asic Flow
Verification In CRV, the each point in test plan is generated automatically. As there points are Functional Verification
generated automatically, we need a mechanism which tells us that all the points in Need
Constructs test plan are not exercised.  When all the points in testplans are verified and the code Testbench
Interface coverage is 100% we can stop verification. Linear Testbench
What are the untested features? Linear Random
OOPS Testbench
Randomization In Directed verification, there will be a separate testcase file for each feature to be How To Check The
verified. So to know how many features are verified, count the testcases.  Verification Results
Functional Coverage Self Checking Testbenchs
is done when all tests are coded and passing alone with 100% code coverage. In
Assertion constraint random verification all the features are generated randomly. Verification How To Get Scenarios
engineer need a mechanism to know the information about the verified features of Which We Never Thought
DPI How To Check Whether
DUT.
UVM Tutorial The Testbench Has
SystemVerilog provides a mechanism to know the untested feature using functional Satisfactorily Exercised
VMM Tutorial The Design
coverage. Functional Coverage is "instrumentation" that is manually added to the
OVM Tutorial TestBench.  This is a better approach then counting testcases.  Functional coverage is Types Of Code Coverage
better than code coverage where the code coverage reports what was exercised Statement Coverage
Easy Labs : SV
rather that what was tested. Block Coverage
Easy Labs : UVM Conditional Coverage
Branch Coverage
Easy Labs : OVM
Functional coverage answers questions like Path Coverage
Easy Labs : VMM Toggle Coverage
   Have all the packets length between 64 to 1518 are used?
AVM Switch TB Fsm Coverage
   Did the DUT got exercised with alternate packets with good and bad crc? Make Your Goal 100
VMM Ethernet sample    Did the monitor observe that the result comes with 4 clock cycles after read Percent Code Coverage
operation? Nothing Less
   Did the fifos are filled completely? Functional Coverage
Verilog Coverage Driven
Summary of functional coverage advantages: Constraint Random
Verification    Functional coverage helps determine how much of your specification was covered. Verification Architecture
Verilog Switch TB    Functional coverage qualifies the testbenchs. Phases Of Verification
   Considered as stopping criteria for unit level verification. Ones Counter Example
Basic Constructs
   Gives feedback about the untested features. Verification Plan
   Gives  the information about the redundant tests which consume valuable cycle.
Report a Bug or Comment
OpenVera    Guides to reach the goals earlier based on grading. on This section - Your
Constructs input is what keeps
Testbench.in improving
Switch TB
with time!
RVM Switch TB
Introduction To Functional Coverage:

RVM Ethernet sample SystemVerilog provides 2 ways to mention coverage.  Cover group which is uses
information from transactor, monitor and checker. Assertion coverage which is uses
temporal language which can be outside or inside RTL code.
Covergroup:
Specman E
Interview Questions There are three types of cover group points:
1. item functional coverage point
2. cross functional coverage point
3. transitional functional coverage point

Item

"Item" is used to capture the information about the sclare value.  A range of
interested values can also be observed.
For example, consider a packet protocol. The packet has a address field with possible

http://testbench.in/TS_20_FUNCTIONAL_COVERAGE.html[9/26/2012 2:21:17 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

values of A0,A1 and data which can be 4 to 10 bytes. At the end of packet parity is
also attached for integrity checking.
The following table identifies these coverage points for the above packet:

Item_DL     Data length     4 to 10


Item_ADD    Address         A0,A1
Item_Par    Parity          Good and Bad

Coverage engine collects item values are during simulation and reports.
Reports consists how many times
   Packets with length 4,5,6,7,8,9,10 are generated.
   Packets with good parity, bad parity are generated.
   Packets with address A0, A1 are generated.

Cross

"cross" is used to examine the cross product of two or more item coverage points.
Example:   verify DUT by sending both good parity and bad parity packets with all the
address.  

Cross_ ADD_Par    Item_ADD,Item_Par

Coverage report consists how many times


  Packets with Address A0 with good parity are generated
  Packets with Address A0 with bad parity are generated
  Packets with Address A1 with good parity are generated
  Packets with Address A1 with bad parity are generated

Transitional

Transitional functional point is used to examine the legal transitions of a value.


Example:
Verify the DUT with incremental packet length from 4 to 10.
Trans_length  ( 4  => 5  => 6 => 7 => 8 =>9 =>10)
Coverage engine reports whether this sequence is exercised or not.

Assertion Coverage:

Assertion coverage looks for the desired behavior in RTL. It uses assertion language
which is in temporal nature. It has direct access to design variables and designer can
add many points in RTL which he wants the verification engineer to cover.
Example:  Verify by sending back-to-back packets.

Functional coverage will be discussed in more detail in later chapters.

 Verification using functional coverage and randomization is called coverage driven


constraint random verification.

http://testbench.in/TS_20_FUNCTIONAL_COVERAGE.html[9/26/2012 2:21:17 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TS_20_FUNCTIONAL_COVERAGE.html[9/26/2012 2:21:17 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS COVERAGE DRIVEN CONSTRAINT RANDOM VERIFICATION Index


Asic Design
ARCHITECTURE Bottle Neck In Asic Flow
SystemVerilog
Verification Functional Verification
Need
Constructs Basic functionality of CDRV Environment: Testbench
Interface Linear Testbench
Input side of DUT : Linear Random
OOPS -- Generating traffic streams Testbench
-- Driving traffic into the design (stimuli) How To Check The
Randomization
Results
Functional Coverage Output side of DUT: Self Checking Testbenchs
-- Checking these data streams How To Get Scenarios
Assertion -- Checking protocols and timing Which We Never Thought
DPI How To Check Whether
Collecting both the functional coverage and code coverage information. The Testbench Has
UVM Tutorial
Satisfactorily Exercised
VMM Tutorial Writing deterministic tests and random tests to achieve 100% coverage. The Design
OVM Tutorial Types Of Code Coverage
Statement Coverage
Easy Labs : SV
Block Coverage
Easy Labs : UVM Conditional Coverage
Branch Coverage
Easy Labs : OVM
Path Coverage
Easy Labs : VMM Toggle Coverage
AVM Switch TB Fsm Coverage
Make Your Goal 100
VMM Ethernet sample Percent Code Coverage
Nothing Less
Functional Coverage
Verilog Coverage Driven
Constraint Random
Verification
Verification
Verilog Switch TB Architecture
Phases Of Verification
Basic Constructs
Ones Counter Example
Verification Plan

OpenVera Report a Bug or Comment


Constructs on This section - Your
input is what keeps
Switch TB
Testbench.in improving
RVM Switch TB with time!
RVM Ethernet sample
Verification Components Required For Cdcrv:

Specman E
     Stimulus
Interview Questions      Stimulus generator
     Transactor
     Driver
     Monitor
     Assertion monitor
     Checker
     Scoreboard
     Coverage
     Utilities
     Tests

http://testbench.in/TS_21_COVERAGE_DRIVEN_CONSTRAINT_RANDOM_VERIFICATION_ARCHITECTURE.html[9/26/2012 2:21:24 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

Stimulus:

When building a verification environment, the verification engineer often starts by


modeling the device input stimulus. In Verilog, the verification engineer is limited in
how to model this stimulus because of the lack of high-level data structures.
Typically, the verification engineer will create a array/memory to store the stimuli.
SystemVerilog provides high-level data structures and the notion of dynamic data
types for modeling stimulus. Using SystemVerilog randomization, stimulus is generated
automatically.  Stimulus is also processed in other verification components.
SystemVerilog high-level data structures helps in storing and processing of stimulus in
an efficient way.  

Stimulus Generator

The generator component generates stimulus which are sent to DUT by driver.
Stimulus generation is modeled to generate the stimulus based on the specification.
For simple memory stimulus generator generates read, write operations, address and
data to be stored in the address if its write operation.  Scenarios like generate
alternate read/write operations are specified in scenario generator. SystemVerilog
provided construct to control the random generation distribution and
order.  Constraints defined in stimulus are combinatioural in nature where as
constraints defined in stimulus generators are sequential in nature.

Stimulus generation can be directed or directed random or automatic and user should
have proper controllability from test case. It should also consider the generation of
stimulus which depends on the state of the DUT for example, Generating read cycle as
soon as interrupt is seen.  Error injection is a mechanism in which the DUT is verified
by sending error input stimulus.  Generally it is also taken care in this module.
Generally generator should be able to generate every possible scenario and the user
should be able to control the generation from directed and directed random testcases.

Transactor

Transactor does the high level operations like burst-operations into individual
commands, sub-layer protocol in layered protocol like PciExpress Transaction layer
over PciExpress Data Link Layer, TCP/IP over Ethernet etc. It also handles the DUT
configuration operations. This layer also provides necessary information to coverage
model about the stimulus generated. Stimulus generated in generator is high level like
Packet is with good crc, length is 5 and da is 8<92>h0.  This high level stimulus is
converted into low level data using packing. This low level data is just a array of bits
or bytes. Packing is an operation in which the high level stimulus values scalars,
strings, array elements and struct are concatenated in the specified manner.

Driver

The drivers translate the operations produced by the generator into the actual inputs
for the design under verification. Generators create inputs at a high level of
abstraction namely, as transactions like read write operation. The drivers convert this
input into actual design inputs, as defined in the specification of the designs
interface. If the generator generates read operation, then read task is called, in that,
the DUT input pin "read_write" is asserted.

http://testbench.in/TS_21_COVERAGE_DRIVEN_CONSTRAINT_RANDOM_VERIFICATION_ARCHITECTURE.html[9/26/2012 2:21:24 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

Monitor

Monitor reports the protocol violation and identifies all the transactions. Monitors are
two types, Passive and active. Passive monitors do not drive any signals.  Active
monitors can drive the DUT signals. Sometimes this is also refered as
receiver.  Monitor converts the state of the design and its outputs to a transaction
abstraction level so it can be stored in a 'score-boards' database to be checked later
on.  Monitor converts the pin level activities in to high level.

Assertion Based Monitor

Assertions are used to check time based protocols, also known as temporal checks.
Assertions are a necessary compliment to transaction based testing as they describe
the pin level, cycle by cycle, protocols of the design. Assertions are also used for
functional coverage.  

Data Checker

The monitor only monitors the interface protocol. It doesn't check the whether the
data is same as expected data or not, as interface has nothing to do with the date.
Checker converts the low level data to high level data and validated the data. This
operation of converting low level data to high level data is called Unpacking which is
reverse of packing operation. For example, if data is collected from all the commands
of the burst operation and then the data is converted in to raw data , and all the sub
fields information are extracted from the data and compared against the expected
values. The comparison state is sent to scoreboard.  

Scoreboard

Scoreboard is sometimes referred as tracker. Scoreboard stores the expected DUT


output. Scoreboard in Verilog tends to be cumbersome, rigid, and may use up much
memory due to the lack of dynamic data types and memory allocation. Dynamic data
types and Dynamic memory allocation makes it much easier to write a scoreboard in
SystemVerilog.  The stimulus generator generated the random vectors and is sent to
the DUT using drivers. These stimuli are stored in scoreboard until the output comes
out of the DUT. When a write operation is done on a memory with address 101 and
data 202, after some cycles, if a read is done at address 101, what should be the
data?.The score board recorded the address and data when write operation is done.
Get the data stored at address of 101 in scoreboard and compare with the output of
the DUT in checker module. Scoreboard also has expected logic if needed. Take a 2
inputs and gate. The expect logic does the "and " operation on the two inputs and
stores the output".

Coverage

This component has all the coverage related to the functional coverage groups.

Utilities

Utilities are set of global tasks which are not related to any protocol. So this module
can be reused across projects without any modification to code. Tasks such as global
timeout, printing messages control, seeding control, test pass/fail conditions, error
counters etc. The tasks defined in utilities are used by all other components of the
TestBench.

Environment:

Environment contains the instances of all the verification component and Component
connectivity is also done.  Steps required for execution of each component is done in
this.

Tests

Tests contain the code to control the TestBench features. Tests can communicate with
all the TestBench components. Once the TestBench is in place, the verification
engineer now needs to focus on writing tests to verify that the device behaves
according to specification.

http://testbench.in/TS_21_COVERAGE_DRIVEN_CONSTRAINT_RANDOM_VERIFICATION_ARCHITECTURE.html[9/26/2012 2:21:24 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TS_21_COVERAGE_DRIVEN_CONSTRAINT_RANDOM_VERIFICATION_ARCHITECTURE.html[9/26/2012 2:21:24 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PHASES OF VERIFICATION Index


Asic Design
SystemVerilog Bottle Neck In Asic Flow
Verification Functional Verification
Need
Constructs Testbench
Interface Linear Testbench
Linear Random
OOPS Testbench
Randomization How To Check The
Results
Functional Coverage Self Checking Testbenchs
Assertion How To Get Scenarios
Which We Never Thought
DPI How To Check Whether
UVM Tutorial The Testbench Has
Satisfactorily Exercised
VMM Tutorial The Design
OVM Tutorial Types Of Code Coverage
Statement Coverage
Easy Labs : SV
Block Coverage
Easy Labs : UVM Conditional Coverage
Branch Coverage
Easy Labs : OVM
Path Coverage
Easy Labs : VMM Toggle Coverage
AVM Switch TB Fsm Coverage
Make Your Goal 100
VMM Ethernet sample Percent Code Coverage
Nothing Less
Functional Coverage
Verilog Coverage Driven
Constraint Random
Verification
Verification Plan Verification Architecture
Verilog Switch TB Phases Of Verification
Ones Counter Example
Basic Constructs
In test plan, we prepare a road map for how do achieve the goal, it is a living Verification Plan
document. Test plan includes, introduction, assumptions, list of test cases, list of
features to be tested, approach, deliverables, resources, risks and scheduling, entry Report a Bug or Comment
OpenVera
and exit criteria.  Test plan helps verification engineer to understand how the on This section - Your
Constructs verification should be done. A test plan could come in many forms, such as a input is what keeps
Switch TB spreadsheet, a document or a simple text file. Sometimes, test plan simply reside in Testbench.in improving
the engineer's head which is dangerous in which the process cannot be properly with time!
RVM Switch TB measured and controlled.   Test plan also contains the descriptions of TestBench
RVM Ethernet sample architecture and description of each component and its functionality.

Building Testbench
Specman E
Interview Questions
In this phase, the verification environment is developed.  Each verification component
can be developed one by one or if more than one engineer is working it can be
developed parallel.  Writing the coverage module can be done at any time. It is
preffered to write down the coverage module first as it gives some idea of the
verification progress.

Writing Tests

http://testbench.in/TS_22_PHASES_OF_VERIFICATION.html[9/26/2012 2:21:32 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

After the TestBench is built and integrated to DUT, it's time for validating the
DUT.  Initially in CDV, the test are ran randomly till some 70 % of coverage is reached
or no improvement in the coverage for 1 day simulation.  By analyzing the coverage
reports, new tests are written to cover the holes. In these tests, randomization is
directed to cover the holes. Then finally, the hard to reach scenarios, called as corner
cases have to be written in directed verification fashion.   Of course, debugging is
done in parallel and DUT fixes are done.

Integrating Code Coverage

Once you have achieved certain level of functional coverage, integrate the code
coverage.  For doing code coverage, the code coverage tools have option to switch it
on. And then do the simulation, the tool will provide the report.

Analyze Coverage

Finally analyze both functional coverage and code coverage reports and take
necessary steps to achieve coverage goals.  Run simulation again with a different
seed, all the while collecting functional coverage information.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TS_22_PHASES_OF_VERIFICATION.html[9/26/2012 2:21:32 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS ONES COUNTER EXAMPLE Index


Asic Design
SystemVerilog Bottle Neck In Asic Flow
Verification Following example is TestBench for ones counter. It has some verification components Functional Verification
which are required, but not all the verification components discussed earlier. All the Need
Constructs components implementation can be seen in further chapters with another protocol. Testbench
Interface Description of the language construct is discussed in further chapters, so don't pay Linear Testbench
attention to them. The intention of showing this example is to make you familiar with Linear Random
OOPS Testbench
some steps required while building verification environment and to help you to
Randomization understand the flow discussed above.   How To Check The
Results
Functional Coverage Self Checking Testbenchs
Assertion Specification: How To Get Scenarios
Which We Never Thought
DPI How To Check Whether
UVM Tutorial Ones Counter is a Counter which counts the number of one's coming in serial stream. The Testbench Has
The Minimum value of the count is "0" and count starts by incriminating one till Satisfactorily Exercised
VMM Tutorial The Design
"15".  After "15" the counter rolls back to "0".  Reset is also provided to reset the
OVM Tutorial counter value to "0". Reset signal is active negedge. Input is 1 bit port for which the Types Of Code Coverage
serial stream enters. Out bit is 4 bit port from where the count values can be taken. Statement Coverage
Easy Labs : SV
Reset and clock pins also provided. Block Coverage
Easy Labs : UVM Conditional Coverage
Branch Coverage
Easy Labs : OVM
Path Coverage
Easy Labs : VMM Toggle Coverage
AVM Switch TB Fsm Coverage
Make Your Goal 100
VMM Ethernet sample Percent Code Coverage
Nothing Less
Functional Coverage
Verilog Coverage Driven
Constraint Random
Verification
Verification Architecture
Verilog Switch TB Phases Of Verification
Ones Counter Example
Basic Constructs
Verification Plan

Report a Bug or Comment


OpenVera on This section - Your
Constructs The following is the RTL code of onescounter with bugs. input is what keeps
Testbench.in improving
Switch TB
with time!
RVM Switch TB      module dff(clk,reset,din,dout);
RVM Ethernet sample           input clk,reset,din;
          output dout;
          logic dout;
          
Specman E           always@(posedge clk,negedge reset)
Interview Questions                if(!reset)
                   dout <= 0;
               else
                   dout <= din;
     endmodule
    
     module ones_counter(clk,reset,data,count);
           input clk,reset,data;
           output [0:3] count;
        
           dff d1(clk,reset,data,count[0]);

http://testbench.in/TS_23_ONES_COUNTER_EXAMPLE.html[9/26/2012 2:21:40 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

           dff d2(count[0],reset,~count[1],count[1]);


           dff d3(count[1],reset,~count[2],count[2]);
           dff d4(count[2],reset,~count[3],count[3]);
        
     endmodule
    
Test Plan:

This is a simple testplan. Features to be verified are


1)      Count should increment from "0" to "15".( Coverage item)
2)      Count should roolover to "0" after "15".(Coverage transition)
3)      Reset should make the output count to "0", when the count values is non "0". (
Assertion coverage)

Block Diagram:

Verification Environment Hierarchy

TOP
|-- Clock generator
|-- Dut Instance
|-- Interface
|-- Assertion block instance ( assertion coverage)
|-- Testcase instance
           |-- Environment
                   |-- Driver
                   |     |-- Stimulus
                   |     |-- Covergroup
                   |-- Monitor
                   |-- Scoreboard

http://testbench.in/TS_23_ONES_COUNTER_EXAMPLE.html[9/26/2012 2:21:40 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

Testbench Components:

Stimulus

Stimulus is a single bit value.  

class stimulus;
  rand  bit value;
  constraint distribution {value dist { 0  := 1 , 1 := 1 }; } 
endclass

Driver

This driver consists of reset and drive method.  Reset method resets the DUT and drive
method generates the stimulus and sends it to DUT. Driver also calculates the
expected DUT output and stores in scoreboard. Coverage is also sampled in this
component. Feature 1 and 2 which are mentioned in Testplan are covered in this
cover group.

 
   class driver;
        stimulus sti;
        Scoreboard sb;
  
        covergroup cov;
             Feature_1: coverpoint sb.store ;
             Feature_2 :  coverpoint  sb.store  {  bins trans = ( 15 => 0) ;} 
        endgroup
        
        virtual intf_cnt intf;
        
        function new(virtual intf_cnt intf,scoreboard sb);
             this.intf = intf;
             this.sb = sb;
             cov = new();
        endfunction
        
        task reset();  // Reset method
             intf.data = 0;
             @ (negedge intf.clk);
             intf.reset = 1;
             @ (negedge intf.clk);
             intf.reset = 0;
             @ (negedge intf.clk);
             intf.reset = 1;
        endtask
        
        task drive(input integer iteration);
             repeat(iteration)
             begin
                  sti = new();

http://testbench.in/TS_23_ONES_COUNTER_EXAMPLE.html[9/26/2012 2:21:40 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

                  @ (negedge intf.clk);
                  if(sti.randomize()) // Generate stimulus
                      intf.data = sti.value; // Drive to DUT
                  sb.store = sb.store + sti.value;// Cal exp value and store in Scoreboard
                  if(sti.value)
                      cov.sample();
             end
        endtask
   endclass

Monitor

The monitor collects the DUT output and then gets the expected value from the score
board and compares them.

    class monitor;
          scoreboard sb;
          virtual intf_cnt intf;
          
          function new(virtual intf_cnt intf,scoreboard sb);
               this.intf = intf;
               this.sb = sb;
          endfunction
          
          task check();
              forever
              @ (negedge intf.clk)
              if(sb.store != intf.count) // Get expected value from scoreboard and
compare with DUT output
                  $display(" * ERROR * DUT count is %b :: SB count is %b
", intf.count,sb.store );
              else
                  $display("           DUT count is %b :: SB count is %b ", intf.count,sb.store );
          endtask
    endclass

Assertion Coverage

This block contains the assertion coverage related to 3 rd feature mentioned in


testplan.

    module assertion_cov(intf_cnt intf);
       Feature_3 : cover property (@(posedge intf.clk)  (intf.count !=0)  |-> intf.reset
== 0 );
    endmodule

Scoreboard

This scoreboard is a simple one which stores one expected value.

   class scoreboard;
       bit [0:3] store;
   endclass

Environment:

Environment contains instances of driver, monitor and scoreboard.  

     class environment;
           driver drvr;
           scoreboard sb;
           monitor mntr;
           virtual intf_cnt intf;
          
           function new(virtual intf_cnt intf);
                 this.intf = intf;
                 sb = new();
                 drvr = new(intf,sb);
                 mntr = new(intf,sb);
                 fork 
                     mntr.check();
                 join_none
           endfunction

http://testbench.in/TS_23_ONES_COUNTER_EXAMPLE.html[9/26/2012 2:21:40 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

          
     endclass
    

Top:

The interface is declared and the test bench and DUT instances are taken. Testbench
and DUT are connected using interfaces.  Clock is also generated and connects it to
DUT and testbench.

   interface intf_cnt(input clk);

      wire clk;
      wire reset;
      wire data;
      wire [0:3] count;

   endinterface
            
  
   module top();
      reg clk = 0;
      initial  // clock generator
      forever #5 clk = ~clk;
      
      // DUT/assertion monitor/testcase instances
      intf_cnt intf(clk);
      ones_counter DUT(clk,intf.reset,intf.data,intf.count);
      testcase test(intf);
      assertion_cov acov(intf);
   endmodule

Tests:

This is a simple test case.  It does reset and then send 10 input values.

    program testcase(intf_cnt intf);
         environment env = new(intf);
        
         initial
         begin
              env.drvr.reset();
              env.drvr.drive(10);
         end
    endprogram

After simulating with this testcase, the coverage report I got

Total Coverage Summary

SCORE   ASSERT    GROUP
9.38    0.00       18.75

Cover group report


VARIABLE   EXPECTED UNCOVERED COVERED PERCENT GOAL WEIGHT  
Feature_1   16      10          6      37.50    100 1
Feature_2    1      1           0       0.00    100 1

Assertion coverage report:


COVER      PROPERTIES CATEGORY SEVERITY ATTEMPTS MATCHES INCOMPLETE
Feature_3  0          0           13    0          0

This coverage report will be different if you simulate in your tool.


To improve the coverage, than the 1st testcase , I wrote 2nd testcase with more input
values and also logic related to 3 feature in the testplan.

program testcase(intf_cnt intf);
  environment env = new(intf);
  
  initial

http://testbench.in/TS_23_ONES_COUNTER_EXAMPLE.html[9/26/2012 2:21:40 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

  begin
    env.drvr.reset();
    env.drvr.drive(100);
    env.drvr.reset();
    env.drvr.drive(100);
  end
endprogram

Download the phase 1 files:

ones_counter.tar
Browse the code in ones_counter.tar

Run the simulation:


your_tool_command -f filelist test_1.sv
your_tool_command -f filelist test_2.sv

Simulation Log Report:


           DUT count is 0xxx :: SB count is 0000 
           DUT count is 0xxx :: SB count is 0000 
           DUT count is 0000 :: SB count is 0000 
           DUT count is 0000 :: SB count is 0000 
 * ERROR * DUT count is 1111 :: SB count is 0001 
 * ERROR * DUT count is 0111 :: SB count is 0001 
 * ERROR * DUT count is 0111 :: SB count is 0001 
 * ERROR * DUT count is 0111 :: SB count is 0001 
 * ERROR * DUT count is 1011 :: SB count is 0010 
 * ERROR * DUT count is 1011 :: SB count is 0011 
           DUT count is 0011 :: SB count is 0011 
           DUT count is 0011 :: SB count is 0011 
 * ERROR * DUT count is 1101 :: SB count is 0100

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TS_23_ONES_COUNTER_EXAMPLE.html[9/26/2012 2:21:40 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS VERIFICATION PLAN Index


Asic Design
SystemVerilog Bottle Neck In Asic Flow
Verification Functional Verification
The Verification Plan is the focal point for defining exactly what needs to be tested, Need
Constructs and drives the coverage criteria.  Success of a verification project relies heavily on Testbench
Interface the completeness and accurate implementation of a verification plan. A good plan Linear Testbench
contains detailed goals using measurable metrics, along with optimal resource usage Linear Random
OOPS Testbench
and realistic schedule estimates. Verification plan gives an opportunity to present and
Randomization review the strategy for functional verification before the verification engineer have How To Check The
gone into detail to implement it. It also establishes proper communication. Just Results
Functional Coverage Self Checking Testbenchs
imagine how it would be working with a multisite project and you have a query for
Assertion which you have to wait till the next day to see the answer in email and they just call How To Get Scenarios
you while you are in sleep.  It also gives an idea about the areas that are going to be Which We Never Thought
DPI How To Check Whether
difficult to verify for taking necessary steps.  It is used to determine the progress and
UVM Tutorial completion of the verification phase of verification.  Verification Planning should start The Testbench Has
early with system/architecture evaluation phase.  Once the functional spec is given to Satisfactorily Exercised
VMM Tutorial The Design
the verification team, they will start its development.  
OVM Tutorial Types Of Code Coverage
A verification plan could come in many forms, such as a spreadsheet, a document or a Statement Coverage
Easy Labs : SV
simple text file. Templates are good if continually used in your company as it makes Block Coverage
Easy Labs : UVM common interface for information, reviewer know where to look for certain Conditional Coverage
information even in a huge document that he wants to know at this moment, because Branch Coverage
Easy Labs : OVM
different reviewers want different infomation in different moments. Path Coverage
Easy Labs : VMM Toggle Coverage
AVM Switch TB Generally Verification plan development is divided in two steps: What to verify and Fsm Coverage
How to verify? Make Your Goal 100
VMM Ethernet sample Step one:  What to Verify? Percent Code Coverage
list of clearly defined features-to-verify. This is called feature extraction phase. Nothing Less
Step two:  How to Verify? Functional Coverage
Verilog After defining what exactly need to be verified, define how to verify them. Coverage Driven
Constraint Random
Verification
Verification Architecture
Verilog Switch TB Verification Plan Contains The Following: Phases Of Verification
Ones Counter Example
Basic Constructs
   Overview Verification Plan
   Resources, Budget and Schedule
Report a Bug or Comment
OpenVera    Verification Environment on This section - Your
Constructs    System Verilog Verification Flow input is what keeps
   Feature Extraction Testbench.in improving
Switch TB
   Stimulus Generation Plan with time!
RVM Switch TB    Checker Plan
RVM Ethernet sample    Coverage Plan
   Details of reusable components

Specman E
Interview Questions

http://testbench.in/TS_24_VERIFICATION_PLAN.html[9/26/2012 2:21:48 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

Overview

This section contains description of the project, what specification is followed, what
languages and methodology are used.   Information related to the HW blocks, SW
blocks and HW/SW interaction is outlined.

Feature Extraction

This section contains list of all the features to be verified.  Generally each feature is
associated with

1.      Unique Name Id  


2.      Description
3.      Expected result
4.      Pointer to the specification
5.      priority.

The "Unique name ID" should be descriptive in nature to understand the nature of the
feature and should be unique.  For example,  <module name>_<sub module>_<feature
number>_<feature name>

Some points on how extraction the features:


       Read the MRD, System Specification, Macro and Micro Hardware Specification.
       Go through the designer notes/presentations.
       Annotate each line/paragraph specifying a functional item e.g.,  read/write a
register
       Annotate each line/paragraph specifying a multiple-functional items  e.g.,
steps required to set and cause an interrupt .
       Identify all RTL configurations
       Identify interfaces and related protocols across interface.
       Identify standards compliance requirements, list corner cases.
       Create a list of illegal scenarios to verify.
       Create a list of exceptions to verify.
       Create a list of operation sequences to verify e.g., interrupt followed by
breakpoint etc.
       Create a list of things to try and break the machine.
       Take advantage of existing plans.
       Use points from compliance checklist for standard protocols.
       Get information about the Common tests for all chips.
       Get review by a number of people, usually very experienced engineers. Better
if you get reviewed by Architects, micro Architects, Leads, verification engineers, RTL
Designers, software designers, marketing team and other team members.

http://testbench.in/TS_24_VERIFICATION_PLAN.html[9/26/2012 2:21:48 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

Resources, Budget And Schedule

This section contains details of man power required and schedule for each phase of
the verification.   Information about the tools which are used for simulation, debugger
and bug tracking are listed.  

Verification Environment

A detailed TestBench architecture is essential for a robust verification


environment.  In this section describe the topology, about each component of the
TestBench, special techniques that are used, IPs, Reused blocks, new blocks, and
guidelines on how to reuse the TestBench components.  For example if you think
upfront about   error injection, configuration, component communication, callbacks
etc, you can provide hooks to do those.  

System Verilog Verification Flow

Details about each level (block, sub-system, system) and phases (RTL, gate) of
verification are mentioned.

Stimulus Generation Plan

The stimulus generation section contains information about different types of


transactions, sequences of transactions and various scenarios generated as per the
specification.
  
Each point is associated with

1.      Unique name ID
2.      Stimulus to be generated for driving into the DUT
3.      Configuration/constraints Information

Checker Plan

This section will explain the expected result checking's in the TestBench. This can be
done in monitor/checker.

Various fields associated with each of the point are:

1.      Checker Unique name


2.      Unique Feature ID(Defined in Feature plan)
3.      Checker Description

Coverage Plan

The coverage section explains the functional coverage of the features. A functional
coverage plan should be built to help implement coverage points in the verification
environment.  Genarally it would be better if the coverage block is brocken based on
the design logical blocks.  It will list the various Coverage groups and assertion.  

Various fields of the coverage plan section are:

1.      Coverage Group
2.      Coverage Description
3.      Coverage name
4.      Unique name ID (Defined in feature plan)
5.      Cover point (Items/cross/transition/assertion)

http://testbench.in/TS_24_VERIFICATION_PLAN.html[9/26/2012 2:21:48 PM]


WWW.TESTBENCH.IN - Systemverilog for Verification

6.      Coverage goal

Details Of Reusable Components

This section contains the details of reusable components and the description about
their usage.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TS_24_VERIFICATION_PLAN.html[9/26/2012 2:21:48 PM]


WWW.TESTBENCH.IN - UVM Tutorial

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INTRODUCTION Index


Introduction
SystemVerilog Uvm Testbench
Verification Uvm Reporting
ahe UVM (Universal Verification Methodology) Class Library provides the building Uvm Transaction
Constructs blocks needed to quickly develop well-constructed and reusable verification Uvm Configuration
Interface components and test environments in SystemVerilog. Uvm Factory
Uvm Sequence 1
OOPS Uvm Sequence 2
UVM library contains:
Randomization Component classes for building testbench components like Uvm Sequence 3
generator/driver/monitor etc. Uvm Sequence 4
Functional Coverage Uvm Sequence 5
Reporting classes for logging, Uvm Sequence 6
Assertion
Factory for object substitution. Uvm Tlm 1
DPI Synchronization classes for managing concurrent process. Uvm Tlm 2
UVM Tutorial Policy classes for printing, comparing, recording, packing, and unpacking of Uvm Callback
uvm_object based classes.
VMM Tutorial
TLM Classes for transaction level interface. Report a Bug or Comment
OVM Tutorial Sequencer and Sequence classes for generating realistic stimulus. on This section - Your
And Macros which can be used for shorthand notation of complex implementation. input is what keeps
Easy Labs : SV
Testbench.in improving
Easy Labs : UVM with time!
Easy Labs : OVM In this tutorial, we will learn some of the UVM concepts with examples.
Easy Labs : VMM
AVM Switch TB Installing Uvm Library
VMM Ethernet sample
1)Go to http://www.accellera.org/activities/vip/
2)Download the uvm*.tar.gz file.
Verilog 3)Untar the file.
Verification 4)Go to the extracted directory  : cd uvm*\uvm\src
5)Set the UVM_HOME path  :  setenv UVM_HOME `pwd`  
Verilog Switch TB (This is required to run the examples which are downloaded from this site)
Basic Constructs 6)Go to examples :  cd  ../examples/hello_world/uvm/
7)Compile the example using :
 your_tool_compilation_command   -f  compile_<toolname>.f
 (example for questasim use :  qverilog -f compile_questa.f)
OpenVera 8)Run the example.
Constructs
Switch TB
 
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/UT_01_INTRODUCTION.html[9/26/2012 2:21:56 PM]


WWW.TESTBENCH.IN - UVM Tutorial

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/UT_01_INTRODUCTION.html[9/26/2012 2:21:56 PM]


WWW.TESTBENCH.IN - UVM Tutorial

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS UVM TESTBENCH Index


Introduction
SystemVerilog Uvm Testbench
Verification Uvm components, uvm env and uvm test are the three main building blocks of a Uvm Reporting
testbench in uvm based verification. Uvm Transaction
Constructs Uvm Configuration
Interface Uvm Factory
Uvm_env Uvm Sequence 1
OOPS Uvm Sequence 2
Randomization uvm_env is extended from uvm_component and does not contain any extra Uvm Sequence 3
functionality. uvm_env is used to create and connect the uvm_components like driver, Uvm Sequence 4
Functional Coverage Uvm Sequence 5
monitors ,  sequeners etc.  A environment class can also be used as sub-environment
Assertion in another environment.  As there is no difference between uvm_env and Uvm Sequence 6
uvm_component , we will discuss about uvm_component, in the next section.   Uvm Tlm 1
DPI Uvm Tlm 2
UVM Tutorial Uvm Callback
VMM Tutorial Verification Components
Report a Bug or Comment
OVM Tutorial uvm verification component classes are derived from uvm_component class which on This section - Your
Easy Labs : SV provides features like hierarchy searching, phasing, configuration , reporting , factory input is what keeps
and transaction recording.   Testbench.in improving
Easy Labs : UVM with time!
Easy Labs : OVM Following are some of the uvm component classes
uvm_agent
Easy Labs : VMM
uvm_monitor
AVM Switch TB uvm_scoreboard
VMM Ethernet sample uvm_driver
uvm_sequencer

Verilog NOTE: uvm_env and uvm_test are also extended from uvm_component.
Verification A typical uvm verification environment:
Verilog Switch TB
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

An agent typically contains three subcomponents: a driver, sequencer, and

http://testbench.in/UT_02_UVM_TESTBENCH.html[9/26/2012 2:22:06 PM]


WWW.TESTBENCH.IN - UVM Tutorial

monitor.  If the agent is active, subtypes should contain all three subcomponents.  If
the agent is passive, subtypes should contain only the monitor.

About Uvm_component Class:

uvm_compoenent class is inherited from uvm_report_object which is inherited from


uvm_object.
As I mentioned previously, uvm_component class provides features like hierarchy
searching, phasing, configuration , reporting , factory and transaction recording.
We will discuss about phasing concept in this section and rest of the features will be
discussed as separate topics.  

UVM phases

UVM Components execute their behavior in strictly ordered, pre-defined phases. Each
phase is defined by its own virtual method, which derived components can override to
incorporate component-specific behavior. By default , these methods do nothing.

--> virtual function void build()

This phase is used to construct various child components/ports/exports and configures


them.

--> virtual function void connect()

This phase is used for connecting the ports/exports of the components.

--> virtual function void end_of_elaboration()

This phase is used for configuring the components if required.

--> virtual function void start_of_simulation()

This phase is used to print the banners and topology.

--> virtual task run()

In this phase , Main body of the test is executed where all threads are forked off.

--> virtual function void extract()

In this phase, all the required information is gathered.

--> virtual function void check()

In this phase, check the results of the extracted information such as un responded
requests in scoreboard, read statistics registers etc.

--> virtual function void report()

http://testbench.in/UT_02_UVM_TESTBENCH.html[9/26/2012 2:22:06 PM]


WWW.TESTBENCH.IN - UVM Tutorial

This phase is used for reporting the pass/fail status.

Only  build() method is executed in top down manner. i.e after executing


parent  build() method, child objects build() methods are executed.  All other
methods are executed in bottom-up manner.  The run() method is the only method
which is time consuming. The run() method is forked, so the order in which all
components run() method are executed is undefined.

Uvm_test

uvm_test is derived from uvm_component class and there is no extra functionality is


added.  The advantage of used uvm_test for defining the user defined test is that the
test case selection can be done from command line option
+UVM_TESTNAME=<testcase_string> . User can also select the testcase by passing the
testcase name as string to uvm_root::run_test(<testcase_string>)  method.

In the above <testcase_string> is the  object type of the testcase class.

 
Lets implement environment for the following topology. I will describe the
implementation of environment , testcase and top module. Agent, monitor and driver
are implemented similar to environment.  

1)Extend uvm_env class and define user environment.

    class env extends uvm_env;

2)Declare the utility macro. This utility macro provides the implementation of create()
and get_type_name() methods and all the requirements needed for factory.

    `uvm_component_utils(env)

3)Declare the objects for agents.

   agent ag1;
   agent ag2;

4)Define the constructor. In the constructor, call the super methods and pass the
parent object. Parent is the object in which environment is instantiated.

    function new(string name , uvm_component parent = null);


        super.new(name, parent);
    endfunction: new

5)Define build method. In the build method, construct the agents.


To construct agents, use  create() method.  The advantage of create() over new() is
that when create() method is called, it will check if there is a factory override and
constructs the object of override type.

   function void build();
       super.build();

http://testbench.in/UT_02_UVM_TESTBENCH.html[9/26/2012 2:22:06 PM]


WWW.TESTBENCH.IN - UVM Tutorial

       uvm_report_info(get_full_name(),"Build", UVM_LOW);
       ag1 = agent::type_id::create("ag1",this);  
       ag2 = agent::type_id::create("ag2",this);  
   endfunction

6)Define
connect(),end_of_elaboration(),start_of_simulation(),run(),extract(),check(),report()
methods.
Just print a message from these methods, as we dont have any logic in this example
to define.

     function void connect();
        uvm_report_info(get_full_name(),"Connect", UVM_LOW);
     endfunction

Complete code of environment class:

class env extends uvm_env;

 `uvm_component_utils(env)
  agent ag1;
  agent ag2;
  
 function new(string name, uvm_component parent);
     super.new(name, parent);
 endfunction

 function void build();
     uvm_report_info(get_full_name(),"Build", UVM_LOW);
     ag1 = agent::type_id::create("ag1",this);  
     ag2 = agent::type_id::create("ag2",this);  
 endfunction

 function void connect();
     uvm_report_info(get_full_name(),"Connect", UVM_LOW);
 endfunction

 function void end_of_elaboration();
     uvm_report_info(get_full_name(),"End_of_elaboration", UVM_LOW);
 endfunction

 function void start_of_simulation();
     uvm_report_info(get_full_name(),"Start_of_simulation", UVM_LOW);
 endfunction

 task run();
     uvm_report_info(get_full_name(),"Run", UVM_LOW);
 endtask

 function void extract();
     uvm_report_info(get_full_name(),"Extract", UVM_LOW);
 endfunction

 function void check();
     uvm_report_info(get_full_name(),"Check", UVM_LOW);
 endfunction

 function void report();
     uvm_report_info(get_full_name(),"Report", UVM_LOW);
 endfunction

endclass

Now we will implement the testcase.


1)Extend uvm_test and define the test case

   class test1 extends uvm_test;

2)Declare component ustilits using utility macro.

   `uvm_component_utils(test1)

http://testbench.in/UT_02_UVM_TESTBENCH.html[9/26/2012 2:22:06 PM]


WWW.TESTBENCH.IN - UVM Tutorial

2)Declare environment class handle.

   env t_env;

3)Define constructor method. In the constructor, call the super method and construct
the environment object.

    function new (string name="test1", uvm_component parent=null);
        super.new (name, parent);
        t_env = new("t_env",this);
    endfunction : new 

4)Define the end_of_elaboration method. In this method, call the print() method. This
print() method will print the topology of the test.

    function void end_of_elaboration();
        uvm_report_info(get_full_name(),"End_of_elaboration", UVM_LOW);
        print();
    endfunction

4)Define the run method and call the global_stop_request() method.

    task run ();
        #1000;
        global_stop_request();
    endtask : run

Testcase source code:

class test1 extends uvm_test;

   `uvm_component_utils(test1)
    env t_env;
 
    function new (string name="test1", uvm_component parent=null);
        super.new (name, parent);
        t_env = new("t_env",this);
    endfunction : new 

    function void end_of_elaboration();
        uvm_report_info(get_full_name(),"End_of_elaboration", UVM_LOW);
        print();
    endfunction
 
    task run ();
        #1000;
        global_stop_request();
    endtask : run

endclass

Top Module:

To start the testbench, run_test() method must be called from initial block.
Run_test() mthod Phases all components through all registered phases.

module top;

  initial
      run_test();

endmodule

Download the source code

uvm_phases.tar
Browse the code in uvm_phases.tar

Command to run the simulation

http://testbench.in/UT_02_UVM_TESTBENCH.html[9/26/2012 2:22:06 PM]


WWW.TESTBENCH.IN - UVM Tutorial

VCS Users : make vcs


Questa Users: make questa

Log file:

[RNTST] Running test test1...


uvm_test_top.t_env [uvm_test_top.t_env] Build
uvm_test_top.t_env.ag1 [uvm_test_top.t_env.ag1] Build
uvm_test_top.t_env.ag1.drv [uvm_test_top.t_env.ag1.drv] Build
uvm_test_top.t_env.ag1.mon [uvm_test_top.t_env.ag1.mon] Build
uvm_test_top.t_env.ag2 [uvm_test_top.t_env.ag2] Build
uvm_test_top.t_env.ag2.drv [uvm_test_top.t_env.ag2.drv] Build
uvm_test_top.t_env.ag2.mon [uvm_test_top.t_env.ag2.mon] Build
uvm_test_top.t_env.ag1.drv [uvm_test_top.t_env.ag1.drv] Connect
uvm_test_top.t_env.ag1.mon [uvm_test_top.t_env.ag1.mon] Connect
uvm_test_top.t_env.ag1 [uvm_test_top.t_env.ag1] Connect
uvm_test_top.t_env.ag2.drv [uvm_test_top.t_env.ag2.drv] Connect
uvm_test_top.t_env.ag2.mon [uvm_test_top.t_env.ag2.mon] Connect
uvm_test_top.t_env.ag2 [uvm_test_top.t_env.ag2] Connect
uvm_test_top.t_env [uvm_test_top.t_env] Connect
uvm_test_top.t_env.ag1.drv [uvm_test_top.t_env.ag1.drv] End_of_elaboration
uvm_test_top.t_env.ag1.mon [uvm_test_top.t_env.ag1.mon] End_of_elaboration
uvm_test_top.t_env.ag1 [uvm_test_top.t_env.ag1] End_of_elaboration
uvm_test_top.t_env.ag2.drv [uvm_test_top.t_env.ag2.drv] End_of_elaboration
uvm_test_top.t_env.ag2.mon [uvm_test_top.t_env.ag2.mon] End_of_elaboration
uvm_test_top.t_env.ag2 [uvm_test_top.t_env.ag2] End_of_elaboration
uvm_test_top.t_env [uvm_test_top.t_env] End_of_elaboration
uvm_test_top [uvm_test_top] End_of_elaboration
----------------------------------------------------------------------
Name                     Type                Size                Value
----------------------------------------------------------------------
uvm_test_top             test1               -          uvm_test_top@2
  t_env                  env                 -                 t_env@4
    ag1                  agent               -                   ag1@6
      drv                driver              -                  drv@12
        rsp_port         uvm_analysis_port   -             rsp_port@16
        sqr_pull_port    uvm_seq_item_pull_+ -        sqr_pull_port@14
      mon                monitor             -                  mon@10
    ag2                  agent               -                   ag2@8
      drv                driver              -                  drv@20
        rsp_port         uvm_analysis_port   -             rsp_port@24
        sqr_pull_port    uvm_seq_item_pull_+ -        sqr_pull_port@22
      mon                monitor             -                  mon@18

uvm_test_top.t_env.ag1.drv[uvm_test_top.t_env.ag1.drv]Start_of_simulation
uvm_test_top.t_env.ag1.mon[uvm_test_top.t_env.ag1.mon]Start_of_simulation
uvm_test_top.t_env.ag1[uvm_test_top.t_env.ag1]Start_of_simulation
uvm_test_top.t_env.ag2.drv[uvm_test_top.t_env.ag2.drv]Start_of_simulation
uvm_test_top.t_env.ag2.mon[uvm_test_top.t_env.ag2.mon]Start_of_simulatio

..
..
..
..

Observe the above log report:

1)Build method was called in top-down fashion. Look at the following part of message.

uvm_test_top.t_env [uvm_test_top.t_env] Build


uvm_test_top.t_env.ag1 [uvm_test_top.t_env.ag1] Build
uvm_test_top.t_env.ag1.drv [uvm_test_top.t_env.ag1.drv] Build
uvm_test_top.t_env.ag1.mon [uvm_test_top.t_env.ag1.mon] Build
uvm_test_top.t_env.ag2 [uvm_test_top.t_env.ag2] Build
uvm_test_top.t_env.ag2.drv [uvm_test_top.t_env.ag2.drv] Build
uvm_test_top.t_env.ag2.mon [uvm_test_top.t_env.ag2.mon] Build

2)Connect method was called in bottopm up fashion. Look at the below part of log
file,

http://testbench.in/UT_02_UVM_TESTBENCH.html[9/26/2012 2:22:06 PM]


WWW.TESTBENCH.IN - UVM Tutorial

uvm_test_top.t_env.ag1.drv [uvm_test_top.t_env.ag1.drv] Connect


uvm_test_top.t_env.ag1.mon [uvm_test_top.t_env.ag1.mon] Connect
uvm_test_top.t_env.ag1 [uvm_test_top.t_env.ag1] Connect
uvm_test_top.t_env.ag2.drv [uvm_test_top.t_env.ag2.drv] Connect
uvm_test_top.t_env.ag2.mon [uvm_test_top.t_env.ag2.mon] Connect
uvm_test_top.t_env.ag2 [uvm_test_top.t_env.ag2] Connect
uvm_test_top.t_env [uvm_test_top.t_env] Connect

3)Following part of log file shows the testcase topology.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/UT_02_UVM_TESTBENCH.html[9/26/2012 2:22:06 PM]


WWW.TESTBENCH.IN - UVM Tutorial

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS UVM REPORTING Index


Introduction
SystemVerilog The uvm_report_object provides an interface to the UVM reporting facility.  Through Uvm Testbench
Verification this interface, components issue the various messages with different severity levels Uvm Reporting
that occur during simulation. Users can configure what actions are taken and what Uvm Transaction
Constructs file(s) are output for individual messages from a particular component or for all Uvm Configuration
Interface messages from all components in the environment.   Uvm Factory
Uvm Sequence 1
OOPS Uvm Sequence 2
A report consists of an id string, severity, verbosity level, and the textual message
Randomization itself.   If the verbosity level of a report is greater than the configured maximum Uvm Sequence 3
verbosity level of its report object, it is ignored. Uvm Sequence 4
Functional Coverage Uvm Sequence 5
Assertion Reporting Methods: Uvm Sequence 6
Uvm Tlm 1
DPI Uvm Tlm 2
Following are the primary reporting methods in the UVM.
UVM Tutorial Uvm Callback
VMM Tutorial virtual function void uvm_report_info
  (string id,string message,int verbosity=UVM_MEDIUM,string filename="",int line=0) Report a Bug or Comment
OVM Tutorial on This section - Your
virtual function void uvm_report_warning input is what keeps
Easy Labs : SV
  (string id,string message,int verbosity=UVM_MEDIUM,string filename="",int line=0) Testbench.in improving
Easy Labs : UVM with time!
Easy Labs : OVM virtual function void uvm_report_error
  (string id,string message,int verbosity=UVM_LOW,   string filename="",int line=0)
Easy Labs : VMM
AVM Switch TB virtual function void uvm_report_fatal
  (string id,string message,int verbosity=UVM_NONE,  string filename="",int line=0)
VMM Ethernet sample
Arguments description:

Verilog id -- a unique id to form a group of messages.


Verification
Verilog Switch TB
message -- The message text

Basic Constructs verbosity -- the verbosity of the message, indicating its relative importance. If this
number is less than or equal to the effective verbosity level, then the report is issued,
subject to the configured action and file descriptor settings.  
OpenVera
Constructs filename/line -- If required to print filename and line number from where the
message is issued, use macros, `__FILE__ and `__LINE__.
Switch TB
RVM Switch TB
Actions:
RVM Ethernet sample
These methods associate the specified action or actions with reports of the given
severity, id, or severity-id pair.
Specman E
Following are the actions defined:
Interview Questions
UVM_NO_ACTION -- Do nothing
UVM_DISPLAY -- Display report to standard output
UVM_LOG  -- Write to a file
UVM_COUNT -- Count up to a max_quit_count value before exiting
UVM_EXIT -- Terminates simulation immediately
UVM_CALL_HOOK -- Callback the hook method .

Configuration:

http://testbench.in/UT_03_UVM_REPORTING.html[9/26/2012 2:22:14 PM]


WWW.TESTBENCH.IN - UVM Tutorial

Using these methods, user can set the verbosity levels and set actions.

function void set_report_verbosity_level
     (int verbosity_level)
function void set_report_severity_action
     (uvm_severity severity,uvm_action action)
function void set_report_id_action
     (string id,uvm_action action)
function void set_report_severity_id_action
     (uvm_severity severity,string id,uvm_action action) 

Example

Lets see an example:

In the following example, messages from rpting::run() method are of different


verbosity level. In the top module, 3 objects of rpting are created and different
verbosity levels are set using set_report_verbosity_level() method.  

`include "uvm.svh"
 import uvm_pkg::*;

class rpting extends uvm_component;

  `uvm_component_utils(rpting)
 
  function new(string name,uvm_component parent);
    super.new(name, parent);
  endfunction

  task run();

    uvm_report_info(get_full_name(),
      "Info Message : Verbo lvl - UVM_NONE  ",UVM_NONE,`__FILE__,`__LINE__);

    uvm_report_info(get_full_name(),
      "Info Message : Verbo lvl - UVM_LOW   ",UVM_LOW);

http://testbench.in/UT_03_UVM_REPORTING.html[9/26/2012 2:22:14 PM]


WWW.TESTBENCH.IN - UVM Tutorial

    uvm_report_info(get_full_name(),
      "Info Message : Verbo lvl - 150       ",150);

    uvm_report_info(get_full_name(),
      "Info Message : Verbo lvl - UVM_MEDIUM",UVM_MEDIUM);

    uvm_report_warning(get_full_name(),
      "Warning Messgae from rpting",UVM_LOW);

    uvm_report_error(get_full_name(),
      "Error Message from rpting \n\n",UVM_LOW);
  endtask

endclass

module top;

 rpting rpt1;
 rpting rpt2;
 rpting rpt3;

 initial begin
   rpt1 = new("rpt1",null);
   rpt2 = new("rpt2",null);
   rpt3 = new("rpt3",null);

   rpt1.set_report_verbosity_level(UVM_MEDIUM);
   rpt2.set_report_verbosity_level(UVM_LOW);
   rpt3.set_report_verbosity_level(UVM_NONE);
   run_test();

 end
endmodule

Download the source code

uvm_reporting.tar
Browse the code in uvm_reporting.tar

Command to run the simulation

VCS Users : make vcs


Questa Users: make questa

Log file:

UVM_INFO reporting.sv(13)@0:rpt1[rpt1]Info Message:Verbo lvl - UVM_NONE  


UVM_INFO @0:rpt1[rpt1] Info Message : Verbo lvl - UVM_LOW  
UVM_INFO @0:rpt1[rpt1] Info Message : Verbo lvl - 150      
UVM_INFO @0:rpt1[rpt1] Info Message : Verbo lvl - UVM_MEDIUM
UVM_WARNIN@0:rpt[rpt1] Warning Messgae from rpting
UVM_ERROR @0:rpt1[rpt1] Error Message from rpting

UVM_INFOreporting.sv(13)@0:rpt2[rpt2]Info Message:Verbo lvl - UVM_NONE  


UVM_INFO@ 0:rpt2[rpt2] Info Message : Verbo lvl - UVM_LOW  
UVM_WARNING@0:rpt2[rpt2] Warning Messgae from rpting
UVM_ERROR@0:rpt2[rpt2] Error Message from rpting

UVM_INFOreporting.sv(13)@0:rpt3[rpt3]Info Message:Verbo lvl - UVM_NONE  


UVM_ERROR @ 9200 [TIMOUT] Watchdog timeout of '23f0' expired.

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/UT_03_UVM_REPORTING.html[9/26/2012 2:22:14 PM]


WWW.TESTBENCH.IN - UVM Tutorial

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/UT_03_UVM_REPORTING.html[9/26/2012 2:22:14 PM]


WWW.TESTBENCH.IN - UVM Tutorial

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS UVM TRANSACTION Index


Introduction
SystemVerilog Uvm Testbench
Verification A transaction is data item which is eventually or directly processed by the DUT. The Uvm Reporting
packets, instructions, pixels are data items. In uvm, transactions are extended from Uvm Transaction
Constructs uvm_transactions class or  uvm_sequence_item class. uvm_transaction is a typedef of Uvm Configuration
Interface uvm_sequence_item. Uvm Factory
Uvm Sequence 1
OOPS Uvm Sequence 2
Randomization Example of a transaction: Uvm Sequence 3
Uvm Sequence 4
Functional Coverage Uvm Sequence 5
class Packet extends uvm_transaction;
Assertion     rand bit [7:0] da; Uvm Sequence 6
    rand bit [7:0] sa; Uvm Tlm 1
DPI Uvm Tlm 2
    rand bit [7:0] length;
UVM Tutorial     rand bit [7:0] data[]; Uvm Callback
VMM Tutorial     rand byte fcs;
endclass Report a Bug or Comment
OVM Tutorial on This section - Your
input is what keeps
Easy Labs : SV
Core Utilities: Testbench.in improving
Easy Labs : UVM with time!
Easy Labs : OVM uvm_transaction class is extended from uvm_object.  uvm_transaction adds more
features line transaction recording , transaction id  and timings of the transaction.
Easy Labs : VMM
AVM Switch TB The methods used to model, transform or operate on transactions like print, copying,
cloning, comparing, recording, packing and unpacking are already defined in
VMM Ethernet sample uvm_object.

Verilog
Verification
Verilog Switch TB
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

FIG:  UVM OBJECT UTILITIES

User Defined Implementations:

User should define these methods in the transaction using do_<method_name> and
call them using <method_name>.  Following table shows calling methods and user-
defined hook do_<method_name> methods.  Clone and create methods, does not
use  hook methods concepts.

http://testbench.in/UT_04_UVM_TRANSACTION.html[9/26/2012 2:22:22 PM]


WWW.TESTBENCH.IN - UVM Tutorial

Shorthand Macros:

Using the field automation concept of uvm, all the above defines methods can be
defined automatically.
To use these field automation macros, first declare all the data fields, then place the
field automation macros between the `uvm_object_utils_begin and
`uvm_object_utils_end macros.

Example of field automation macros:

class Packet extends uvm_transaction;
  
   rand bit [7:0] da;
   rand bit [7:0] sa;
   rand bit [7:0] length;
   rand bit [7:0] data[];
   rand byte      fcs;

    `uvm_object_utils_begin(Packet)
       `uvm_field_int(da, UVM_ALL_ON|UVM_NOPACK)
       `uvm_field_int(sa, UVM_ALL_ON|UVM_NOPACK)
       `uvm_field_int(length, UVM_ALL_ON|UVM_NOPACK)
       `uvm_field_array_int(data, UVM_ALL_ON|UVM_NOPACK)
       `uvm_field_int(fcs, UVM_ALL_ON|UVM_NOPACK)
    `uvm_object_utils_end

endclass.

For most of the data types in systemverilog, uvm defined corresponding field
automation macros. Following table shows all the field automation macros.

http://testbench.in/UT_04_UVM_TRANSACTION.html[9/26/2012 2:22:22 PM]


WWW.TESTBENCH.IN - UVM Tutorial

Each `uvm_field_* macro has at least two arguments: ARG and FLAG.
ARG is the instance name of the variable and FLAG is used to control the field usage in
core utilities operation.

Following table shows uvm field automation flags:

http://testbench.in/UT_04_UVM_TRANSACTION.html[9/26/2012 2:22:22 PM]


WWW.TESTBENCH.IN - UVM Tutorial

By default, FLAG is set to UVM_ALL_ON. All these flags can be ored. Using NO_* flags,
can turn of particular field usage in a paerticuler method. NO_* flags takes
precedency over other flags.

Example of Flags:

    `uvm_field_int(da, UVM_ALL_ON|UVM_NOPACK)

The above macro will use the field "da" in all utilities methods except Packing and
unpacking methods.

Lets see a example:

In the following example, all the utility methods are defined using field automation
macros except Packing and unpacking methods.  Packing and unpacking methods are
done  in do_pack() amd do_unpack() method.

 `include "uvm.svh"
 import uvm_pkg::*;

//Define the enumerated types for packet types


typedef enum { GOOD_FCS, BAD_FCS } fcs_kind_t;

class Packet extends uvm_transaction;

    rand fcs_kind_t     fcs_kind;
    
    rand bit [7:0] length;
    rand bit [7:0] da;
    rand bit [7:0] sa;
    rand bit [7:0] data[];
    rand byte fcs;
    
    constraint payload_size_c { data.size inside { [1 : 6]};}
    
    constraint length_c {  length == data.size; } 
                    
    function new(string name = "");
         super.new(name);
    endfunction : new
    
    function void post_randomize();
         if(fcs_kind == GOOD_FCS)
             fcs = 8'b0;
         else
            fcs = 8'b1;
         fcs = cal_fcs();
    endfunction : post_randomize
    
    ///// method to calculate the fcs /////
    virtual function byte cal_fcs;
         integer i;
         byte result ;
         result = 0;
         result = result ^ da;
         result = result ^ sa;
         result = result ^ length;
         for (i = 0;i< data.size;i++)
         result = result ^ data[i];
         result = fcs ^ result;
         return result;
    endfunction : cal_fcs
    
    `uvm_object_utils_begin(Packet)
       `uvm_field_int(da, UVM_ALL_ON|UVM_NOPACK)
       `uvm_field_int(sa, UVM_ALL_ON|UVM_NOPACK)
       `uvm_field_int(length, UVM_ALL_ON|UVM_NOPACK)
       `uvm_field_array_int(data, UVM_ALL_ON|UVM_NOPACK)
       `uvm_field_int(fcs, UVM_ALL_ON|UVM_NOPACK)

http://testbench.in/UT_04_UVM_TRANSACTION.html[9/26/2012 2:22:22 PM]


WWW.TESTBENCH.IN - UVM Tutorial

    `uvm_object_utils_end
    
    function void do_pack(uvm_packer packer);
        super.do_pack(packer);
        packer.pack_field_int(da,$bits(da));
        packer.pack_field_int(sa,$bits(sa));
        packer.pack_field_int(length,$bits(length));
        foreach(data[i])
          packer.pack_field_int(data[i],8);
        packer.pack_field_int(fcs,$bits(fcs));
    endfunction : do_pack
    
    function void do_unpack(uvm_packer packer);
        int sz;
        super.do_pack(packer);
    
        da = packer.unpack_field_int($bits(da));
        sa = packer.unpack_field_int($bits(sa));
        length = packer.unpack_field_int($bits(length));
        
        data.delete();
        data = new[length];
        foreach(data[i])
          data[i] = packer.unpack_field_int(8);
        fcs = packer.unpack_field_int($bits(fcs));
    endfunction : do_unpack

endclass : Packet

/////////////////////////////////////////////////////////
////    Test to check the packet implementation      ////
/////////////////////////////////////////////////////////
module test;

    Packet pkt1 = new("pkt1");


    Packet pkt2 = new("pkt2");
    byte unsigned pkdbytes[];

    initial
    repeat(10)
       if(pkt1.randomize)
       begin
          $display(" Randomization Sucessesfull.");
          pkt1.print();
          uvm_default_packer.use_metadata = 1;    
          void'(pkt1.pack_bytes(pkdbytes));
          $display("Size of pkd bits %d",pkdbytes.size());
          pkt2.unpack_bytes(pkdbytes);
          pkt2.print();
          if(pkt2.compare(pkt1))
              $display(" Packing,Unpacking and compare worked");
          else
              $display(" *** Something went wrong in Packing or Unpacking or compare ***
\n \n");
       end
       else
       $display(" *** Randomization Failed ***");
    
endmodule

Download the source code

uvm_transaction.tar
Browse the code in uvm_transaction.tar

Command to run the simulation

VCS Users : make vcs


Questa Users: make questa

Log report:

http://testbench.in/UT_04_UVM_TRANSACTION.html[9/26/2012 2:22:22 PM]


WWW.TESTBENCH.IN - UVM Tutorial

 Randomization Sucessesfull.
-------------------------------------------------------------------
---
Name                     Type                Size                Value
-------------------------------------------------------------------
---
pkt1                     Packet              -                  pkt1@3
  da                     integral            8                    'h1d
  sa                     integral            8                    'h26
  length                 integral            8                     'h5
  data                   da(integral)        5                       -
    [0]                  integral            8                    'hb1
    [1]                  integral            8                    'h3f
    [2]                  integral            8                    'h9e
    [3]                  integral            8                    'h38
    [4]                  integral            8                    'h8d
  fcs                    integral            8                    'h9b
-------------------------------------------------------------------
---
Size of pkd bits           9
-------------------------------------------------------------------
---
Name                     Type                Size                Value
-------------------------------------------------------------------
---
pkt2                     Packet              -                  pkt2@5
  da                     integral            8                    'h1d
  sa                     integral            8                    'h26
  length                 integral            8                     'h5
  data                   da(integral)        5                       -
    [0]                  integral            8                    'hb1
    [1]                  integral            8                    'h3f
    [2]                  integral            8                    'h9e
    [3]                  integral            8                    'h38
    [4]                  integral            8                    'h8d
  fcs                    integral            8                    'h9b
-------------------------------------------------------------------
---
 Packing,Unpacking and compare worked

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/UT_04_UVM_TRANSACTION.html[9/26/2012 2:22:22 PM]


WWW.TESTBENCH.IN - UVM Tutorial

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS UVM CONFIGURATION Index


Introduction
SystemVerilog Uvm Testbench
Verification Configuration is a  mechanism in UVM that higher level components in a hierarchy can Uvm Reporting
configure the lower level components variables. Using set_config_* methods, user can Uvm Transaction
Constructs configure integer, string and objects of lower level components. Without this Uvm Configuration
Interface mechanism, user should access the lower level component using hierarchy paths, Uvm Factory
which restricts reusability. This mechanism can be used only with components. Uvm Sequence 1
OOPS Uvm Sequence 2
Sequences and transactions cannot be configured using this mechanism. When
Randomization set_config_* method is called, the data is stored w.r.t strings in a table. There is also Uvm Sequence 3
a global configuration table. Uvm Sequence 4
Functional Coverage Uvm Sequence 5
Higher level component can set the configuration data in level component table. It is
Assertion the responsibility of the lower level component to get the data from the component Uvm Sequence 6
table and update the appropriate table. Uvm Tlm 1
DPI Uvm Tlm 2
UVM Tutorial Uvm Callback
VMM Tutorial Set_config_* Methods:
Report a Bug or Comment
OVM Tutorial Following are the method to configure integer , string and object of uvm_object on This section - Your
based class respectively. input is what keeps
Easy Labs : SV
Testbench.in improving
Easy Labs : UVM function void set_config_int (string inst_name, with time!
Easy Labs : OVM                               string field_name,
                              uvm_bitstream_t value)
Easy Labs : VMM
AVM Switch TB function void set_config_string (string inst_name,
                                 string field_name,
VMM Ethernet sample                                  string value)

function void set_config_object (string inst_name,  
Verilog                                  string field_name,  
Verification                    uvm_object value,  bit clone = 1)
Verilog Switch TB
Basic Constructs Arguments description:

string inst_name: Hierarchical string path.


OpenVera string field_name: Name of the field in the table.
Constructs
bitstream_t value: In set_config_int, a integral value that can be anything from 1
bit to 4096 bits.
Switch TB bit clone : If this bit is set then object is cloned.
RVM Switch TB
inst_name and field_name are strings of hierarchal path. They can include wile card
RVM Ethernet sample "*" and "?" characters. These methods must be called in build phase of the component.

Specman E
Interview Questions "*"  matches zero or more characters
"?"  matches exactly one character

Some examples:

"*"     -All the lower level components.

"*abc"  -All the lower level components which ends with "abc".


Example: "xabc","xyabc","xyzabc" ....

http://testbench.in/UT_05_UVM_CONFIGURATION.html[9/26/2012 2:22:30 PM]


WWW.TESTBENCH.IN - UVM Tutorial

"abc*"  -All the lower level components which starts  with "abc".


Example: "abcx","abcxy","abcxyz" ....

"ab?"   -All the lower level components which start with "ab" , then followed by one
more character.
Example: "abc","abb","abx" ....

"?bc"   -All the lower level components which start with any one character  ,then
followed by "c".
Example: "abc","xbc","bbc" ....

"a?c"   -All the lower level components which start with "a" , then followed by one
more character and then followed by "c".
Example: "abc","aac","axc" …..

There are two ways to get the configuration data:


1)Automatic : Using Field macros
2)Manual : using gte_config_* methods.

Automatic Configuration:

To use the atomic configuration, all the configurable fields should be defined using
uvm component field macros and uvm component utilities macros.

uvm component utility macros:


For non parameterized classes
`uvm_component_utils_begin(TYPE)
  `uvm_field_* macro invocations here
`uvm_component_utils_end
For parameterized classes.
`uvm_component_param_utils_begin(TYPE)
  `uvm_field_* macro invocations here
`uvm_component_utils_end

For UVM Field macros, Refer to link


UVM_TRANSACTION  

Example:
Following example is from link
UVM_TESTBENCH  

2 Configurable fields, a integer and a string are defined in env, agent, monitor and
driver classes. Topology of the environment using these classes is

http://testbench.in/UT_05_UVM_CONFIGURATION.html[9/26/2012 2:22:30 PM]


WWW.TESTBENCH.IN - UVM Tutorial

Driver class Source Code:

Similar to driver class, all other components env, agent and monitor are define.

class driver extends uvm_driver;

  integer int_cfg;
  string  str_cfg;

  `uvm_component_utils_begin(driver)
      `uvm_field_int(int_cfg, UVM_DEFAULT)
      `uvm_field_string(str_cfg, UVM_DEFAULT)
  `uvm_component_utils_end

  function new(string name, uvm_component parent);
      super.new(name, parent);
  endfunction

  function void build();
      super.build();
  endfunction

endclass

Testcase:

Using set_config_int() and set_config_string() configure variables at various hierarchal


locations.

    //t_env.ag1.drv.int_cfg
    //t_env.ag1.mon.int_cfg
    set_config_int("*.ag1.*","int_cfg",32);

    //t_env.ag2.drv
    set_config_int("t_env.ag2.drv","int_cfg",32);

    //t_env.ag2.mon
    set_config_int("t_env.ag2.mon","int_cfg",32);

    //t_env.ag1.mon.str_cfg
    //t_env.ag2.mon.str_cfg
    //t_env.ag1.drv.str_cfg
    //t_env.ag2.drv.str_cfg
    set_config_string("*.ag?.*","str_cfg","pars");

    //t_env.str_cfg
    set_config_string("t_env","str_cfg","abcd");

Download the source code

uvm_configuration_1.tar
Browse the code in uvm_configuration_1.tar

http://testbench.in/UT_05_UVM_CONFIGURATION.html[9/26/2012 2:22:30 PM]


WWW.TESTBENCH.IN - UVM Tutorial

Command to run the simulation

VCS Users : make vcs


Questa Users: make questa

From the above log report of th example, we can see the variables int_cfg and str_cfg
of all the components and they are as per the configuration setting from the testcase.

Manual Configurations:

Using get_config_* methods, user can get the required data if the data is available in
the table.
Following are the method to get configure data of type integer , string and object of
uvm_object based class respectively.

function bit get_config_int (string field_name,
                   inout uvm_bitstream_t value)

function bit get_config_string (string field_name,
                              inout string value)

function bit get_config_object (string field_name,
                          inout uvm_object value,
                             input bit clone = 1)

If a entry is found in the table with "field_name" then data will be updated to "value"
argument . If entry is not found, then the function returns "0". So when these
methods are called, check the return value.

Example: 
Driver class code:
class driver extends uvm_driver;

   integer int_cfg;
   string  str_cfg;

   `uvm_component_utils(driver)

   function new(string name, uvm_component parent);
       super.new(name, parent);
   endfunction

   function void build();
       super.build();
       void'(get_config_int("int_cfg",int_cfg));
       void'(get_config_string("str_cfg",str_cfg));
       uvm_report_info(get_full_name(),
       $psprintf("int_cfg %0d : str_cfg %0s ",int_cfg,str_cfg),UVM_LOW);
   endfunction

endclass 
Download the source code

uvm_configuration_2.tar
Browse the code in uvm_configuration_2.tar

Command to run the simulation

VCS Users : make vcs


Questa Users: make questa

Log file

UVM_INFO @ 0: uvm_test_top.t_env
     int_cfg x : str_cfg abcd
UVM_INFO @ 0: uvm_test_top.t_env.ag1  
     int_cfg x : str_cfg  
UVM_INFO @ 0: uvm_test_top.t_env.ag1.drv  
     int_cfg 32 : str_cfg pars

http://testbench.in/UT_05_UVM_CONFIGURATION.html[9/26/2012 2:22:30 PM]


WWW.TESTBENCH.IN - UVM Tutorial

UVM_INFO @ 0: uvm_test_top.t_env.ag1.mon
     int_cfg 32 : str_cfg pars
UVM_INFO @ 0: uvm_test_top.t_env.ag2
     int_cfg x : str_cfg  
UVM_INFO @ 0: uvm_test_top.t_env.ag2.drv
     int_cfg 32 : str_cfg pars
UVM_INFO @ 0: uvm_test_top.t_env.ag2.mon  
     int_cfg 32 : str_cfg pars

Configuration Setting Members:

print_config_settings
function void print_config_settings
             ( string  field  =  "",
              uvm_component  comp  =  null,
              bit  recurse  =  0 )

This method prints all configuration information for this component.


If "field" is specified and non-empty, then only configuration settings matching that
field, if any, are printed.  The field may not contain wildcards. If "recurse" is set, then
information for all children components are printed recursively.

print_config_matches
static bit print_config_matches = 0

Setting this static variable causes get_config_* to print info about matching
configuration settings as they are being applied. These two members will be helpful
to know while debugging.

Download the source code

uvm_configuration_3.tar
Browse the code in uvm_configuration_3.tar

Command to run the simulation

VCS Users : make vcs


Questa Users: make questa

Log file
When print_config_settings method is called

uvm_test_top.t_env.ag1.drv
   uvm_test_top.*.ag1.* int_cfg int     32
uvm_test_top.t_env.ag1.drv.rsp_port
   uvm_test_top.*.ag?.* str_cfg string  pars
uvm_test_top.t_env.ag1.drv.rsp_port
   uvm_test_top.*.ag1.* int_cfg int     32
uvm_test_top.t_env.ag1.drv.sqr_pull_port
   uvm_test_top.*.ag?.* str_cfg string  pars
uvm_test_top.t_env.ag1.drv.sqr_pull_port  
   uvm_test_top.*.ag1.* int_cfg int     32

When print_config_matches is set to 1.

UVM_INFO @ 0: uvm_test_top.t_env [auto-configuration]


Auto-configuration matches for component uvm_test_top.t_env (env).
Last entry for a given field takes precedence.

Config set from  Instance Path     Field name   Type    Value


------------------------------------------------------------------------------
uvm_test_top(test1) uvm_test_top.t_env str_cfg  string  abcd

http://testbench.in/UT_05_UVM_CONFIGURATION.html[9/26/2012 2:22:30 PM]


WWW.TESTBENCH.IN - UVM Tutorial

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/UT_05_UVM_CONFIGURATION.html[9/26/2012 2:22:30 PM]


WWW.TESTBENCH.IN - UVM Tutorial

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS UVM FACTORY Index


Introduction
SystemVerilog Uvm Testbench
Verification The factory pattern is an well known object-oriented design pattern. The factory Uvm Reporting
method design pattern defining a separate method for creating the objects. ,  whose Uvm Transaction
Constructs subclasses can then override to specify the derived type of object that will be Uvm Configuration
Interface created. Uvm Factory
Uvm Sequence 1
OOPS Uvm Sequence 2
Using this method, objects are constructed dynamically based on the specification
Randomization type of the object. User can alter the behavior of the pre-build code without Uvm Sequence 3
modifying the code. From the testcase, user from environment or testcase can replace Uvm Sequence 4
Functional Coverage Uvm Sequence 5
any object which is at any hierarchy level with the user defined object.
Assertion Uvm Sequence 6
For example: In your environment, you have a driver component. You would like the Uvm Tlm 1
DPI Uvm Tlm 2
extend the driver component for error injection scenario. After defining the extended
UVM Tutorial driver class  with error injection,  how will you  replace the base driver component Uvm Callback
VMM Tutorial which is deep in the hierarchy of your environment ?   Using hierarchical path, you
could replace the driver object with the extended driver. This could not be easy if Report a Bug or Comment
OVM Tutorial there are many driver objects. Then you should also take care of its connections with on This section - Your
the other components of testbenchs like scoreboard etc. input is what keeps
Easy Labs : SV
Testbench.in improving
Easy Labs : UVM One more example: In your Ethernet verification environment, you have different with time!
Easy Labs : OVM drivers to support different interfaces for 10mbps,100mps and 1G. Now you want to
reuse the same environment for 10G verification.  Inside somewhere deep in the
Easy Labs : VMM hierarchy, while building the components, as a driver components ,your current
AVM Switch TB environment can only select 10mmps/100mps/1G drivers using configuration
settings.  How to add one more driver to the current drivers list of drivers so that
VMM Ethernet sample from the testcase you could configure the environment to work for 10G.  

Using the uvm fatroy, it is very easy to solve the above two requirements.  Only classs
Verilog extended from uvm_object and uvm_component are supported for this.
Verification
There are three basic steps to be followed for using uvm factory.
Verilog Switch TB
Basic Constructs 1) Registration
2) Construction
3) Overriding
OpenVera
Constructs
The factory makes it is possible to override the type of uvm component /object  or
instance of a uvm component/object  in2 ways. They are based on uvm
Switch TB component/object type or  uvm compoenent/object  name.  
RVM Switch TB
Registration:
RVM Ethernet sample
While defining a class , its type has to be registered with the uvm factory. To do this
job easier, uvm has predefined macros.
Specman E
Interview Questions `uvm_component_utils(class_type_name)
`uvm_component_param_utils(class_type_name #(params))
`uvm_object_utils(class_type_name)
`uvm_object_param_utils(class_type_name #(params))

For uvm_*_param_utils are used for parameterized classes and other two macros for
non-parameterized class.  Registration is required for name-based overriding , it is
not required for type-based overriding.

EXAMPLE: Example of above macros

http://testbench.in/UT_06_UVM_FACTORY.html[9/26/2012 2:22:39 PM]


WWW.TESTBENCH.IN - UVM Tutorial

class packet extends uvm_object;
  `uvm_object_utils(packet)
endclass

class packet #(type T=int, int mode=0) extends uvm_object;
  `uvm_object_param_utils(packet #(T,mode))
endclass

class driver extends uvm_component;
  `uvm_component_utils(driver)
endclass

class monitor #(type T=int, int mode=0) extends uvm_component;
  `uvm_component_param_utils(driver#(T,mode))
endclass

Construction:

To construct a uvm based component or uvm based objects, static method create()
should be used. This function constructs the appropriate object based on the
overrides and constructs the object and returns it. So while constructing the uvm
based components or uvm based objects , do not use new() constructor.

Syntax :

static function T create(string name,    
                         uvm_component parent,  
                         string context = " ")

The Create() function returns an instance of the component type, T, represented by


this proxy, subject to any factory overrides based on the context provided by the
parents full name.  The context argument, if supplied, supersedes the parents
context.  The new instance will have the given leaf name and parent.

EXAMPLE:
class_type object_name;

object_name = clss_type::type_id::creat("object_name",this);

For uvm_object based classes, doesnt need the parent handle as second argument.

Overriding:

If required, user could override the registered classes or objects. User can override
based of name string or class-type.  

There are 4 methods defined for overriding:

function void set_inst_override_by_type
       (uvm_object_wrapper original_type,
        uvm_object_wrapper override_type,
        string full_inst_path )

The above method is used to override the object instances of "original_type" with
"override_type" . "override_type" is extended from"original_type".

function void set_inst_override_by_name
       (string original_type_name,
        string override_type_name,
        string full_inst_path )

http://testbench.in/UT_06_UVM_FACTORY.html[9/26/2012 2:22:39 PM]


WWW.TESTBENCH.IN - UVM Tutorial

Original_type_name and override_type_name are the class names which are registered
in the factory. All the instances of objects with name "Original_type_name" will be
overriden with objects of name "override_type_name" using
set_inst_override_by_name() method.

function void set_type_override_by_type
       (uvm_object_wrapper original_type,    
        uvm_object_wrapper override_type,    
        bit replace = 1 )

Using the above method, request to create an object of  original_type can be


overriden with override_type.

function void set_type_override_by_name
      (string original_type_name,    
       string override_type_name,    
       bit replace = 1)

Using the above method, request to create an object of  original_type_name can be


overriden with override_type_name.

When multiple overrides are done , then using the argument "replace" , we can
control whether to override the previous override or not. If argument "replace" is 1,
then previous overrides will be replaced otherwise, previous overrides will remain.  

print() method, prints the state of the uvm_factory, registered types, instance
overrides, and type overrides.

Now we will see a complete example. This example is based on the environment build
in topic UVM TESTBENCH . Refer to that section for more information about this
example.

Lets look at the 3 steps which I discussed above using the example defined in UVM
TESTBENCH

1) Registration

In all the class, you can see the macro  `uvm_component_utils(type_name)

2) Construction

In file agant.sv file,  monitor and driver are constructed using create() method.

mon = monitor::type_id::create("mon",this);
drv = driver::type_id::create("drv",this);

3)In this example, a one testcase is already developed in topic UVM_TESTBENCH.


There are no over rides in this test case.

Topology of this test environment is shown below.

http://testbench.in/UT_06_UVM_FACTORY.html[9/26/2012 2:22:39 PM]


WWW.TESTBENCH.IN - UVM Tutorial

In this example, there is one driver class and one monitor class.  In this testcase , By
extending driver class , we will define driver_2 class and by extending monitor class,
we will define monitor_2 class.

From the testcase , Using set_type_override_by_type, we will override driver with


driver_2 and Using set_type_override_by_name, we will override monitor with
monitor_2.

To know about the overrides which are done, call factory.print() method of factory
class.

class driver_2 extends driver;

   `uvm_component_utils(driver_2)

    function new(string name, uvm_component parent);
        super.new(name, parent);
    endfunction

endclass

class monitor_2 extends monitor;

   `uvm_component_utils(monitor_2)

    function new(string name, uvm_component parent);
        super.new(name, parent);
    endfunction

endclass

class test_factory extends uvm_test;

   `uvm_component_utils(test_factory)
    env t_env;
 
    function new (string name="test1", uvm_component parent=null);
        super.new (name, parent);

        factory.set_type_override_by_type(driver::get_type(),driver_2::get_type(),"*");
        factory.set_type_override_by_name("monitor","monitor_2","*");
        factory.print();
        t_env = new("t_env",this);
    endfunction : new 

    function void end_of_elaboration();
        uvm_report_info(get_full_name(),"End_of_elaboration", UVM_LOW);

http://testbench.in/UT_06_UVM_FACTORY.html[9/26/2012 2:22:39 PM]


WWW.TESTBENCH.IN - UVM Tutorial

        print();
    endfunction : end_of_elaboration
 
    task run ();
        #1000;
        global_stop_request();
    endtask : run

endclass

Download the example:

uvm_factory.tar
Browse the code in uvm_factory.tar

Command to simulate

Command to run the example with the testcase which is defined above:
VCS Users : make vcs
Questa Users: make questa

Method factory.print() displayed all the overrides as shown below in the log file.

#### Factory Configuration (*)

No instance overrides are registered with this factory


Type Overrides:

  Requested Type  Override Type


  --------------  -------------
  driver          driver_2
  monitor         monitor_2

In the below text printed by print_topology() method ,we can see overridden driver
and monitor.  

-------------------------------------------------------------------
---
Name                     Type                Size                Value
-------------------------------------------------------------------
---
uvm_test_top             test_factory        -          uvm_test_top@2
  t_env                  env                 -                 t_env@4
    ag1                  agent               -                   ag1@6
      drv                driver_2            -                  drv@12
        rsp_port         uvm_analysis_port   -             rsp_port@16
        sqr_pull_port    uvm_seq_item_pull_+ -        sqr_pull_port@14
      mon                monitor_2           -                  mon@10
    ag2                  agent               -                   ag2@8
      drv                driver_2            -                  drv@20
        rsp_port         uvm_analysis_port   -             rsp_port@24
        sqr_pull_port    uvm_seq_item_pull_+ -        sqr_pull_port@22
      mon                monitor_2           -                  mon@18
-------------------------------------------------------------------
---

In the below text printed by print_topology() method ,with testcase test1 which does
note have overrides.

Command to run this example with test1 is  


VCS Users : make vcs
Questa Users: make questa

-------------------------------------------------------------------
---
Name                     Type                Size                Value
-------------------------------------------------------------------
---
uvm_test_top             test1               -          uvm_test_top@2
  t_env                  env                 -                 t_env@4
    ag1                  agent               -                   ag1@6
      drv                driver              -                  drv@12
        rsp_port         uvm_analysis_port   -             rsp_port@16

http://testbench.in/UT_06_UVM_FACTORY.html[9/26/2012 2:22:39 PM]


WWW.TESTBENCH.IN - UVM Tutorial

        sqr_pull_port    uvm_seq_item_pull_+ -        sqr_pull_port@14
      mon                monitor             -                  mon@10
    ag2                  agent               -                   ag2@8
      drv                driver              -                  drv@20
        rsp_port         uvm_analysis_port   -             rsp_port@24
        sqr_pull_port    uvm_seq_item_pull_+ -        sqr_pull_port@22
      mon                monitor             -                  mon@18
-------------------------------------------------------------------
---

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/UT_06_UVM_FACTORY.html[9/26/2012 2:22:39 PM]


WWW.TESTBENCH.IN - UVM Tutorial

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS UVM SEQUENCE 1 Index


Introduction
SystemVerilog Introduction Uvm Testbench
Verification Uvm Reporting
Uvm Transaction
Constructs A sequence is a series of transaction.  User can define the complex stimulus. Uvm Configuration
Interface sequences can be reused, extended, randomized, and combined sequentially and Uvm Factory
hierarchically in various ways. Uvm Sequence 1
OOPS Uvm Sequence 2
 
Randomization For example, for a processor, lets say PUSH_A,PUSH_B,ADD,SUB,MUL,DIV and POP_C Uvm Sequence 3
are the instructions. If the instructions are generated randomly, then to excursing a Uvm Sequence 4
Functional Coverage Uvm Sequence 5
meaningful operation like "adding 2 variables" which requires a series of transaction
Assertion "PUSH_A  PUSH_B  ADD  POP_C " will take longer time. By defining these series of Uvm Sequence 6
"PUSH_A  PUSH_B  ADD  POP_C ", it would be easy to exercise the DUT. Uvm Tlm 1
DPI Uvm Tlm 2
UVM Tutorial Advantages of uvm sequences : Uvm Callback
VMM Tutorial Sequences can be reused.
Report a Bug or Comment
Stimulus generation is independent of testbench.
OVM Tutorial on This section - Your
Easy to control the generation of transaction. input is what keeps
Easy Labs : SV Sequences can be combined sequentially and hierarchically.   Testbench.in improving
Easy Labs : UVM with time!
A complete sequence generation requires following 4 classes.
Easy Labs : OVM 1- Sequence item.
Easy Labs : VMM 2- Sequence
3- Sequencer
AVM Switch TB 4- Driver
VMM Ethernet sample

uvm_sequence_item :
Verilog User has to define a transaction by extending
uvm_sequence_item.  uvm_sequence_item class provides the basic functionality for
Verification objects, both sequence items and sequences, to operate in the sequence mechanism.
Verilog Switch TB For more information about  uvm_sequence_item  Refer to link  
Basic Constructs
UVM_TRANSACTION  

uvm_sequence:
OpenVera User should extend uvm_sequence class and define the construction of sequence of
Constructs transactions. These transactions can be directed, constrained randomized or fully
randomized. The uvm_sequence class provides the interfaces necessary in order to
Switch TB
create streams of sequence items and/or other sequences.  
RVM Switch TB
RVM Ethernet sample
    virtual class uvm_sequence #(
       type REQ  =  uvm_sequence_item,
       type RSP  =  REQ
Specman E     )
Interview Questions
uvm_sequencer:
uvm_sequencer is responsible for the coordination between sequence and driver.
Sequencer sends the transaction to driver and gets the response from the driver. The
response transaction from the driver is optional. When multiple sequences are running
in parallel, then sequencer is responsible for arbitrating between the parallel
sequences. There are two types of sequencers : uvm_sequencer and
uvm_push_sequencer

http://testbench.in/UT_07_UVM_SEQUENCE_1.html[9/26/2012 2:22:50 PM]


WWW.TESTBENCH.IN - UVM Tutorial

    class uvm_sequencer #(
      type  REQ  =  uvm_sequence_item,
      type  RSP  =  REQ
    )
    
    class uvm_push_sequencer #(
      type  REQ  =  uvm_sequence_item,
      type  RSP  =  REQ
    )

uvm driver:
User should extend uvm_driver class to define driver component. uvm driver is a
component that initiate requests for new transactions and drives it to lower level
components. There are two types of drivers: uvm_driver and uvm_push_driver.

    class uvm_driver #(
      type  REQ  =  uvm_sequence_item,
      type  RSP  =  REQ
    ) 
    
    class uvm_push_driver #(
      type  REQ  =  uvm_sequence_item,
      type  RSP  =  REQ
    )

In pull mode , uvm_sequencer is connected to uvm_driver , in push


mode  uvm_push_sequencer is connectd to uvm_push_driver.  

uvm_sequencer and uvm_driver are parameterized components with request and


response transaction types. REQ and RSP types by default are uvm_sequence_type
types. User can specify REQ and RSP of different transaction types. If user specifies
only REQ type, then RSP will be REQ type.

Sequence And Driver Communication:

The above image shows how a transaction from a sequence is sent to driver and the
response from the driver is sent to sequencer.  There are multiple methods called
during this operation.

First when the body() method is called


1) A transaction is created using "create()" method. If a transaction is created using
"create()" method, then it can be overridden if required using uvm factory.

2) After a transaction is created, wait_for_grant() method is called. This method is


blocking method.

http://testbench.in/UT_07_UVM_SEQUENCE_1.html[9/26/2012 2:22:50 PM]


WWW.TESTBENCH.IN - UVM Tutorial

3) In the run task of the driver, when "seq_item_port.get_next_item()" is called, then


the sequencer un blocks wait_for_grant() method. If more than one sequence is
getting executed by sequencer, then based on arbitration rules, un blocks the
wait_for_grant() method.

4) After the wait_for_grant() un blocks, then transaction can be randomized, or its


properties can be filled directly. Then using the send_request() method, send the
transaction to the driver.

5) After calling the send_request() method, "wait_for_item_done()" method is called.


This is a blocking method and execution gets blocks at this method call.

6) The transaction which is sent from sequence , in the driver this transaction is
available as "seq_item_port.get_next_item(req)" method argument. Then driver can
drive this transaction to bus or lower level.

7) Once the driver operations are completed, then  by calling


"seq_item_port.put(rsp)", wait_for_item_done() method of sequence gest unblocked.
Using get_responce(res), the response transaction from driver is taken by sequence
and processes it.

After this step, again the steps 1 to 7 are repeated five times.

If a response from driver is not required, then steps 5,6,7 can be skipped and
item_done() method from driver should be called as shown in above image.

Simple Example

Lest write an example: This is a simple example of  processor instruction. Various


instructions which are supported by the processor are
PUSH_A,PUSH_B,ADD,SUB,MUL,DIV and POP_C.

Sequence Item

1) Extend uvm_sequence_item and define instruction class.

    class instruction extends uvm_sequence_item;

2) Define the instruction as enumerated types and declare a variable of instruction


enumerated type.

    typedef enum {PUSH_A,PUSH_B,ADD,SUB,MUL,DIV,POP_C} inst_t; 
    rand inst_t inst;

3) Define operational method using uvm_field_* macros.

   `uvm_object_utils_begin(instruction)
     `uvm_field_enum(inst_t,inst, UVM_ALL_ON)
   `uvm_object_utils_end

4) Define the constructor.

http://testbench.in/UT_07_UVM_SEQUENCE_1.html[9/26/2012 2:22:50 PM]


WWW.TESTBENCH.IN - UVM Tutorial

   function new (string name = "instruction");
      super.new(name);
   endfunction 

Sequence item code:


class instruction extends uvm_sequence_item;
  typedef enum {PUSH_A,PUSH_B,ADD,SUB,MUL,DIV,POP_C} inst_t; 
  rand inst_t inst;

  `uvm_object_utils_begin(instruction)
    `uvm_field_enum(inst_t,inst, UVM_ALL_ON)
  `uvm_object_utils_end

  function new (string name = "instruction");
    super.new(name);
  endfunction 

endclass

Sequence

We will define a operation addition using uvm_sequence. The instruction sequence


should be "PUSH A  PUSH B  ADD  POP C".
 
1) Define a sequence by extending uvm_sequence. Set REQ parameter to "instruction"
type.

    class operation_addition extends uvm_sequence #(instruction);

2) Define the constructor.

    function new(string name="operation_addition");
       super.new(name);
    endfunction

3) Lets name the sequencer which we will develop is "instruction_sequencer".


Using the `uvm_sequence_utils macro, register the "operation_addition" sequence
with "instruction_sequencer" sequencer. This macro adds the sequence to the
sequencer list. This macro will also register the sequence for factory overrides.

    `uvm_sequence_utils(operation_addition, instruction_sequencer)    

4)
In the body() method, first call wait_for_grant(), then construct a transaction and set
the instruction enum to PUSH_A . Then send the transaction to driver using
send_request() method. Then call the wait_for_item_done() method. Repeat the
above steps for other instructions PUSH_B, ADD and POP_C.
 
For construction of a transaction, we will use the create() method.

  virtual task body();
    req = instruction::type_id::create("req");
      wait_for_grant();
      assert(req.randomize() with {
         inst == instruction::PUSH_A;
      });
      send_request(req);
      wait_for_item_done();
      //get_response(res); This is optional. Not using in this example.

      req = instruction::type_id::create("req");
      wait_for_grant();
      req.inst = instruction::PUSH_B;
      send_request(req);
      wait_for_item_done();
      //get_response(res);

      req = instruction::type_id::create("req");
      wait_for_grant();
      req.inst = instruction::ADD;
      send_request(req);
      wait_for_item_done();
      //get_response(res);

http://testbench.in/UT_07_UVM_SEQUENCE_1.html[9/26/2012 2:22:50 PM]


WWW.TESTBENCH.IN - UVM Tutorial

      req = instruction::type_id::create("req");
      wait_for_grant();
      req.inst = instruction::POP_C;
      send_request(req);
      wait_for_item_done();
      //get_response(res);
  endtask

Sequence code

class operation_addition extends uvm_sequence #(instruction);

  instruction req;
 
  function new(string name="operation_addition");
    super.new(name);
  endfunction
  
  `uvm_sequence_utils(operation_addition, instruction_sequencer)    

  virtual task body();
    req = instruction::type_id::create("req");
      wait_for_grant();
      assert(req.randomize() with {
         inst == instruction::PUSH_A;
      });
      send_request(req);
      wait_for_item_done();
      //get_response(res); This is optional. Not using in this example.

      req = instruction::type_id::create("req");
      wait_for_grant();
      req.inst = instruction::PUSH_B;
      send_request(req);
      wait_for_item_done();
      //get_response(res);

      req = instruction::type_id::create("req");
      wait_for_grant();
      req.inst = instruction::ADD;
      send_request(req);
      wait_for_item_done();
      //get_response(res);

      req = instruction::type_id::create("req");
      wait_for_grant();
      req.inst = instruction::POP_C;
      send_request(req);
      wait_for_item_done();
      //get_response(res);
  endtask
  
endclass 

Sequencer:

uvm_sequence has  a property called default_sequence. Default sequence is a


sequence which will be started automatically. Using set_config_string, user can
override the default sequence to any user defined sequence, so that when a
sequencer is started, automatically a user defined sequence will be started.  If over
rides are not done with user defined sequence, then a random transaction are
generated.  Using "start_default_sequence()" method, "default_sequence" can also be
started.
uvm sequencer has seq_item_export and res_export tlm ports for connecting to uvm
driver.

1) Define instruction_sequencer by extending uvm_sequencer.

    class instruction_sequencer extends uvm_sequencer #(instruction);

2) Define the constructor.


Inside the constructor, place the macro `uvm_update_sequence_lib_and_item().
This macro creates 3 predefined sequences. We will discuss about the predefined

http://testbench.in/UT_07_UVM_SEQUENCE_1.html[9/26/2012 2:22:50 PM]


WWW.TESTBENCH.IN - UVM Tutorial

sequences in next section.

    function new (string name, uvm_component parent);
      super.new(name, parent);
      `uvm_update_sequence_lib_and_item(instruction)
    endfunction 

3) Place the uvm_sequencer_utils macro. This macro registers the sequencer for
factory overrides.

    `uvm_sequencer_utils(instruction_sequencer)

Sequencer Code;
class instruction_sequencer extends uvm_sequencer #(instruction);

  function new (string name, uvm_component parent);
    super.new(name, parent);
    `uvm_update_sequence_lib_and_item(instruction)
  endfunction 

  `uvm_sequencer_utils(instruction_sequencer)

endclass

Driver:

uvm_driver is a class which is extended from uvm_componenet. This driver is used in


pull mode. Pull mode means, driver pulls the transaction from the sequencer when it
requires.
uvm driver has 2 TLM ports.
1) Seq_item_port: To get a item from sequencer, driver uses this port. Driver can also
send response back using this port.
2) Rsp_port :  This can also be used to send response back to sequencer.

Seq_item_port methods:

Lets implement a driver:

1) Define a driver which takes the instruction from the sequencer and does the
processing. In this example we will just print the instruction type and wait for some
delay.

    class instruction_driver extends uvm_driver #(instruction);

2) Place the uvm_component_utils macro to define virtual methods like


get_type_name and create.

   `uvm_component_utils(instruction_driver)

3) Define  Constructor method.

http://testbench.in/UT_07_UVM_SEQUENCE_1.html[9/26/2012 2:22:50 PM]


WWW.TESTBENCH.IN - UVM Tutorial

    function new (string name, uvm_component parent);
      super.new(name, parent);
    endfunction 

4) Define the run() method. Run() method is executed in the "run phase". In this
methods, transactions are taken from the sequencer and drive them on to dut
interface or to other components.
Driver class has a port "seq_item_port". Using the method
seq_item_port.get_next_item(), get the transaction from the sequencer and process
it.  Once the processing is done, using the item_done() method, indicate to the
sequencer that the request is completed. In this example, after taking the
transaction, we will print the transaction and wait for 10 units time.  

  task run ();
    while(1) begin
      seq_item_port.get_next_item(req);
      $display("%0d: Driving Instruction  %s",$time,req.inst.name());
      #10;
      seq_item_port.item_done();
    end
  endtask

endclass 

Driver class code:

class instruction_driver extends uvm_driver #(instruction);

  // Provide implementations of virtual methods such as get_type_name and create


  `uvm_component_utils(instruction_driver)

  // Constructor
  function new (string name, uvm_component parent);
    super.new(name, parent);
  endfunction 

  task run ();
    forever begin
      seq_item_port.get_next_item(req);
      $display("%0d: Driving Instruction  %s",$time,req.inst.name());
      #10;
      // rsp.set_id_info(req);   These two steps are required only if
      // seq_item_port.put(esp); responce needs to be sent back to sequence
      seq_item_port.item_done();
    end
  endtask

endclass 

Driver And Sequencer Connectivity:

Deriver and sequencer are connected using TLM. uvm_driver has seq_item_port which
is used to get the transaction from uvm sequencer. This port is connected to
uvm_sequencer seq_item_export  Using
"<driver>.seq_item_port.connect(<sequencer>.seq_item_export);" driver and
sequencer can be connected. Simillarly  "res_port" of driver which is used to send
response from driver to sequencer is connected to "res_export" of the sequencer using
""<driver>.res_port.connect(<sequencer>.res_export);".

http://testbench.in/UT_07_UVM_SEQUENCE_1.html[9/26/2012 2:22:50 PM]


WWW.TESTBENCH.IN - UVM Tutorial

Testcase:

This testcase is used only for the demo purpose of this tutorial session. Actually, the
sequencer and the driver and instantiated and their ports are connected in a agent
component and used.  Lets implement a testcase

1) Take instances of sequencer and driver and construct both components.

    sequencer = new("sequencer", null); 
    sequencer.build();
    driver = new("driver", null); 
    driver.build();

2)
Connect the seq_item_export to the drivers seq_item_port.

    driver.seq_item_port.connect(sequencer.seq_item_export);

3) Using set_confg_string() method, set the default sequence of the sequencer to


"operation_addition". Operation_addition is the sequence which we defined previous.

    set_config_string("sequencer", "default_sequence", "operation_addition");

4) Using the start_default_sequence() method of the sequencer, start the default


sequence of the sequencer. In the previous step we configured the addition operation
as default sequene. When you run the simulation, you will see the PUSH_A,PUSH_B
ADD and POP_C series of transaction.

    sequencer.start_default_sequence();

Testcase Code:

module test;

  instruction_sequencer sequencer;
  instruction_driver driver;

  initial begin
    set_config_string("sequencer", "default_sequence", "operation_addition");
    sequencer = new("sequencer", null); 
    sequencer.build();
    driver = new("driver", null); 
    driver.build();

http://testbench.in/UT_07_UVM_SEQUENCE_1.html[9/26/2012 2:22:50 PM]


WWW.TESTBENCH.IN - UVM Tutorial

    driver.seq_item_port.connect(sequencer.seq_item_export);
    sequencer.print();
    fork 
      begin
        run_test();
        sequencer.start_default_sequence();
      end
      #2000 global_stop_request();
    join
  end

endmodule

Download the example:

uvm_basic_sequence.tar
Browse the code in uvm_basic_sequence.tar

Command to simulate

VCS Users : make vcs


Questa Users: make questa

Log file Output

UVM_INFO @ 0 [RNTST] Running test ...


0: Driving Instruction  PUSH_A
10: Driving Instruction  PUSH_B
20: Driving Instruction  ADD
30: Driving Instruction  POP_C

From the above log , we can see that transactions are generates as we defined in uvm
sequence.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/UT_07_UVM_SEQUENCE_1.html[9/26/2012 2:22:50 PM]


WWW.TESTBENCH.IN - UVM Tutorial

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS UVM SEQUENCE 2 Index


Introduction
SystemVerilog Uvm Testbench
Verification Pre Defined Sequences: Uvm Reporting
Uvm Transaction
Constructs Every sequencer in uvm has 3 pre defined sequences. They are Uvm Configuration
Interface   Uvm Factory
1)uvm_random_sequence Uvm Sequence 1
OOPS Uvm Sequence 2
2)uvm_exhaustive_sequence. Uvm Sequence 3
Randomization 3)uvm_simple_sequence Uvm Sequence 4
Functional Coverage All the user defined sequences which are registered by user and the above three Uvm Sequence 5
predefined sequences are stored in sequencer queue.   Uvm Sequence 6
Assertion
Uvm Tlm 1
DPI Uvm Tlm 2
UVM Tutorial Uvm Callback
VMM Tutorial
Report a Bug or Comment
OVM Tutorial on This section - Your
input is what keeps
Easy Labs : SV
Testbench.in improving
Easy Labs : UVM with time!
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

Verilog
Verification uvm_random_sequence :
Verilog Switch TB
This sequence randomly selects and executes a sequence from the sequencer
Basic Constructs sequence library, excluding uvm_random_sequence itself, and
uvm_exhaustive_sequence. From the above image, from sequence id 2 to till the last
sequence, all the sequences are executed randomly.  If the "count" variable of the
OpenVera sequencer is set to 0, then non of the sequence is executed. If the "count" variable of
Constructs the sequencer is set to -1, then some random number of sequences from 0 to
"max_random_count" are executed. By default "max_random_count" is set to
Switch TB 10.  "Count" and "max_random_count" can be changed using set_config_int().
RVM Switch TB
The sequencer when automatically started executes the sequence which is point by
RVM Ethernet sample default_sequence. By default  default_sequence variable points to
uvm_random_sequence.

Specman E uvm_exhaustive_sequence:
Interview Questions This sequence randomly selects and executes each sequence from the sequencers
sequence library once in a randc style, excluding itself and uvm_random_sequence.

uvm_simple_sequence:

This sequence simply executes a single sequence item.

In the previous example from UVM_SEQUENCE_1 section.

The print() method of the sequencer in that example printed the following

http://testbench.in/UT_08_UVM_SEQUENCE_2.html[9/26/2012 2:22:59 PM]


WWW.TESTBENCH.IN - UVM Tutorial

-------------------------------------------------------------------
---
Name                     Type                Size                Value
-------------------------------------------------------------------
---
sequencer                instruction_sequen+ -             sequencer@2
  rsp_export             uvm_analysis_export -            rsp_export@4
  seq_item_export        uvm_seq_item_pull_+ -      seq_item_export@28
  default_sequence       string              18     operation_addition
  count                  integral            32                     -1
  max_random_count       integral            32                   'd10
  sequences              array               4                       -
    [0]                  string              19    uvm_random_sequence
    [1]                  string              23   uvm_exhaustive_sequ+
    [2]                  string              19    uvm_simple_sequence
    [3]                  string              18     operation_addition
  max_random_depth       integral            32                    'd4
  num_last_reqs          integral            32                    'd1
  num_last_rsps          integral            32                    'd1
-------------------------------------------------------------------
---

Some observations from the above log:

 The count  is set to -1.  The default sequencer is set to operations_addition. There


are 3 predefined sequences and 1 user defined sequence.  

Lets look at a example: In the attached example, in file sequence.sv file, there are 4
seuqneces, they are operation_addition, operation_subtraction,
operation_multiplication.

In the testcase.sv file, the "default_seuence" is set to "uvm_exhaustive_sequence"


using the set_config_string.

    set_config_string("sequencer", "default_sequence", "uvm_exhaustive_sequence");

Download the example

uvm_sequence_1.tar
Browse the code in uvm_sequence_1.tar

Command to run the summation

VCS Users : make vcs


Questa Users: make questa

Log File

0: Driving Instruction  PUSH_B

10: Driving Instruction  PUSH_A


20: Driving Instruction  PUSH_B
30: Driving Instruction  SUB
40: Driving Instruction  POP_C

50: Driving Instruction  PUSH_A


60: Driving Instruction  PUSH_B
70: Driving Instruction  MUL
80: Driving Instruction  POP_C

90: Driving Instruction  PUSH_A


100: Driving Instruction  PUSH_B
110: Driving Instruction  ADD
120: Driving Instruction  POP_C

http://testbench.in/UT_08_UVM_SEQUENCE_2.html[9/26/2012 2:22:59 PM]


WWW.TESTBENCH.IN - UVM Tutorial

From the above log , we can see that all the 3 user defined sequences and predefined
uvm_simple_sequence are executed.

Sequence Action Macro:

In the previous sections, we have seen the implementation of body() method of


sequence. The body() method implementation requires some steps.  We have seen
these steps as  Creation of item, wait for grant, randomize the item, send the item.  

All these steps have be automated using "sequence action macros". There are some
more additional steps added in these macros. Following are the steps defined with the
"sequence action macro".

Pre_do(), mid_do() and post_do() are callback methods which are in uvm sequence.  If
user is interested , he can use these methods. For example, in  mid_do() method, user
can print the transaction or  the randomized transaction can be fined tuned.  These
methods should not be clled by user directly.  

Syntax:

virtual task pre_do(bit is_item)
virtual function void mid_do(uvm_sequence_item this_item)
virtual function void post_do(uvm_sequence_item this_item)

Pre_do() is a task , if  the method consumes simulation cycles, the behavior may be
unexpected.

Example Of Pre_do,Mid_do And Post_do

Lets look at a example:   We will define a sequence using `uvm_do macro. This macro
has all the above defined phases.
  
1)Define the body method using the `uvm_do() macro. Before and after this macro,
just call messages.

  virtual task body();
     uvm_report_info(get_full_name(),
            "Seuqnce Action Macro Phase  : Before uvm_do macro ",UVM_LOW);
     `uvm_do(req);
     uvm_report_info(get_full_name(),
            "Seuqnce Action Macro Phase  : After uvm_do macro ",UVM_LOW);
  endtask

2)Define pre_do() method. Lets just print a message from this method.

  virtual task pre_do(bit is_item);
       uvm_report_info(get_full_name(),
            "Seuqnce Action Macro Phase  : PRE_DO   ",UVM_LOW);

http://testbench.in/UT_08_UVM_SEQUENCE_2.html[9/26/2012 2:22:59 PM]


WWW.TESTBENCH.IN - UVM Tutorial

  endtask

3)Define mid_do() method. Lets just print a message from this method.

  virtual function void mid_do(uvm_sequence_item this_item);
       uvm_report_info(get_full_name(),
            "Seuqnce Action Macro Phase  : MID_DO   ",UVM_LOW);
  endfunction

4)Define post_do() method. Lets just print a message from this method.

  virtual function void post_do(uvm_sequence_item this_item);
       uvm_report_info(get_full_name(),
            "Seuqnce Action Macro Phase  : POST_DO   ",UVM_LOW);
  endfunction 

Complet sequence code:

class demo_uvm_do extends uvm_sequence #(instruction);

  instruction req;
 
  function new(string name="demo_uvm_do");
    super.new(name);
  endfunction
  
  `uvm_sequence_utils(demo_uvm_do, instruction_sequencer)    

  virtual task pre_do(bit is_item);
       uvm_report_info(get_full_name(),
           "Seuqnce Action Macro Phase  : PRE_DO   ",UVM_LOW);
  endtask

  virtual function void mid_do(uvm_sequence_item this_item);
       uvm_report_info(get_full_name(),
           "Seuqnce Action Macro Phase  : MID_DO   ",UVM_LOW);
  endfunction

  virtual function void post_do(uvm_sequence_item this_item);
       uvm_report_info(get_full_name(),
           "Seuqnce Action Macro Phase  : POST_DO   ",UVM_LOW);
  endfunction 

  virtual task body();
     uvm_report_info(get_full_name(),
           "Seuqnce Action Macro Phase  : Before uvm_do macro ",UVM_LOW);
     `uvm_do(req);
     uvm_report_info(get_full_name(),
           "Seuqnce Action Macro Phase  : After uvm_do macro ",UVM_LOW);
  endtask
  
endclass 

Download the example

uvm_sequence_2.tar
Browse the code in uvm_sequence_2.tar

Command to run the simulation

VCS Users : make vcs


Questa Users: make questa

Log file report:

UVM_INFO@0:reporter[sequencer.demo_uvm_do]
    Seuqnce Action Macro Phase  : Before uvm_do macro
UVM_INFO@0:reporter[sequencer.demo_uvm_do]
    Seuqnce Action Macro Phase  : PRE_DO  
UVM_INFO@0:reporter[sequencer.demo_uvm_do]
    Seuqnce Action Macro Phase  : MID_DO  

0: Driving Instruction  MUL

http://testbench.in/UT_08_UVM_SEQUENCE_2.html[9/26/2012 2:22:59 PM]


WWW.TESTBENCH.IN - UVM Tutorial

UVM_INFO@10:reporter[sequencer.demo_uvm_do]
    Seuqnce Action Macro Phase  : POST_DO  
UVM_INFO@10:reporter[sequencer.demo_uvm_do]
    Seuqnce Action Macro Phase  : After uvm_do macro  

The above log file shows the  messages from pre_do,mid_do and post_do methods.

List Of Sequence Action Macros:

These macros are used to start sequences and sequence items that were either
registered with a <`uvm-sequence_utils> macro or whose associated sequencer was
already set using the <set_sequencer> method.

`uvm_create(item/sequence)

This action creates the item or sequence using the factory. Only the create phase will
be executed.

`uvm_do(item/sequence)

This macro takes as an argument a uvm_sequence_item variable or sequence . All the


above defined 7 phases will be executed.

`uvm_do_with(item/sequence, Constraint block)

This is the same as `uvm_do except that the constraint block in the 2nd argument is
applied to the item or sequence in a randomize with statement before execution.

`uvm_send(item/sequence)

Create phase and randomize phases are skipped, rest all the phases will be executed.
Using `uvm_create, create phase can be executed.  Essentially, an `uvm_do without
the create or randomization.

`uvm_rand_send(item/sequence)

Only create phase is skipped. rest of all the phases will be executed. User should use
`uvm_create to create the sequence or item.

`uvm_rand_send_with(item/sequence , Constraint block)

 Only create phase is skipped. rest of all the phases will be executed. User should use
`uvm_create to create the sequence or item.  Constraint block will be applied which
randomization.

`uvm_do_pri(item/sequence, priority )

This is the same as `uvm_do except that the sequence item or sequence is executed
with the priority specified in the argument.

`uvm_do_pri_with(item/sequence , constraint block , priority)

This is the same as `uvm_do_pri except that the given constraint block is applied to
the item or sequence in a randomize with statement  before execution.

`uvm_send_pri(item/sequence,priority)

This is the same as `uvm_send except that the sequence item or sequence is executed
with the priority specified in the argument.

`uvm_rand_send_pri(item/sequence,priority)

This is the same as `uvm_rand_send except that the sequence item or sequence is
executed with the priority specified in the argument.

`uvm_rand_send_pri_with(item/sequence,priority,constraint block)

This is the same as `uvm_rand_send_pri except that the given constraint block is
applied to the item or sequence in a randomize with statement before execution.  

Following  macros are used on sequence or sequence items on a different sequencer.

http://testbench.in/UT_08_UVM_SEQUENCE_2.html[9/26/2012 2:22:59 PM]


WWW.TESTBENCH.IN - UVM Tutorial

`uvm_create_on(item/sequence,sequencer)

This is the same as `uvm_create except that it also sets the parent sequence to the
sequence in which the macro is invoked, and it sets the sequencer to the specified
sequencer argument.

`uvm_do_on(item/sequence,sequencer)

This is the same as `uvm_do except that it also sets the parent sequence to the
sequence in which the macro is invoked, and it sets the sequencer to the specified
sequencer  argument.

`uvm_do_on_pri(item/sequence,sequencer, priority)

This is the same as `uvm_do_pri except that it also sets the parent sequence to the
sequence in which the macro is invoked, and it sets the sequencer to the specified
sequencer  argument.

`uvm_do_on_with(item/sequence,sequencer, constraint block)

This is the same as `uvm_do_with except that it also sets the parent sequence to the
sequence in which the macro is invoked, and it sets the  sequencer to the specified
sequencer  argument.  The user must supply brackets around the constraints.

`uvm_do_on_pri_with(item/sequence,sequencer,priority,constraint block)

This is the same as `uvm_do_pri_with except that it also sets the parent sequence to
the sequence in which the macro is invoked, and it sets the sequencer to the specified
sequencer argument.

Examples With Sequence Action Macros:

  virtual task body();
      uvm_report_info(get_full_name(),
          "Executing Sequence Action Macro uvm_do",UVM_LOW);
      `uvm_do(req)
  endtask

  virtual task body();
      uvm_report_info(get_full_name(),
          "Executing Sequence Action Macro uvm_do_with ",UVM_LOW);
      `uvm_do_with(req,{ inst == ADD; })
  endtask

  virtual task body();
      uvm_report_info(get_full_name(),
           "Executing Sequence Action Macro uvm_create and uvm_send",UVM_LOW);
      `uvm_create(req)
      req.inst = instruction::PUSH_B;
      `uvm_send(req)
  endtask
  
  virtual task body();
      uvm_report_info(get_full_name(),
           "Executing Sequence Action Macro uvm_create and
uvm_rand_send",UVM_LOW);
      `uvm_create(req)
      `uvm_rand_send(req)
  endtask
  

Download the example

uvm_sequence_3.tar
Browse the code in uvm_sequence_3.tar

Command to sun the simulation

VCS Users : make vcs

http://testbench.in/UT_08_UVM_SEQUENCE_2.html[9/26/2012 2:22:59 PM]


WWW.TESTBENCH.IN - UVM Tutorial

Questa Users: make questa

Log file report

0: Driving Instruction  PUSH_B
UVM_INFO@10:reporter[***]Executing Sequence Action Macro uvm_do_with
10: Driving Instruction  ADD
UVM_INFO@20:reporter[***]Executing Sequence Action Macro uvm_create and
uvm_send
20: Driving Instruction  PUSH_B
UVM_INFO@30:reporter[***]Executing Sequence Action Macro uvm_do
30: Driving Instruction  DIV
UVM_INFO@40:reporter[***]Executing Sequence Action Macro uvm_create and
uvm_rand_send
40: Driving Instruction  MUL

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/UT_08_UVM_SEQUENCE_2.html[9/26/2012 2:22:59 PM]


WWW.TESTBENCH.IN - UVM Tutorial

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS UVM SEQUENCE 3 Index


Introduction
SystemVerilog Body Callbacks: Uvm Testbench
Verification Uvm Reporting
uvm sequences has two callback methods pre_body() and post_body(), which are Uvm Transaction
Constructs executed before and after the sequence body() method execution. These callbacks Uvm Configuration
Interface are called only when start_sequence() of sequencer or start() method of the sequence Uvm Factory
is called. User should not call these methods. Uvm Sequence 1
OOPS Uvm Sequence 2
Randomization Uvm Sequence 3
virtual task pre_body() Uvm Sequence 4
Functional Coverage Uvm Sequence 5
virtual task post_body()
Assertion Uvm Sequence 6
Example Uvm Tlm 1
DPI Uvm Tlm 2
UVM Tutorial In this example, I just printed messages from pre_body() and post_body() methods. Uvm Callback
VMM Tutorial These methods can be used for initialization, synchronization with some events or
cleanup. Report a Bug or Comment
OVM Tutorial on This section - Your
input is what keeps
Easy Labs : SV
class demo_pre_body_post_body extends uvm_sequence #(instruction); Testbench.in improving
Easy Labs : UVM with time!
Easy Labs : OVM   instruction req;
 
Easy Labs : VMM   function new(string name="demo_pre_body_post_body");
AVM Switch TB     super.new(name);
  endfunction
VMM Ethernet sample   
  `uvm_sequence_utils(demo_pre_body_post_body, instruction_sequencer)    

Verilog   virtual task pre_body();
Verification        uvm_report_info(get_full_name()," pre_body() callback ",UVM_LOW);
  endtask
Verilog Switch TB
Basic Constructs   virtual task post_body();
       uvm_report_info(get_full_name()," post_body() callback ",UVM_LOW);
  endtask
OpenVera   virtual task body();
Constructs      uvm_report_info(get_full_name(),
Switch TB           "body() method: Before uvm_do macro ",UVM_LOW);
     `uvm_do(req);
RVM Switch TB      uvm_report_info(get_full_name(),
RVM Ethernet sample           "body() method: After uvm_do macro ",UVM_LOW);
  endtask
  
endclass 
Specman E
Interview Questions
Download the example

uvm_sequence_4.tar
Browse the code in uvm_sequence_4.tar

Command to sun the simulation

VCS Users : make vcs


Questa Users: make questa

http://testbench.in/UT_09_UVM_SEQUENCE_3.html[9/26/2012 2:23:07 PM]


WWW.TESTBENCH.IN - UVM Tutorial

Log file report

UVM_INFO @ 0 [RNTST] Running test ...


UVM_INFO @ 0: reporter [***]  pre_body() callback
UVM_INFO @ 0: reporter [***] body() method: Before uvm_do macro
0: Driving Instruction  SUB
UVM_INFO @ 10: reporter [***] body() method: After uvm_do macro
UVM_INFO @ 10: reporter [***]  post_body() callback

Hierarchical Sequences

One main advantage of sequences is smaller sequences can be used to create


sequences to generate stimulus required for todays complex protocol.  

To create a sequence using another sequence, following steps has to be done

1)Extend the uvm_sequence class and define a new class.


2)Declare instances of child sequences which will be used to create new sequence.
3)Start the child sequence using <instance>.start() method in body() method.

Sequential Sequences

To executes child sequences sequentially, child sequence start() method should be


called sequentially in body method.
In the below example you can see all the 3 steps mentioned above.
In this example, I have defined 2 child sequences. These child sequences can be used
as normal sequences.

Sequence 1 code:

This sequence generates 4 PUSH_A instructions.

  virtual task body();
      repeat(4) begin
         `uvm_do_with(req, { inst == PUSH_A; });
      end
  endtask

Sequence 2 code:

This sequence generates 4 PUSH_B instructions.

  virtual task body();
      repeat(4) begin
         `uvm_do_with(req, { inst == PUSH_B; });
      end
  endtask

Sequential Sequence code:

This sequence first calls sequence 1 and then calls sequence 2.

class sequential_sequence extends uvm_sequence #(instruction);

  seq_a s_a;
  seq_b s_b;
 
  function new(string name="sequential_sequence");
    super.new(name);
  endfunction
  
  `uvm_sequence_utils(sequential_sequence, instruction_sequencer)    

  virtual task body();

http://testbench.in/UT_09_UVM_SEQUENCE_3.html[9/26/2012 2:23:07 PM]


WWW.TESTBENCH.IN - UVM Tutorial

         `uvm_do(s_a);
         `uvm_do(s_b);
  endtask
  
endclass  

From the testcase, "sequential_sequence" is selected as "default_sequence". 

Download the example

uvm_sequence_5.tar
Browse the code in uvm_sequence_5.tar

Command to sun the simulation

VCS Users : make vcs


Questa Users: make questa

Log file report

0: Driving Instruction  PUSH_A
10: Driving Instruction  PUSH_A
20: Driving Instruction  PUSH_A
30: Driving Instruction  PUSH_A
40: Driving Instruction  PUSH_B
50: Driving Instruction  PUSH_B
60: Driving Instruction  PUSH_B
70: Driving Instruction  PUSH_B

If you observe the above log, you can see sequence seq_a is executed first and then
sequene seq_b is executed.

Parallelsequences

To executes child sequences Parallel, child sequence start() method should be called
parallel using fork/join  in body method.

Parallel Sequence code:

class parallel_sequence extends uvm_sequence #(instruction);

  seq_a s_a;
  seq_b s_b;
 
  function new(string name="parallel_sequence");
    super.new(name);
  endfunction
  
  `uvm_sequence_utils(parallel_sequence, instruction_sequencer)    

  virtual task body();
         fork
              `uvm_do(s_a)
              `uvm_do(s_b)
         join
  endtask
  
endclass  

Download the example

uvm_sequence_6.tar
Browse the code in uvm_sequence_6.tar

Command to sun the simulation

VCS Users : make vcs


Questa Users: make questa

Log file report

http://testbench.in/UT_09_UVM_SEQUENCE_3.html[9/26/2012 2:23:07 PM]


WWW.TESTBENCH.IN - UVM Tutorial

UVM_INFO @ 0 [RNTST] Running test ...


0: Driving Instruction  PUSH_A
10: Driving Instruction  PUSH_B
20: Driving Instruction  PUSH_A
30: Driving Instruction  PUSH_B
40: Driving Instruction  PUSH_A
50: Driving Instruction  PUSH_B
60: Driving Instruction  PUSH_A
70: Driving Instruction  PUSH_B

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/UT_09_UVM_SEQUENCE_3.html[9/26/2012 2:23:07 PM]


WWW.TESTBENCH.IN - UVM Tutorial

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS UVM SEQUENCE 4 Index


Introduction
SystemVerilog Sequencer Arbitration: Uvm Testbench
Verification Uvm Reporting
When sequences are executed parallel, sequencer will arbitrate among the parallel Uvm Transaction
Constructs sequence. When all the parallel sequences are waiting for a grant from sequencer Uvm Configuration
Interface using wait_for_grant() method, then the sequencer, using the arbitration mechanism, Uvm Factory
sequencer grants to one of the sequencer. Uvm Sequence 1
OOPS Uvm Sequence 2
Randomization There are 6 different arbitration algorithms, they are Uvm Sequence 3
Uvm Sequence 4
Functional Coverage Uvm Sequence 5
Assertion Uvm Sequence 6
Uvm Tlm 1
DPI Uvm Tlm 2
UVM Tutorial Uvm Callback
VMM Tutorial
Report a Bug or Comment
OVM Tutorial on This section - Your
input is what keeps
Easy Labs : SV
Testbench.in improving
Easy Labs : UVM with time!
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

Verilog
Verification
To set the arbitaration, use the set_arbitration() method of the sequencer. By default
Verilog Switch TB , the arbitration algorithms is set to SEQ_ARB_FIFO.
Basic Constructs
   function void set_arbitration(SEQ_ARB_TYPE val)

OpenVera Lets look at a example.


Constructs In this example, I have 3 child sequences seq_mul seq_add and seq_sub each of them
generates 3 transactions.
Switch TB
RVM Switch TB Sequence code 1:
virtual task body();
RVM Ethernet sample
      repeat(3) begin
         `uvm_do_with(req, { inst == MUL; });
      end
Specman E   endtask
Interview Questions
Sequence code 2:
  virtual task body();
      repeat(3) begin
         `uvm_do_with(req, { inst == ADD; });
      end
  endtask

Sequence code 3:
  virtual task body();
      repeat(3) begin
         `uvm_do_with(req, { inst == SUB; });

http://testbench.in/UT_10_UVM_SEQUENCE_4.html[9/26/2012 2:23:16 PM]


WWW.TESTBENCH.IN - UVM Tutorial

      end
  endtask

Parallel sequence code:

In the body method, before starting child sequences, set the arbitration using
set_arbitration(). In this code, im setting it to SEQ_ARB_RANDOM.

class parallel_sequence extends uvm_sequence #(instruction);

  seq_add add;
  seq_sub sub;
  seq_mul mul;
 
  function new(string name="parallel_sequence");
    super.new(name);
  endfunction
  
  `uvm_sequence_utils(parallel_sequence, instruction_sequencer)    

  virtual task body();
      m_sequencer.set_arbitration(SEQ_ARB_RANDOM);
      fork
         `uvm_do(add)
         `uvm_do(sub)
         `uvm_do(mul)
      join
  endtask
  
endclass

Download the example

uvm_sequence_7.tar
Browse the code in uvm_sequence_7.tar

Command to sun the simulation

VCS Users : make vcs


Questa Users: make questa

Log file report for when SEQ_ARB_RANDOM is set.

0: Driving Instruction  MUL
10: Driving Instruction  SUB
20: Driving Instruction  MUL
30: Driving Instruction  SUB
40: Driving Instruction  MUL
50: Driving Instruction  ADD
60: Driving Instruction  ADD
70: Driving Instruction  SUB
80: Driving Instruction  ADD

Log file report for when SEQ_ARB_FIFO is set.

0: Driving Instruction  ADD
10: Driving Instruction  SUB
20: Driving Instruction  MUL
30: Driving Instruction  ADD
40: Driving Instruction  SUB
50: Driving Instruction  MUL
60: Driving Instruction  ADD
70: Driving Instruction  SUB
80: Driving Instruction  MUL

http://testbench.in/UT_10_UVM_SEQUENCE_4.html[9/26/2012 2:23:16 PM]


WWW.TESTBENCH.IN - UVM Tutorial

If you observe the first log report, all the transaction of the sequences are generated
in random order. In the second log file, the transactions are given equal priority and
are in fifo order.

Setting The Sequence Priority:

There are two ways to set the priority of a sequence. One is using the start method of
the sequence and other using the set_priority() method of the sequence. By default,
the priority of a sequence is 100.   Higher numbers indicate higher priority.

virtual task start (uvm_sequencer_base sequencer, 
               uvm_sequence_base parent_sequence = null,
               integer this_priority = 100,
               bit call_pre_post = 1)

function void set_priority (int value)

Lets look a example with SEQ_ARB_WEIGHTED.

For sequence seq_mul set the weight to 200.


For sequence seq_add set the weight to 300.
For sequence seq_sub set the weight to 400.

In the below example, start() method is used to override the default priority value.

Code :

class parallel_sequence extends uvm_sequence #(instruction);

  seq_add add;
  seq_sub sub;
  seq_mul mul;
 
  function new(string name="parallel_sequence");
    super.new(name);
  endfunction
  
  `uvm_sequence_utils(parallel_sequence, instruction_sequencer)    

  virtual task body();
      m_sequencer.set_arbitration(SEQ_ARB_WEIGHTED);
      add = new("add");
      sub = new("sub");
      mul = new("mul");
      fork
         sub.start(m_sequencer,this,400);
         add.start(m_sequencer,this,300);
         mul.start(m_sequencer,this,200);
      join
  endtask
  
endclass 

Download the example

uvm_sequence_8.tar
Browse the code in uvm_sequence_8.tar

Command to sun the simulation

VCS Users : make vcs


Questa Users: make questa

Log file report

0: Driving Instruction  MUL
10: Driving Instruction  ADD

http://testbench.in/UT_10_UVM_SEQUENCE_4.html[9/26/2012 2:23:16 PM]


WWW.TESTBENCH.IN - UVM Tutorial

20: Driving Instruction  SUB


30: Driving Instruction  SUB
40: Driving Instruction  ADD
50: Driving Instruction  ADD
60: Driving Instruction  ADD
70: Driving Instruction  MUL
80: Driving Instruction  SUB

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/UT_10_UVM_SEQUENCE_4.html[9/26/2012 2:23:16 PM]


WWW.TESTBENCH.IN - UVM Tutorial

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS UVM SEQUENCE 5 Index


Introduction
SystemVerilog Sequencer Registration Macros Uvm Testbench
Verification Uvm Reporting
Uvm Transaction
Constructs Sequence Registration Macros does the following Uvm Configuration
Interface 1) Implements get_type_name method. Uvm Factory
2) Implements create() method. Uvm Sequence 1
OOPS Uvm Sequence 2
3) Registers with the factory.
Randomization 4) Implements the static get_type() method. Uvm Sequence 3
5) Implements the virtual get_object_type() method. Uvm Sequence 4
Functional Coverage Uvm Sequence 5
6) Registers the sequence type with the sequencer type.
Assertion 7) Defines p_sequencer variable. p_sequencer is a handle to its sequencer. Uvm Sequence 6
8) Implements m_set_p_sequencer() method. Uvm Tlm 1
DPI Uvm Tlm 2
UVM Tutorial If there are no local variables, then use following macro Uvm Callback
VMM Tutorial
`uvm_sequence_utils(TYPE_NAME,SQR_TYPE_NAME) Report a Bug or Comment
OVM Tutorial on This section - Your
input is what keeps
Easy Labs : SV
If there are local variables in sequence, then use macro Testbench.in improving
Easy Labs : UVM with time!
Easy Labs : OVM `uvm_sequence_utils_begin(TYPE_NAME,SQR_TYPE_NAME)
  `uvm_field_* macro invocations here
Easy Labs : VMM `uvm_sequence_utils_end
AVM Switch TB
VMM Ethernet sample Macros `uvm_field_* are used for define utility methods.
These `uvm_field_* macros  are discussed in
UVM_TRANSACTION  
Verilog
Verification
Example to demonstrate the usage of the above macros:
Verilog Switch TB
Basic Constructs
class seq_mul extends uvm_sequence #(instruction);

  rand integer num_inst ;
OpenVera   instruction req;
Constructs
Switch TB   constraint num_c { num_inst inside { 3,5,7 }; };
RVM Switch TB     `uvm_sequence_utils_begin(seq_mul,instruction_sequencer)    
RVM Ethernet sample     `uvm_field_int(num_inst, UVM_ALL_ON)
    `uvm_sequence_utils_end
  
  function new(string name="seq_mul");
Specman E     super.new(name);
Interview Questions   endfunction
  

  virtual task body();
      uvm_report_info(get_full_name(),
        $psprintf("Num of transactions %d",num_inst),UVM_LOW);
      repeat(num_inst) begin
         `uvm_do_with(req, { inst == MUL; });
      end
  endtask
  

http://testbench.in/UT_11_UVM_SEQUENCE_5.html[9/26/2012 2:23:26 PM]


WWW.TESTBENCH.IN - UVM Tutorial

endclass 

Download the example

uvm_sequence_9.tar
Browse the code in uvm_sequence_9.tar

Command to sun the simulation

VCS Users : make vcs


Questa Users: make questa

Log

UVM_INFO @ 0: reporter [RNTST] Running test ...


UVM_INFO @ 0: reporter [sequencer.seq_mul] Num of transactions           5
0: Driving Instruction  MUL
10: Driving Instruction  MUL
20: Driving Instruction  MUL
30: Driving Instruction  MUL
40: Driving Instruction  MUL

Setting Sequence Members:

set_config_*  can be used only for the components not for the sequences.
By using configuration you can change the variables inside components only not in
sequences.

But there is a workaround to this problem.

Sequence has handle name called p_sequencer which is pointing the Sequencer on
which it is running.
Sequencer is a component , so get_config_* methods are implemented for it.
So from the sequence, using the sequencer get_config_* methods, sequence members
can be updated if the variable is configured.

When using set_config_* , path to the variable should be sequencer name, as we are
using the sequencer get_config_* method.

Following method demonstrates how this can be done:

Sequence:

1) num_inst is a integer variables which can be updated.


2) In the body method, call the get_config_int() method to get the integer value if
num_inst is configured from testcase.

class seq_mul extends uvm_sequence #(instruction);

  integer num_inst = 4;
  instruction req;

    `uvm_sequence_utils_begin(seq_mul,instruction_sequencer)    
    `uvm_field_int(num_inst, UVM_ALL_ON)
    `uvm_sequence_utils_end
  
  function new(string name="seq_mul");
    super.new(name);
  endfunction
  

  virtual task body();

       void'(p_sequencer.get_config_int("num_inst",num_inst));

       uvm_report_info(get_full_name(),
           $psprintf("Num of transactions %d",num_inst),UVM_LOW);

http://testbench.in/UT_11_UVM_SEQUENCE_5.html[9/26/2012 2:23:26 PM]


WWW.TESTBENCH.IN - UVM Tutorial

      repeat(num_inst) begin
         `uvm_do_with(req, { inst == MUL; });
      end
  endtask
  
endclass 

Testcase:

From the testcase, using the     set_config_int() method, configure the num_inst to 3.
The instance path argument should be the sequencer path name.

module test;

  instruction_sequencer sequencer;
  instruction_driver driver;

  initial begin
    set_config_string("sequencer", "default_sequence", "seq_mul");
    set_config_int("sequencer", "num_inst",3);
    sequencer = new("sequencer", null); 
    sequencer.build();
    driver = new("driver", null); 
    driver.build();

    driver.seq_item_port.connect(sequencer.seq_item_export);
    sequencer.print();
    fork 
      begin
        run_test();
        sequencer.start_default_sequence();
      end
      #3000 global_stop_request();
    join
  end

endmodule
 

Download the example

uvm_sequence_10.tar
Browse the code in uvm_sequence_10.tar

Command to sun the simulation

VCS Users : make vcs


Questa Users: make questa

Log

UVM_INFO @ 0: reporter [RNTST] Running test ...


UVM_INFO @ 0: reporter [sequencer.seq_mul] Num of transactions           3
0: Driving Instruction  MUL
10: Driving Instruction  MUL
20: Driving Instruction  MUL

From the above log we can see that seq_mul.num_inst value is 3.

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/UT_11_UVM_SEQUENCE_5.html[9/26/2012 2:23:26 PM]


WWW.TESTBENCH.IN - UVM Tutorial

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/UT_11_UVM_SEQUENCE_5.html[9/26/2012 2:23:26 PM]


WWW.TESTBENCH.IN - UVM Tutorial

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS UVM SEQUENCE 6 Index


Introduction
SystemVerilog Uvm Testbench
Verification Exclusive Access Uvm Reporting
Uvm Transaction
Constructs A sequence may need exclusive access to the driver which sequencer is arbitrating Uvm Configuration
Interface among multiple sequence. Some operations require that a series of transaction needs Uvm Factory
to be driven without any other transaction in between them. Then a exclusive access Uvm Sequence 1
OOPS Uvm Sequence 2
to the driver will allow to a sequence to complete its operation with out any other
Randomization sequence operations in between them. Uvm Sequence 3
Uvm Sequence 4
Functional Coverage Uvm Sequence 5
There are 2 mechanisms to get exclusive access:
Assertion Lock-unlcok Uvm Sequence 6
Uvm Tlm 1
DPI Grab-ungrab Uvm Tlm 2
UVM Tutorial Uvm Callback
VMM Tutorial Lock-Unlock
Report a Bug or Comment
OVM Tutorial on This section - Your
task lock(uvm_sequencer_base sequencer = Null)
input is what keeps
Easy Labs : SV function void unlock(uvm_sequencer_base sequencer = Null)
Testbench.in improving
Easy Labs : UVM with time!
Easy Labs : OVM Using lock() method , a sequence can requests for exclusive access.  A lock request
Easy Labs : VMM will be arbitrated the same as any other request.  A lock is granted after all earlier
requests are completed and no other locks or grabs are blocking this sequence. A
AVM Switch TB lock() is blocking task and when access is granted, it will unblock.
VMM Ethernet sample     
Using unlock(), removes any locks or grabs obtained by this sequence on the specified
sequencer.  
Verilog If sequencer is null, the lock/unlock will be applied on the current default sequencer.
Verification
Lets see an example,
Verilog Switch TB
In this example there are 3 sequences with each sequence generating 4 transactions.
Basic Constructs All these 3 sequences will be called in parallel in another sequence.

Sequence 1 code:
OpenVera
  virtual task body();
Constructs       repeat(4) begin
Switch TB          `uvm_do_with(req, { inst == PUSH_A; });
      end
RVM Switch TB
  endtask
RVM Ethernet sample
Sequence 2 code:
 virtual task body();
      repeat(4) begin
Specman E
         `uvm_do_with(req, { inst == POP_C; });
Interview Questions       end
  endtask
  

Sequence 3 code:

In this sequence , call the lock() method to get the exclusive access to driver.
After completing all the transaction driving, then call the unclock() method.

 virtual task body();

http://testbench.in/UT_12_UVM_SEQUENCE_6.html[9/26/2012 2:23:34 PM]


WWW.TESTBENCH.IN - UVM Tutorial

      lock();
      repeat(4) begin
         `uvm_do_with(req, { inst == PUSH_B; });
      end
      unlock();
  endtask

Parallel sequence code:

  virtual task body();
      fork
         `uvm_do(s_a)
         `uvm_do(s_b)
         `uvm_do(s_c)
      join
  endtask

Download the example

uvm_sequence_11.tar
Browse the code in uvm_sequence_11.tar

Command to sun the simulation

VCS Users : make vcs


Questa Users: make questa

Log file:

0: Driving Instruction  PUSH_A
10: Driving Instruction  POP_C
20: Driving Instruction  PUSH_A
30: Driving Instruction  PUSH_B
40: Driving Instruction  PUSH_B
50: Driving Instruction  PUSH_B
60: Driving Instruction  PUSH_B
70: Driving Instruction  POP_C
80: Driving Instruction  PUSH_A
90: Driving Instruction  POP_C
100: Driving Instruction  PUSH_A
110: Driving Instruction  POP_C

From the above log file, we can observe that , when seq_b sequence got the access,
then transactions from seq_a and seq_c are not generated.

Lock() will be arbitrated before giving the access. To get the exclusive access without
arbitration, grab() method should be used.

Grab-Ungrab

task grab(uvm_sequencer_base sequencer = null)


function void ungrab(uvm_sequencer_base sequencer = null)

grab() method requests a lock on the specified sequencer. A grab() request is put in
front of the arbitration queue.  It will be arbitrated before any other requests.  A
grab() is granted when no other grabs or locks are blocking this sequence.

A grab() is blocking task and when access is granted, it will unblock.

Ungrab() method removes any locks or grabs obtained by this sequence on the
specified sequencer.
If no argument is supplied, then current default sequencer is chosen.

Example:

http://testbench.in/UT_12_UVM_SEQUENCE_6.html[9/26/2012 2:23:34 PM]


WWW.TESTBENCH.IN - UVM Tutorial

 virtual task body();
      #25;
      grab();
      repeat(4) begin
         `uvm_do_with(req, { inst == PUSH_B; });
      end
      ungrab();
  endtask

Download the example

uvm_sequence_12.tar
Browse the code in uvm_sequence_12.tar

Command to sun the simulation

VCS Users : make vcs


Questa Users: make questa

0: Driving Instruction  PUSH_A
10: Driving Instruction  POP_C
20: Driving Instruction  PUSH_A
30: Driving Instruction  PUSH_B
40: Driving Instruction  PUSH_B
50: Driving Instruction  PUSH_B
60: Driving Instruction  PUSH_B
70: Driving Instruction  POP_C
80: Driving Instruction  PUSH_A
90: Driving Instruction  POP_C
100: Driving Instruction  PUSH_A
110: Driving Instruction  POP_C

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/UT_12_UVM_SEQUENCE_6.html[9/26/2012 2:23:34 PM]


WWW.TESTBENCH.IN - UVM Tutorial

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS UVM TLM 1 Index


Introduction
SystemVerilog Before going into the TLM interface concepts, lets see why we need TLM interface Uvm Testbench
Verification Uvm Reporting
Port Based Data Transfer: Uvm Transaction
Constructs Uvm Configuration
Interface Following is a simple verification environment.   Uvm Factory
Uvm Sequence 1
OOPS Uvm Sequence 2
Randomization Uvm Sequence 3
Uvm Sequence 4
Functional Coverage Uvm Sequence 5
Assertion Uvm Sequence 6
Uvm Tlm 1
DPI Uvm Tlm 2
UVM Tutorial Uvm Callback
VMM Tutorial
Report a Bug or Comment
OVM Tutorial on This section - Your
input is what keeps
Easy Labs : SV
Testbench.in improving
Easy Labs : UVM with time!
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample
Components generator and driver are implemented as modules.  These modules are
connected using module ports or SV interfaces.  The advantage of this methodology is,
the two above mentioned components are independent. Instead of consumer module,
Verilog any other component which can understand producer interface can be connected,
Verification which gives a great reusability.
Verilog Switch TB
The disadvantage of this methodology is , data transfer is done at lower lever
Basic Constructs abstraction.

Task Based Data Transfer:


OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/UT_13_UVM_TLM_1.html[9/26/2012 2:23:43 PM]


WWW.TESTBENCH.IN - UVM Tutorial

In the above environment, methods are used to transfer the data between
components. So, this gives a better control and data transfer is done at high level.
The disadvantage is, components are using hierarchal paths which do not allow the
reusability.

TLM interfaces:

UVM has TLM interfaces which provide the advantages which we saw in the above two
data transfer styles.
Data is transferred at high level.  Transactions which are developed by extending the
uvm_sequence_item can be transferred between components using method calls.
These methods are not hierarchal fixed, so that components can be reused.

The advantages of TLM interfaces are


1) Higher level abstraction
2) Reusable. Plug and play connections.
3) Maintainability
4) Less code.
5) Easy to implement.
6) Faster simulation.
7) Connect to Systemc.
8) Can be used for reference model development.

Operation Supported By Tlm Interface:

Putting:
Producer transfers a value to Consumer.
Getting:
Consumer requires a data value from producer.
Peeking:
Copies data from a producer without consuming the data.
Broadcasting:
Transaction is broadcasted to none or one or multiple consumers.

Methods

BLOCKING:
virtual task put(input T1 t)
virtual task get(output T2 t)
virtual task peek(output T2 t)

NON-BLOCKIN:
virtual function bit try_put(input T1 t)
virtual function bit can_put()
virtual function bit try_get(output T2 t)
virtual function bit can_get()
virtual function bit try_peek(output T2 t)

http://testbench.in/UT_13_UVM_TLM_1.html[9/26/2012 2:23:43 PM]


WWW.TESTBENCH.IN - UVM Tutorial

virtual function bit can_peek()

BLOCKING TRANSPORT:
virtual task transport(input T1 req,output T2 rsp)

NON-BLOCKING TRANSPORT:
virtual function bit nb_transport(input T1 req,output T2 rsp)

ANALYSIS:
virtual function void write(input T1 t)

Tlm Terminology :

Producer:
A component which generates a transaction.
Consumer:
A component which consumes the transaction.
Initiator:
A component which initiates process.
Target:
A component which responded to initiator.

Tlm Interface Compilation Models:

Blocking:
A blocking interface conveys transactions in blocking fashion; its methods do not
return until the transaction has been successfully sent or retrieved.  Its methods are
defined as tasks.
Non-blocking:
A non-blocking interface attempts to convey a transaction without consuming
simulation time.  Its methods are declared as functions.  Because delivery may fail
(e.g. the target component is busy and can not accept the request), the methods may
return with failed status.
Combined:

A combination interface contains both the blocking and non-blocking variants.  

Interfaces:

The UVM provides ports, exports and implementation and analysis ports for connecting
your components via the TLM interfaces. Port, Export, implementation terminology
applies to control flow not to data flow.

Port:
Interface that requires an implementation is port.
Import:
Interface that provides an implementation is import ot implementation port.
Export:
Interface used to route transaction interfaces to other layers of the hierarchy.
Analysis:
Interface used to distribute transactions to passive components.

Direction:

Unidirectional:
Data transfer is done in a single direction and flow of control is in either or both
direction.
Bidirectional:
Data transfer is done in both directions and flow of control is in either or both
directions.

Examples:
A read  operation is a bidirectional.
A write operation is unidirectional.

Lets look at a example:


In this example, we will use *_put_* interface.

http://testbench.in/UT_13_UVM_TLM_1.html[9/26/2012 2:23:43 PM]


WWW.TESTBENCH.IN - UVM Tutorial

There are 2 components, producer and consumer.


Producer generates the transaction and Consumers consumes it.
In this example, producer calls the put() method to send transaction to consumer i.e
producer is initiator and consumer is target.
When the put() method in the producer is called, it actually executes the put()
method which is defined in consumer component.

Transaction

We will use the below transaction in this example.

class instruction extends uvm_sequence_item;
  typedef enum {PUSH_A,PUSH_B,ADD,SUB,MUL,DIV,POP_C} inst_t; 
  rand inst_t inst;

  `uvm_object_utils_begin(instruction)
    `uvm_field_enum(inst_t,inst, UVM_ALL_ON)
  `uvm_object_utils_end

  function new (string name = "instruction");
    super.new(name);
  endfunction 
endclass 

Producer:  

1) Define producer component by extending uvm_component.

 class producer extends uvm_component;

 endclass : producer

2) Declare uvm_blocking_put_port port.

   uvm_blocking_put_port#(instruction) put_port;

3) In the constructor, construct the port.

    function new(string name, uvm_component p = null);
      super.new(name,p);
      put_port = new("put_port", this);
    endfunction

4) Define the run() method. In this method, randomize the transaction.


   Then call the put() of the put_port and pass the randomized transaction.

    task run;
      for(int i = 0; i < 10; i++)
        begin
          instruction ints;
          #10;
          ints = new();
          if(ints.randomize()) begin
          `uvm_info("producer", $sformatf("sending  
%s",ints.inst.name()), UVM_MEDIUM)
          put_port.put(ints);
          end
        end
    endtask

Producer source code


  class producer extends uvm_component;

    uvm_blocking_put_port#(instruction) put_port;

http://testbench.in/UT_13_UVM_TLM_1.html[9/26/2012 2:23:43 PM]


WWW.TESTBENCH.IN - UVM Tutorial

    
    function new(string name, uvm_component p = null);
      super.new(name,p);
      put_port = new("put_port", this);
    endfunction
    
    task run;
      for(int i = 0; i < 10; i++)
        begin
          instruction ints;
          #10;
          ints = new();
          if(ints.randomize()) begin
          `uvm_info("producer", $sformatf("sending  
%s",ints.inst.name()), UVM_MEDIUM)
          put_port.put(ints);
          end
        end
    endtask
    
  endclass : producer

Consumer:

1) Define a consumer component by extending uvm_component.

  class consumer extends uvm_component;

  endclass : consumer

2) Declare  uvm_blocking_put_imp import. The parameters to this port are transaction


and the consumer component itself.

 uvm_blocking_put_imp#(instruction,consumer) put_port;

3) In the construct , construct the port.

    function new(string name, uvm_component p = null);
      super.new(name,p);
      put_port = new("put_port", this);
    endfunction

4) Define put() method. When the producer calls "put_port.put(ints);", then  this


method will be called. Arguments to this method is transaction type "instruction".
   In this method, we will just print the transaction.

    task put(instruction t);
          `uvm_info("consumer", $sformatf("receiving %s",t.inst.name()), UVM_MEDIUM) 
    endtask

Consumer source code


  class consumer extends uvm_component;

    uvm_blocking_put_imp#(instruction,consumer) put_port;
    
    function new(string name, uvm_component p = null);
      super.new(name,p);
      put_port = new("put_port", this);
    endfunction
    
    task put(instruction t);
         `uvm_info("consumer", $sformatf("receiving %s",t.inst.name()), UVM_MEDIUM) 
    //push the transaction into queue or array
    //or drive the transaction to next level
    //or drive to interface
    endtask
    
  endclass : consumer

Connecting producer and consumer

In the env class, take the instance of producer and consumer components.
In the connect method, connect the producer put_port to consumer put_port using  

http://testbench.in/UT_13_UVM_TLM_1.html[9/26/2012 2:23:43 PM]


WWW.TESTBENCH.IN - UVM Tutorial

  p.put_port.connect(c.put_port);

Env Source code


  class env extends uvm_env;
    producer p;
    consumer c;
    
    function new(string name = "env");
      super.new(name);
      p = new("producer", this);
      c = new("consumer", this);
    endfunction
    
    function void connect();
      p.put_port.connect(c.put_port);
    endfunction
    
    task run();
      #1000;
       global_stop_request();
    endtask
    
  endclass
  
Testcase
module test;
  env e;
  
  initial begin
    e = new();
    run_test();
  end

endmodule 

Download the example

uvm_tlm_1.tar
Browse the code in uvm_tlm_1.tar

Command to sun the simulation

VCS Users : make vcs


Questa Users: make questa

Log

UVM_INFO producer.sv(26) @ 10:


  env.producer [producer] sending   PUSH_A
UVM_INFO consumer.sv(20) @ 10:
  env.consumer [consumer] receiving PUSH_A
UVM_INFO producer.sv(26) @ 20:
  env.producer [producer] sending   PUSH_B
UVM_INFO consumer.sv(20) @ 20:
  env.consumer [consumer] receiving PUSH_B

One more example using  *_get_* interface as per the below  topology.

Download the example

http://testbench.in/UT_13_UVM_TLM_1.html[9/26/2012 2:23:43 PM]


WWW.TESTBENCH.IN - UVM Tutorial

uvm_tlm_2.tar
Browse the code in uvm_tlm_2.tar

Command to sun the simulation

VCS Users : make vcs


Questa Users: make questa

All Interfaces In Uvm:

uvm_blocking_put_port #(T)
uvm_nonblocking_put_port #(T)
uvm_put_port #(T)
uvm_blocking_get_port #(T)
uvm_nonblocking_get_port #(T)
uvm_get_port #(T)
uvm_blocking_peek_port #(T)
uvm_nonblocking_peek_port #(T)
uvm_peek_port #(T)
uvm_blocking_get_peek_port #(T)
uvm_nonblocking_get_peek_port #(T)
uvm_get_peek_port #(T)
uvm_analysis_port #(T)
uvm_transport_port #(REQ,RSP)
uvm_blocking_transport_port #(REQ,RSP)
uvm_nonblocking_transport_port #(REQ,RSP)
uvm_master_port #(REQ,RSP)
uvm_blocking_master_port #(REQ,RSP)
uvm_nonblocking_master_port #(REQ,RSP)
uvm_slave_port #(REQ,RSP)
uvm_blocking_slave_port #(REQ,RSP)
uvm_nonblocking_slave_port #(REQ,RSP)
uvm_put_export #(T)
uvm_blocking_put_export #(T)
uvm_nonblocking_put_export #(T)
uvm_get_export #(T)
uvm_blocking_get_export #(T)
uvm_nonblocking_get_export #(T)
uvm_peek_export #(T)
uvm_blocking_peek_export #(T)
uvm_nonblocking_peek_export #(T)
uvm_get_peek_export #(T)
uvm_blocking_get_peek_export #(T)
uvm_nonblocking_get_peek_export #(T)
uvm_analysis_export #(T)
uvm_transport_export #(REQ,RSP)
uvm_nonblocking_transport_export #(REQ,RSP)
uvm_master_export #(REQ,RSP)
uvm_blocking_master_export #(REQ,RSP)
uvm_nonblocking_master_export #(REQ,RSP)
uvm_slave_export #(REQ,RSP)
uvm_blocking_slave_export #(REQ,RSP)
uvm_nonblocking_slave_export #(REQ,RSP)
uvm_put_imp #(T,IMP)
uvm_blocking_put_imp #(T,IMP)
uvm_nonblocking_put_imp #(T,IMP)
uvm_get_imp #(T,IMP)
uvm_blocking_get_imp #(T,IMP)
uvm_nonblocking_get_imp #(T,IMP)
uvm_peek_imp #(T,IMP)
uvm_blocking_peek_imp #(T,IMP)
uvm_nonblocking_peek_imp #(T,IMP)
uvm_get_peek_imp #(T,IMP)
uvm_blocking_get_peek_imp #(T,IMP)
uvm_nonblocking_get_peek_imp #(T,IMP)
uvm_analysis_imp #(T,IMP)
uvm_transport_imp#(REQ,RSP,IMP,REQ_IMP,RSP_IMP)
uvm_blocking_transport_imp#(REQ,RSP,IMP,REQ_IMP,RSP_IMP)
uvm_nonblocking_transport_imp#(REQ,RSP,IMP,REQ_IMP,RSP_IMP)
uvm_master_imp #(REQ,RSP,IMP,REQ_IMP,RSP_IMP)
uvm_blocking_master_imp#(REQ,RSP,IMP,REQ_IMP,RSP_IMP)
uvm_nonblocking_master_imp#(REQ,RSP,IMP,REQ_IMP,RSP_IMP)
uvm_slave_imp#(REQ,RSP,IMP,REQ_IMP,RSP_IMP)
uvm_blocking_slave_imp#(REQ,RSP,IMP,REQ_IMP,RSP_IMP)
uvm_nonblocking_slave_imp#(REQ,RSP,IMP,REQ_IMP,RSP_IMP)

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/UT_13_UVM_TLM_1.html[9/26/2012 2:23:43 PM]


WWW.TESTBENCH.IN - UVM Tutorial

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/UT_13_UVM_TLM_1.html[9/26/2012 2:23:43 PM]


WWW.TESTBENCH.IN - UVM Tutorial

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS UVM TLM 2 Index


Introduction
SystemVerilog Analysis Uvm Testbench
Verification Uvm Reporting
The analysis port  is used to perform non-blocking broadcasts of transactions.  It is by Uvm Transaction
Constructs components like monitors/drivers to publish transactions to its subscribers, which are Uvm Configuration
Interface typically scoreboards and response/coverage collectors. For each port, more than one Uvm Factory
component can be connected. Even if a component is not connected to the port, Uvm Sequence 1
OOPS Uvm Sequence 2
simulation can continue, unlike put/get ports where simulation is not continued.
Randomization Uvm Sequence 3
The uvm_analysis_port consists of a single function, write().  Subscriber component Uvm Sequence 4
Functional Coverage Uvm Sequence 5
should provide an implementation of write()method. UVM provides the
Assertion uvm_subscriber base component to simplify this operation, so a typical analysis Uvm Sequence 6
component would extend uvm_subscriber and its export is analysis_export. Uvm Tlm 1
DPI Uvm Tlm 2
UVM Tutorial Uvm Callback
VMM Tutorial Lets write a example.
In the example, we will define a monitor component and a subscriber. Report a Bug or Comment
OVM Tutorial on This section - Your
Monitor source code: input is what keeps
Easy Labs : SV
Testbench.in improving
Easy Labs : UVM In monitor, call the function write() pass the transaction. with time!
Easy Labs : OVM
class monitor extends uvm_monitor;
Easy Labs : VMM     uvm_analysis_port #(instruction) anls_port;
AVM Switch TB
    function new(string name, uvm_component p = null);
VMM Ethernet sample         super.new(name,p);
        anls_port = new("anls_port", this);
    endfunction
Verilog
Verification     task run;
       instruction inst;
Verilog Switch TB        inst = new();
Basic Constructs        #10ns;
       inst.inst = instruction::MUL;
       anls_port.write(inst); 
       #10ns;
OpenVera        inst.inst = instruction::ADD;
Constructs        anls_port.write(inst); 
Switch TB        #10ns;
       inst.inst = instruction::SUB;
RVM Switch TB        anls_port.write(inst); 
RVM Ethernet sample     endtask
endclass
Specman E Subscriber source code:
Interview Questions
In Subscriber, define the write() method.

  class subscriber extends uvm_subscriber#(instruction);
    
    function new(string name, uvm_component p = null);
        super.new(name,p);
    endfunction

    function void write(instruction t);
       `uvm_info(get_full_name(),

http://testbench.in/UT_14_UVM_TLM_2.html[9/26/2012 2:23:53 PM]


WWW.TESTBENCH.IN - UVM Tutorial

         $sformatf("receiving %s",t.inst.name()), UVM_MEDIUM) 


    endfunction

  endclass : subscriber

Env source code:


  class env extends uvm_env;
    monitor mon;
    subscriber sb,cov;
    
    function new(string name = "env");
      super.new(name);
      mon = new("mon", this);
      sb  = new("sb", this);
      cov = new("cov", this);
    endfunction
    
    function void connect();
      mon.anls_port.connect(sb.analysis_export);
      mon.anls_port.connect(cov.analysis_export);
    endfunction
    
    task run();
      #1000;
       global_stop_request();
    endtask
    
  endclass

module test;
  env e;
  
  initial begin
    e = new();
    run_test();
  end

endmodule

Download the example

uvm_tlm_3.tar
Browse the code in uvm_tlm_3.tar

Command to sun the simulation

VCS Users : make vcs


Questa Users: make questa

From the below log, you see that transaction is sent to both the components cov and
sb.

Log

UVM_INFO subscriber.sv(18) @ 0: env.cov [env.cov] receiving MUL


UVM_INFO subscriber.sv(18) @ 0: env.sb [env.sb] receiving MUL
UVM_INFO subscriber.sv(18) @ 0: env.cov [env.cov] receiving ADD
UVM_INFO subscriber.sv(18) @ 0: env.sb [env.sb] receiving ADD
UVM_INFO subscriber.sv(18) @ 0: env.cov [env.cov] receiving SUB
UVM_INFO subscriber.sv(18) @ 0: env.sb [env.sb] receiving SUB

Tlm Fifo

Tlm_fifo provides storage of transactions between two independently running


processes just like mailbox.  Transactions are put into the FIFO via the put_export and
fetched from the get_export.  

http://testbench.in/UT_14_UVM_TLM_2.html[9/26/2012 2:23:53 PM]


WWW.TESTBENCH.IN - UVM Tutorial

Methods

Following are the methods defined for tlm fifo.

 function new(string name,  
 uvm_component parent = null,
 int size = 1)

The size indicates the maximum size of the FIFO; a value of zero indicates no upper
bound.

 virtual function int size()

Returns the capacity of the FIFO. 0 indicates the FIFO capacity has no limit.

 virtual function int used()

Returns the number of entries put into the FIFO.

 virtual function bit is_empty()

Returns 1 when there are no entries in the FIFO, 0 otherwise.

 virtual function bit is_full()

Returns 1 when the number of entries in the FIFO is equal to its size, 0 otherwise.

 virtual function void flush()

Removes all entries from the FIFO, after which used returns 0 and is_empty returns 1.

Example

Lets implement a example.


In this example, we will use a tlm_fifo to connect  producer and consumer.
The producer component generates the transaction and using its put_port  pot()
method, sends transaction out.  The consumer component, to get the transaction
from outside, uses get() method of get_port.  These two ports are connected to
tlm_fifo in the env class. In this example, producer and consumer are initiators as
both components are calling the methods.

Producer source code:

  class producer extends uvm_component;
    uvm_blocking_put_port#(int) put_port;
    
    function new(string name, uvm_component p = null);
      super.new(name,p);
      put_port = new("put_port", this);
      
    endfunction
    
    task run;
      int randval;
      for(int i = 0; i < 10; i++)
        begin
          #10;

http://testbench.in/UT_14_UVM_TLM_2.html[9/26/2012 2:23:53 PM]


WWW.TESTBENCH.IN - UVM Tutorial

           randval = $urandom_range(4,10);


          `uvm_info("producer",
              $sformatf("sending   %d",randval), UVM_MEDIUM)
          put_port.put(randval);
        end
    endtask
    
  endclass : producer

Consumer source code:


  class consumer extends uvm_component;
    uvm_blocking_get_port#(int) get_port;
    
    function new(string name, uvm_component p = null);
      super.new(name,p);
      get_port = new("get_port", this);
    endfunction
    
    task run;
      int val;
      forever
        begin
          get_port.get(val);
          `uvm_info("consumer", 
              $sformatf("receiving %d", val), UVM_MEDIUM)
        end
    endtask
    
  endclass : consumer

Env source code:


  class env extends uvm_env;
    producer p;
    consumer c;
    tlm_fifo #(int) f;
    
    function new(string name = "env");
      super.new(name);
      p = new("producer", this);
      c = new("consumer", this);
      f = new("fifo", this);
    endfunction
    
    function void connect();
      p.put_port.connect(f.put_export);
      c.get_port.connect(f.get_export);
    endfunction
    
    task run();
      #1000 global_stop_request();
    endtask
    
  endclass

Download the example

uvm_tlm_4.tar
Browse the code in uvm_tlm_4.tar

Command to sun the simulation

VCS Users : make vcs


Questa Users: make questa

Log

UVM_INFO producer.sv(28) @ 10: env.producer [producer] sending             7


UVM_INFO consumer.sv(26) @ 10: env.consumer [consumer] receiving           7
UVM_INFO producer.sv(28) @ 20: env.producer [producer] sending             4
UVM_INFO consumer.sv(26) @ 20: env.consumer [consumer] receiving           4

http://testbench.in/UT_14_UVM_TLM_2.html[9/26/2012 2:23:53 PM]


WWW.TESTBENCH.IN - UVM Tutorial

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/UT_14_UVM_TLM_2.html[9/26/2012 2:23:53 PM]


WWW.TESTBENCH.IN - UVM Tutorial

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS UVM CALLBACK Index


Introduction
SystemVerilog Callback mechanism is used for altering the behavior of the transactor without Uvm Testbench
Verification modifying the transactor. One of the many promises of Object-Oriented programming Uvm Reporting
is that it will allow for plug-and-play re-usable verification components. Verification Uvm Transaction
Constructs Designers will hook the transactors together to make a verification environment. In Uvm Configuration
Interface SystemVerilog, this hooking together of transactors can be tricky. Callbacks provide a Uvm Factory
mechanism whereby independently developed objects may be connected together in Uvm Sequence 1
OOPS Uvm Sequence 2
simple steps.
Randomization Uvm Sequence 3
This article describes uvm callbacks. uvm callback might be used for simple Uvm Sequence 4
Functional Coverage Uvm Sequence 5
notification, two-way communication, or to distribute work in a process. Some
Assertion requirements are often unpredictable when the transactor is first written. So a Uvm Sequence 6
transactor should provide some kind of hooks for executing the code which is defined Uvm Tlm 1
DPI Uvm Tlm 2
afterwards. In uvm, these hooks are created using callback methods. For instance, a
UVM Tutorial driver is developed and an empty method is called before driving the transaction to Uvm Callback
VMM Tutorial the DUT. Initially this empty method does nothing. As the implementation goes, user
may realize that he needs to print the state of the transaction or to delay the Report a Bug or Comment
OVM Tutorial transaction driving to DUT or inject an error into transaction. Callback mechanism on This section - Your
allows executing the user defined code in place of the empty callback method.  Other input is what keeps
Easy Labs : SV
example of callback usage is in monitor. Callbacks can be used in a monitor for Testbench.in improving
Easy Labs : UVM collecting coverage information or for hooking up to scoreboard to pass transactions with time!
Easy Labs : OVM for self checking. With this, user is able to control the behavior of the transactor in
verification environment and individual testcases without doing any modifications to
Easy Labs : VMM the transactor itself.  
AVM Switch TB
Following are the steps to be followed to create a transactor with callbacks. We will
VMM Ethernet sample see simple example of creating a Driver transactor to support callback mechanism.

Stpe 1) Define a facade class.


Verilog
Verification  1) Extend the uvm_callback class to create a faced class.
Verilog Switch TB    class Driver_callback extends uvm_callback;
Basic Constructs
   endclass : Driver_callback

 2)Define required callback methods. All the callback methods must be virtual.
OpenVera    In this example, we will create callback methods which will be called before driving
Constructs the packet and after driving the packet to DUT.
Switch TB
   virtual task pre_send(); endtask
RVM Switch TB    virtual task post_send(); endtask
RVM Ethernet sample
 3)Define the constructor and get_type_name methods and define type_name.

   function new (string name = "Driver_callback");
Specman E      super.new(name);
Interview Questions    endfunction

   static string type_name = "Driver_callback";

   virtual function string get_type_name();
     return type_name;
   endfunction

Step 2) Register the facade class with driver and call the callback methods.

http://testbench.in/UT_15_UVM_CALLBACK.html[9/26/2012 2:24:10 PM]


WWW.TESTBENCH.IN - UVM Tutorial

 1)In the driver class, using `uvm_register_cb() macro, register the facade class.

   class Driver extends uvm_component;

      `uvm_component_utils(Driver)

      `uvm_register_cb(Driver,Driver_callback)

      function new (string name, uvm_component parent=null);
         super.new(name,parent);
      endfunction

   endclass

 2)Calling callback method.


   Inside the transactor, callback methods should be called whenever something
interesting happens.
   We will call the callback method before driving the packet and after driving the
packet. We defined 2 methods in facade class. We will call pre_send() method before
sending the packet and post_send() method after sending the packet.

   Using a `uvm_do_callbacks() macro, callback methods are called.


   There are 3 argumentd to `uvm_do_callbacks(,) macro.
   First argument must be the driver class and second argument is facade class.
   Third argument must be the callback method in the facade class.
 
   To call pre_send() method , use macro
   `uvm_do_callbacks(Driver,Driver_callback,pre_send());
   and similarly to call post_send() method,
   `uvm_do_callbacks(Driver,Driver_callback,post_send());

   Place the above macros before and after driving the packet.

 virtual task run();
    
     repeat(2) begin 
         `uvm_do_callbacks(Driver,Driver_callback,pre_send())
         $display(" Driver: Started Driving the packet ...... %d",$time);  
         // Logic to drive the packet goes hear
         // let's consider that it takes 40 time units to drive a packet.
         #40; 
         $display(" Driver: Finished Driving the packet ...... %d",$time);  
         `uvm_do_callbacks(Driver,Driver_callback,post_send())
     end
  endtask

   With this, the Driver implementation is completed with callback support.

Driver And Driver Callback Class Source Code


class Driver_callback extends uvm_callback;

  function new (string name = "Driver_callback");
    super.new(name);
  endfunction

  static string type_name = "Driver_callback";

  virtual function string get_type_name();
    return type_name;
  endfunction

  virtual task pre_send(); endtask
  virtual task post_send(); endtask

http://testbench.in/UT_15_UVM_CALLBACK.html[9/26/2012 2:24:10 PM]


WWW.TESTBENCH.IN - UVM Tutorial

endclass : Driver_callback

class Driver extends uvm_component;

  `uvm_component_utils(Driver)

  `uvm_register_cb(Driver,Driver_callback)

  function new (string name, uvm_component parent=null);
    super.new(name,parent);
  endfunction

 
 virtual task run();
    
     repeat(2) begin 
         `uvm_do_callbacks(Driver,Driver_callback,pre_send())
         $display(" Driver: Started Driving the packet ...... %d",$time);  
         // Logic to drive the packet goes hear
         // let's consider that it takes 40 time units to drive a packet.
         #40; 
         $display(" Driver: Finished Driving the packet ...... %d",$time);  
         `uvm_do_callbacks(Driver,Driver_callback,post_send())
     end
  endtask

endclass

Let's run the driver in simple testcase. In this testcase, we are not changing any
callback methods definitions.

Testcase Source Code

module test;

Driver drvr;

initial begin
  drvr = new("drvr");
  run_test();
end 

endmodule 

Download files

uvm_callback_1.tar
Browse the code in uvm_callback_1.tar

Command to run the simulation

VCS Users : make vcs


Questa Users: make questa

Log report

UVM_INFO @ 0: reporter [RNTST] Running test ...


 Driver: Started Driving the packet ......                    0
 Driver: Finished Driving the packet ......                   40
 Driver: Started Driving the packet ......                   40
 Driver: Finished Driving the packet ......                   80
UVM_ERROR @ 9200: reporter [TIMOUT] Watchdog timeout of '9200' expired.

Following steps are to be performed for using callback mechanism to do required


functionality.
We will see how to use the callbacks which are implemented in the above defined
driver in a testcase.

1) Implement the user defined callback method by extending facade class of the
driver class.
   We will delay the driving of packet be 20 time units using the pre_send() call back
method.

http://testbench.in/UT_15_UVM_CALLBACK.html[9/26/2012 2:24:10 PM]


WWW.TESTBENCH.IN - UVM Tutorial

   We will just print a message from post_send() callback method.

class Custom_Driver_callbacks_1 extends Driver_callback;

     function new (string name = "Driver_callback");
        super.new(name);
     endfunction
  
     virtual task pre_send();
       $display("CB_1:pre_send: Delaying the packet driving by 20 time units.
%d",$time);
       #20;
     endtask
  
     virtual task post_send();
      $display("CB_1:post_send: Just a message from  post send callback method \n");
     endtask
 
endclass 

2) Construct the user defined facade class object.

     Custom_Driver_callbacks_1 cb_1;


     cb_1 = new("cb_1");

3) Register the callback method with the driver component. uvm_callback class has
static method add() which is used to register the callback.

   uvm_callbacks #(Driver,Driver_callback)::add(drvr,cb_1);
  

Testcase 2 Source Code


class Custom_Driver_callbacks_1 extends Driver_callback;

     function new (string name = "Driver_callback");
        super.new(name);
     endfunction
  
     virtual task pre_send();
       $display("CB_1:pre_send: Delaying the packet driving by 20 time units.
%d",$time);
       #20;
     endtask
  
     virtual task post_send();
      $display("CB_1:post_send: Just a message from  post send callback method \n");
     endtask
 
endclass 

module test;

initial begin
  Driver drvr;
  Custom_Driver_callbacks_1 cb_1;
  drvr = new("drvr");
  cb_1 = new("cb_1");
  uvm_callbacks #(Driver,Driver_callback)::add(drvr,cb_1);
  uvm_callbacks #(Driver,Driver_callback)::display();
  run_test();
end 

endmodule 

Download the example

uvm_callback_2.tar
Browse the code in uvm_callback_2.tar

Simulation Command

VCS Users : make vcs


Questa Users: make questa

http://testbench.in/UT_15_UVM_CALLBACK.html[9/26/2012 2:24:10 PM]


WWW.TESTBENCH.IN - UVM Tutorial

  Run the testcase. See the log results; We delayed the driving of packet by 20 time
units using callback mechanism. See the difference between the previous testcase log
and this log.

Log report

cb_1   on drvr  ON
UVM_INFO @ 0: reporter [RNTST] Running test ...
CB_1:pre_send: Delaying the packet driving by 20 time units.                    0
 Driver: Started Driving the packet ......                   20
 Driver: Finished Driving the packet ......                   60
CB_1:post_send: Just a message from  post send callback method

CB_1:pre_send: Delaying the packet driving by 20 time units.                   60


 Driver: Started Driving the packet ......                   80
 Driver: Finished Driving the packet ......                  120
CB_1:post_send: Just a message from  post send callback method

UVM_ERROR @ 9200: reporter [TIMOUT] Watchdog timeout of '9200' expired.

  

Now we will see registering 2 callback methods.


   1) Define another user defined callback methods by extending facade class.

class Custom_Driver_callbacks_2 extends Driver_callback;
  
     function new (string name = "Driver_callback");
        super.new(name);
     endfunction

     virtual task pre_send();
       $display("CB_2:pre_send: Hai .... this is from Second callback %d",$time);
     endtask
 
endclass

   2) Construct the user defined facade class object.

     Custom_Driver_callbacks_2 cb_2;


     cb_2 = new("cb_2");

   3) Register the object

    uvm_callbacks #(Driver,Driver_callback)::add(drvr,cb_2);

Testcase 3 Source Code


    
class Custom_Driver_callbacks_1 extends Driver_callback;

     function new (string name = "Driver_callback");
        super.new(name);
     endfunction
  
     virtual task pre_send();
       $display("CB_1:pre_send: Delaying the packet driving by 20 time units.
%d",$time);
       #20;
     endtask
  
     virtual task post_send();
      $display("CB_1:post_send: Just a message from  post send callback method \n");
     endtask
 
endclass 

class Custom_Driver_callbacks_2 extends Driver_callback;
  
     function new (string name = "Driver_callback");
        super.new(name);
     endfunction

http://testbench.in/UT_15_UVM_CALLBACK.html[9/26/2012 2:24:10 PM]


WWW.TESTBENCH.IN - UVM Tutorial

     virtual task pre_send();
       $display("CB_2:pre_send: Hai .... this is from Second callback %d",$time);
     endtask
  
 
   endclass
module test;

initial begin
  Driver drvr;
  Custom_Driver_callbacks_1 cb_1;
  Custom_Driver_callbacks_2 cb_2;
  drvr = new("drvr");
  cb_1 = new("cb_1");
  cb_2 = new("cb_2");
  uvm_callbacks #(Driver,Driver_callback)::add(drvr,cb_1);
  uvm_callbacks #(Driver,Driver_callback)::add(drvr,cb_2);
  uvm_callbacks #(Driver,Driver_callback)::display();
  run_test();
end 

endmodule

Download source code

uvm_callback_3.tar
Browse the code in uvm_callback_3.tar

Command to run the simulation

VCS Users : make vcs


Questa Users: make questa

 Run the testcase and analyze the result.

Log report

UVM_INFO @ 0: reporter [RNTST] Running test ...


CB_1:pre_send: Delaying the packet driving by 20 time units.                    0
CB_2:pre_send: Hai .... this is from Second callback                   20
 Driver: Started Driving the packet ......                   20
 Driver: Finished Driving the packet ......                   60
CB_1:post_send: Just a message from  post send callback method

CB_1:pre_send: Delaying the packet driving by 20 time units.                   60


CB_2:pre_send: Hai .... this is from Second callback                   80
 Driver: Started Driving the packet ......                   80
 Driver: Finished Driving the packet ......                  120
CB_1:post_send: Just a message from  post send callback method

UVM_ERROR @ 9200: reporter [TIMOUT] Watchdog timeout of '9200' expired.

 The log results show that pre_send() method of CDc_1 is called first and then
pre_send() method of Cdc_2. This is because of the order of the registering callbacks.

  uvm_callbacks #(Driver,Driver_callback)::add(drvr,cb_1);
  uvm_callbacks #(Driver,Driver_callback)::add(drvr,cb_2);

Now we will see how to change the order of the callback method calls.
By changing the sequence of calls to add() method, order of callback method calling
can be changed.

Testcase 4 Source Code


module test;

initial begin
  Driver drvr;
  Custom_Driver_callbacks_1 cb_1;
  Custom_Driver_callbacks_2 cb_2;
  drvr = new("drvr");
  cb_1 = new("cb_1");
  cb_2 = new("cb_2");

http://testbench.in/UT_15_UVM_CALLBACK.html[9/26/2012 2:24:10 PM]


WWW.TESTBENCH.IN - UVM Tutorial

  uvm_callbacks #(Driver,Driver_callback)::add(drvr,cb_2);
  uvm_callbacks #(Driver,Driver_callback)::add(drvr,cb_1);
  uvm_callbacks #(Driver,Driver_callback)::display();
  run_test();
end 

endmodule 

Download the source code

uvm_callback_4.tar
Browse the code in uvm_callback_4.tar

Command to run the simulation

VCS Users : make vcs


Questa Users: make questa

Run and analyze the results.


Log results show that, pre_send() method of CDs_1 is called after calling
CDs_2  pre_send() method.

Log file report

UVM_INFO @ 0: reporter [RNTST] Running test ...


CB_2:pre_send: Hai .... this is from Second callback                    0
CB_1:pre_send: Delaying the packet driving by 20 time units.                    0
 Driver: Started Driving the packet ......                   20
 Driver: Finished Driving the packet ......                   60
CB_1:post_send: Just a message from  post send callback method

CB_2:pre_send: Hai .... this is from Second callback                   60


CB_1:pre_send: Delaying the packet driving by 20 time units.                   60
 Driver: Started Driving the packet ......                   80
 Driver: Finished Driving the packet ......                  120
CB_1:post_send: Just a message from  post send callback method

UVM_ERROR @ 9200: reporter [TIMOUT] Watchdog timeout of '9200' expired.

Methods:

add_by_name:

We have seen, the usage of add() method which requires object.


Using add_by_name() method, callback can be registered with object name.

static function void add_by_name(string name,
        uvm_callback cb,
        uvm_component root,
        uvm_apprepend ordering = UVM_APPEND)

delete:

uvm also provides uvm_callbacks::delete() method to remove the callback methods


which are registered.
Similar to delete, delete_by_name() method is used to remove the callback using the
object name.

static function void delete_by_name(string name,
       uvm_callback cb,
       uvm_component root )

Macros:

`uvm_register_cb 

   Registers the given CB callback type with the given T object type.

`uvm_set_super_type

http://testbench.in/UT_15_UVM_CALLBACK.html[9/26/2012 2:24:10 PM]


WWW.TESTBENCH.IN - UVM Tutorial

   Defines the super type of T to be ST.

`uvm_do_callbacks 

   Calls the given METHOD of all callbacks of type CB registered with the calling object

`uvm_do_obj_callbacks

   Calls the given METHOD of all callbacks based on type CB registered with the given
object, OBJ, which is or is based on type T.

`uvm_do_callbacks_exit_on

   Calls the given METHOD of all callbacks of type CB registered with the calling object

`uvm_do_obj_callbacks_exit_on

   Calls the given METHOD of all callbacks of type CB registered with the given object
OBJ, which must be or be based on type T, and returns upon the first callback that
returns the bit value given by VAL.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/UT_15_UVM_CALLBACK.html[9/26/2012 2:24:10 PM]


WWW.TESTBENCH.IN - VMM Tutorial

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INTRODUCTION Index


Introduction
SystemVerilog Vmm Log
Verification Vmm Env
Verification methodological manual (VMM) , co-authored by verification experts from Vmm Data
Constructs ARM and Synopsys, describes how to use SystemVerilog to develop scalable, Vmm Channel
Interface predictable and reusable  verification environments. VMM has become important Vmm Atomic Generator
factor in increasing verification reuse, improved verification productivity and Vmm Xactor
OOPS Vmm Callback
timeliness.
Randomization Vmm Test
VMM consists coding guide lines and base classes. VMM is focused on Coverage driven Vmm Channel Record
Functional Coverage And Playback
verification methodology. VMM supports both the top-down and bottom-up
Assertion approaches. VMM follows layered test bench architecture to take the full advantage of Vmm Scenario Generator
the automation. The VMM for SystemVerilog TestBench architecture comprises five Vmm Opts
DPI
layers.
UVM Tutorial Report a Bug or Comment
The layered TestBench is the heart of the verification environment in VMM: on This section - Your
VMM Tutorial
input is what keeps
OVM Tutorial signal layer: Testbench.in improving
Easy Labs : SV This layer connects the TestBench to the RTL design. It consists of interface, clocking, with time!
and modport constructs.
Easy Labs : UVM  
Easy Labs : OVM command layer:
Easy Labs : VMM This layer contains lower-level driver and monitor components, as well as the
assertions. This layer provides a transaction-level interface to the layer above and
AVM Switch TB drives the physical pins via the signal layer.
VMM Ethernet sample
functional layer:
This layer contains higher-level driver and monitor components, as well as the self-
checking structure (scoreboard/tracker).
Verilog
Verification scenario layer:
Verilog Switch TB This layer uses generators to produce streams or sequences of transactions that are
applied to the functional layer. The generators have a set of weights, constraints or
Basic Constructs scenarios specified by the test layer. The randomness of constrained-random testing is
introduced within this layer.

OpenVera test layer:


Constructs Tests are located in this layer. Test layer can interact with all the layers. This layer
allows to pass directed commands to functional and command layer.
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/VM_01_INTRODUCTION.html[9/26/2012 2:24:18 PM]


WWW.TESTBENCH.IN - VMM Tutorial

VMM libraries consists following sub libraries

VMM Standard Library


VMM Register Abstraction Layer (RAL)
VMM Hardware Abstraction Layer (HAL)
VMM Scoreboarding  

The VMM Standard Library provides base classes for key aspects of the verification
environment, transaction generation, notification service and a message logging
service.

These libraries can be downloaded from http://www.vmmcentral.org


Following are some of the classes and macros defined in the VMM Standard Library

vmm_env :
The class is a base class used to implement verification environments.

vmm_xactor :
This base class is to be used as the basis for all transactors, including bus-functional
models, monitors and generators. It provides a standard control mechanism expected
to be found in all transactors.

vmm_channel :
This class implements a generic transaction-level interface mechanism. Transaction-
level interfaces remove the higher-level layers from the physical interface details.
Using channels, transactors pass transactions from one to other.

vmm_data :
This base class is to be used as the basis for all transaction descriptors and data
models. It provides a standard set of methods expected to be found in all descriptors.
User must extend vmm_data to create a custom transaction.

vmm_log :
The vmm_log class used implements an interface to the message service. These
classes provide a mechanism for reporting simulation activity to a file or a terminal.
To ensure a consistent look and feel to the messages issued from different sources,
vmm_log is used.

vmm_atomic_gen :
This is a macro. This macro defines a atomic generator for generating transaction
which are derived from vmm_data.

http://testbench.in/VM_01_INTRODUCTION.html[9/26/2012 2:24:18 PM]


WWW.TESTBENCH.IN - VMM Tutorial

vmm_scenario_gen :
Defines a scenario generator class to generate sequences of related instances of the
specified class.

vmm_notify :
The vmm_notify class implements an interface to the notification service. The
notification service provides a synchronization mechanism for concurrent threads or
transactors.

vmm_test :
This class will be useful for runtime selection of testcases to run on an environment.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/VM_01_INTRODUCTION.html[9/26/2012 2:24:18 PM]


WWW.TESTBENCH.IN - VMM Tutorial

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS VMM LOG Index


Introduction
SystemVerilog Vmm Log
Verification The vmm_log class provides an interface to the VMM message service so that all Vmm Env
messages, regardless of their sources, can have a common "look and feel".  Not always Vmm Data
Constructs we require all type of messages. During normal simulation, we need only note, error Vmm Channel
Interface and warning messages. While you are debugging, you may need debug messages and Vmm Atomic Generator
trace messages. vmm_log allows you to control the messages. This helps in debugging. Vmm Xactor
OOPS Vmm Callback
vmm_log has a uniform message format which helps for post processing the log file
Randomization using scripts if needed. You can also convert a error message to warning message Vmm Test
which is required in some specific testcases. The message service describes and Vmm Channel Record
Functional Coverage And Playback
controls messages based on several concepts:
Assertion Vmm Scenario Generator
Message source: Vmm Opts
DPI
A message source can be any component of a TestBench. They can be Transactors,
UVM Tutorial scoreboards, assertions, environment or a testcase. Report a Bug or Comment
  on This section - Your
VMM Tutorial
input is what keeps
Message filters:
OVM Tutorial
Filters can prevent or allow a message from being issued. They can be promoted or Testbench.in improving
with time!
Easy Labs : SV demoted based on the identifier, type, severity or content.
Easy Labs : UVM
Easy Labs : OVM Vmm Message Type
Easy Labs : VMM
Individual messages are categorized into different types.
AVM Switch TB
VMM Ethernet sample FAILURE_TYP  : For reporting error messages.
NOTE_TYP     : Normal message used to indicate the simulation progress.
DEBUG_TYP    : Message useful for debugging purpose.
Verilog TIMING_TYP   : For reporting timing errors.
Verification XHANDLING_TYP: For reporting X or Z on signals
INTERNAL_TYP : Messages from the VMM base classes.
Verilog Switch TB
REPORT_TYP,PROTOCOL_TYP,TRANSACTION_TYP,COMMAND_TYP,CYCLE_TYP :
Basic Constructs Additional message types that can be used by transactors.

OpenVera
Message Severity
Constructs
Switch TB Individual messages are categorized into different severities
RVM Switch TB
FATAL_SEV  : An error which causes a program to abort.  
RVM Ethernet sample ERROR_SEV  : Simulation aborts after a certain number of errors are observed.
WARNING_SEV: Simulation can proceed and still produce useful result.
NORMAL_SEV : This message indicates the state of simulation.
Specman E TRACE_SEV  : This message identifies high-level internal information that is not
Interview Questions normally issued.
DEBUG_SEV  : This message identifies medium-level internal information that is not
normally issued.
VERBOSE_SEV: This message identifies low-level internal information that is not
normally issued.

Vmm Log Macros

We can use the following predefined macros to select the message severity.

http://testbench.in/VM_02_VMM_LOG.html[9/26/2012 2:24:29 PM]


WWW.TESTBENCH.IN - VMM Tutorial

`vmm_fatal(vmm_log log, string msg);
`vmm_error(vmm_log log, string msg);
`vmm_warning(vmm_log log, string msg);
`vmm_note(vmm_log log, string msg);
`vmm_trace(vmm_log log, string msg);
`vmm_debug(vmm_log log, string msg);
`vmm_verbose(vmm_log log, string msg);

The second argument in the above macro can accept only a string. So if we want to
pass a complex message, then convert it to string using a $psprintf() system task.

These macros are simple to use and the macro expansion is easy to understand.
Following is a expansion of `vmm_not macro. Other macros also have same logic with
different Message severity levels.

`define vmm_note ( log, msg )

do 
   if (log.start_msg(vmm_log::NOTE_TYP)) begin 
      void'(log.text(msg)); 
      log.end_msg(); 
   end 
while (0)

To change the severity and verbosity of the messages services at simulation time , use
+vmm_log_default=SEVERITY TYPE. Where SEVERITY TYPE can be ERROR, WARNING,
NORMAL, TRACE, DEBUG OR VERBOSE.  We will see the demo of this service in the
example.

Message Handling

Different messages require different action by the simulator once the message has
been issued.

ABORT_SIM  : Aborts the simulation.


COUNT_ERROR: Count the message as an error.
STOP_PROMPT: Stop the simulation immediately and return to the simulation
runtime-control command prompt.
DEBUGGER   : Stop the simulation immediately and start the graphical debugging
environment.
DUMP_STACK : Dump the call stack or any other context status information and
continue the simulation.
CONTINUE   : Continue the simulation normally.

To use this vmm feature, take the instance of vmm_log and use the message macros.
For most of the vmm classes like vmm_env,vmm_xactor,vmm_data etc, this
instantiation is already done internally, so user dont need to take a separate instance
of vmm_log.

vmm_log log = new("test_log","log");

Following is a simple program which demonstrates the usages of different severity


levels.
This program creates the object of a vmm_log class and uses log macros to define
various messages. You can also see the usage of $psprintf() system task.

program test_log();

vmm_log log = new("test_log","log");

   initial begin

http://testbench.in/VM_02_VMM_LOG.html[9/26/2012 2:24:29 PM]


WWW.TESTBENCH.IN - VMM Tutorial

       `vmm_error(log,"This is a ERROR Message");


       `vmm_warning(log,"This is a WARNING Message");
       `vmm_note(log,$psprintf("This is a NOTE Message at time %d",$time)); 
       `vmm_trace(log,"This is a TRACE Message");
       `vmm_debug(log,"This is a DEBUG Message");
       `vmm_verbose(log,"This is a VERBOSE Message");
       `vmm_fatal(log,"This is a FATAL Message");
   end

endprogram

Download the source code

vmm_log.tar
Browse the code in vmm_log.tar

Simulation commands
vcs -sverilog -f filelist -R -ntb_opts rvm -ntb_opts dtm

You can see the following messages on the terminal. You can only see Normal, Error,
warning and fatal messages.

Log file report:

!ERROR![FAILURE] on test_log(log) at                    0:


    This is a ERROR Message
WARNING[FAILURE] on test_log(log) at                    0:
    This is a WARNING Message
Normal[NOTE] on test_log(log) at                    0:
    This is a NOTE Message at time                    0
*FATAL*[FAILURE] on test_log(log) at                    0:
    This is a FATAL Message

Run the simulation with command option +vmm_log_default=DEBUG


You can see the following messages on the terminal. You can see that Debug and trace
message is also coming.

Log file report:

!ERROR![FAILURE] on test_log(log) at                    0:


    This is a ERROR Message
WARNING[FAILURE] on test_log(log) at                    0:
    This is a WARNING Message
Normal[NOTE] on test_log(log) at                    0:
    This is a NOTE Message at time                    0
Trace[DEBUG] on test_log(log) at                    0:
    This is a TRACE Message
Debug[DEBUG] on test_log(log) at                    0:
    This is a DEBUG Message
*FATAL*[FAILURE] on test_log(log) at                    0:
    This is a FATAL Message

Run the simulation with command option +vmm_log_default=VERBOSE


You can see the following messages on the terminal. You can see that Trace, Debug
and Verbose messages are also coming.

Log file report:

!ERROR![FAILURE] on test_log(log) at                    0:


    This is a ERROR Message
WARNING[FAILURE] on test_log(log) at                    0:
    This is a WARNING Message
Normal[NOTE] on test_log(log) at                    0:
    This is a NOTE Message at time                    0
Trace[DEBUG] on test_log(log) at                    0:
    This is a TRACE Message
Debug[DEBUG] on test_log(log) at                    0:
    This is a DEBUG Message
Verbose[DEBUG] on test_log(log) at                    0:
    This is a VERBOSE Message
*FATAL*[FAILURE] on test_log(log) at                    0:

http://testbench.in/VM_02_VMM_LOG.html[9/26/2012 2:24:29 PM]


WWW.TESTBENCH.IN - VMM Tutorial

    This is a FATAL Message

Counting Number Of Messages Based Of Message Severity

Some time we need to count the number of messages executed based of the severity
type. vmm_log has get_message_count() function which returns the message count
based on severity type, source and message string.

user dont need to implement a logic to print the state of test i.e TEST PASSED or TEST
FAILED, vmm_env has already implemented this in the report() method. We will see
this in next topic.

virtual function int get_message_count(int severity = ALL_SEVS,
                                      string name = "",
                                      string instance = "",
                                      bit recurse = 0);

Following is a example which demonstrations the  get_message_count() function. The


following example , also demonstrates the use of $psprintf which will be use full to
print message when there are variable arguments to print.

program test_log();

vmm_log log = new("test_log","log");


int fatal_cnt ;
int error_cnt ;
int warn_cnt ; 

   initial begin
       `vmm_note(log,$psprintf("This is a NOTE Message at time %d",$time));
        
       `vmm_error(log,"This is a ERROR Message 1 ");
       `vmm_error(log,"This is a ERROR Message 2 ");
       `vmm_error(log,"This is a ERROR Message 3 ");

      
       `vmm_warning(log,"This is a WARNING Message 1 ");
       `vmm_warning(log,"This is a WARNING Message 2 ");

        fatal_cnt = log.get_message_count(vmm_log::FATAL_SEV, "/./", "/./", 1);
        error_cnt = log.get_message_count(vmm_log::ERROR_SEV, "/./", "/./", 1);
        warn_cnt  = log.get_message_count(vmm_log::WARNING_SEV, "/./", "/./", 1);
    
        $display("\n\n");
        $display(" Number of Fatal messages   : %0d ",fatal_cnt);
        $display(" Number of Error messages   : %0d ",error_cnt);
        $display(" Number of Warning messages : %0d ",warn_cnt);
        $display("\n\n");
  
   end

endprogram

Download the source code

vmm_log_1.tar
Browse the code in vmm_log_1.tar

Simulation commands
vcs -sverilog -f filelist -R -ntb_opts rvm -ntb_opts dtm

Log file report:

Normal[NOTE] on test_log(log) at                    0:

http://testbench.in/VM_02_VMM_LOG.html[9/26/2012 2:24:29 PM]


WWW.TESTBENCH.IN - VMM Tutorial

    This is a NOTE Message at time                    0


!ERROR![FAILURE] on test_log(log) at                    0:
    This is a ERROR Message 1
!ERROR![FAILURE] on test_log(log) at                    0:
    This is a ERROR Message 2
!ERROR![FAILURE] on test_log(log) at                    0:
    This is a ERROR Message 3
WARNING[FAILURE] on test_log(log) at                    0:
    This is a WARNING Message 1
WARNING[FAILURE] on test_log(log) at                    0:
    This is a WARNING Message 2

 Number of Fatal messages   : 0


 Number of Error messages   : 3
 Number of Warning messages : 2

Sometimes we would like to wait for a specific message and execute some logic. For
example, you want to count number of crc error packets transmitted by dut in some
special testcase or you want to stop the simulation after a specific series of messages
are received. vmm_log has a method to wait for a specific message.

virtual task wait_for_msg(string name = "",
                          string instance = "",
                          bit recurse = 0,
                          int typs = ALL_TYPS,
                          int severity = ALL_SEVS,
                          string text = "",
                          logic issued = 1'bx,
                          ref vmm_log_msg msg);

Following is a simple example which demonstrates the use of above method. In this
example, wait_for_msg() method wait for a specific string.

program test_log();

vmm_log log = new("test_log","log");


   vmm_log_msg msg = new(log);

/* This logic is some where in the monitor */


   initial 
   repeat (4) begin
   #($urandom()%10) 
   `vmm_error(log,"Packet with CRC ERROR is received");
   end

/* In testcase you are counting the error messages */

   initial
   forever begin
   log.wait_for_msg("/./","/./",-1,vmm_log::ALL_TYPS,vmm_log::ERROR_SEV,"Packet
with CRC ERROR is received",1'bx,msg);
   // You can count number of crc errored pkts rcvd.
   // or do whatever you want.
   $display(" -- Rcvd CRC ERROR message at %d --",$time);
   end

endprogram

Download the source code

vmm_log_2.tar
Browse the code in vmm_log_2.tar

Simulation commands
vcs -sverilog -f filelist -R -ntb_opts rvm -ntb_opts dtm

http://testbench.in/VM_02_VMM_LOG.html[9/26/2012 2:24:29 PM]


WWW.TESTBENCH.IN - VMM Tutorial

Log file report:

!ERROR![FAILURE] on test_log(log) at                    8:


    Packet with CRC ERROR is received
 -- Rcvd CRC ERROR message at                    8 --
!ERROR![FAILURE] on test_log(log) at                    8:
    Packet with CRC ERROR is received
 -- Rcvd CRC ERROR message at                    8 --
!ERROR![FAILURE] on test_log(log) at                   11:
    Packet with CRC ERROR is received
 -- Rcvd CRC ERROR message at                   11 --
!ERROR![FAILURE] on test_log(log) at                   11:
    Packet with CRC ERROR is received
 -- Rcvd CRC ERROR message at                   11 --

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/VM_02_VMM_LOG.html[9/26/2012 2:24:29 PM]


WWW.TESTBENCH.IN - VMM Tutorial

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS VMM ENV Index


Introduction
SystemVerilog Vmm Log
Verification Vmm Env
Verification environment is developed by extending vmm_env class.  The TestBench Vmm Data
Constructs simulation needs some systematic flow like reset, initialize etc. vmm_env base class Vmm Channel
Interface has methods formalize the simulation steps. All methods are declared as virtual Vmm Atomic Generator
methods. All the Verification components and instantiated, connected and component Vmm Xactor
OOPS Vmm Callback
activities starting is done in this class. As it contains all verification components
Randomization instances, the environment class affects the entire test environment. Vmm Test
Vmm Channel Record
Functional Coverage And Playback
The vmm_env class divides a simulation into the following steps, with corresponding
Assertion methods: Vmm Scenario Generator
  gen_cfg() : Vmm Opts
DPI
Randomize test configuration parameters.
UVM Tutorial Report a Bug or Comment
on This section - Your
VMM Tutorial   build() :
Creates the instances of channels and transactors. Transactors are connected using input is what keeps
OVM Tutorial Testbench.in improving
channels. DUT is also connected to TestBench using the interfaces.
with time!
Easy Labs : SV
Easy Labs : UVM   reset_dut() :
Reset the DUT using the interface signals.
Easy Labs : OVM
Easy Labs : VMM   cfg_dut() :
Configures the DUT configuration parameters.
AVM Switch TB
VMM Ethernet sample   start() :
Starts all the components of the verification environment to start component activity.
All the transactors (atomic_gen, senario_gen, vmm_xactor....) have start method,
Verilog which starts their activities. All the components start() methods are called in this
method.
Verification
Verilog Switch TB   wait_for_end() :
Basic Constructs This method waits till the test is done.

  stop() :
Stops all the components of the verification environment to terminate the simulation
OpenVera cleanly. Stop data generators.
Constructs
Switch TB   cleanup() :
Performs clean-up operations to let the simulation terminate gracefully.  It  waits for
RVM Switch TB DUT to drain all the data it has.
RVM Ethernet sample
  report() :
The report method in vmm_env collects error and warning metrics from all the log
objects and reports a summary of the results.
Specman E
Interview Questions To create a user environment, define a new class extended from vmm_env and extend
the above methods. To retain the core functionality of the base class methods, each
extended method must call super. as the first line of code.  

In The following example, we are defining a new class Custom_env from vmm_env and
extending all the vmm_env class methods. All the methods are extended and
`vmm_note() message is included to understand the simulation flow.

class Custom_env extends vmm_env;

http://testbench.in/VM_03_VMM_ENV.html[9/26/2012 2:24:38 PM]


WWW.TESTBENCH.IN - VMM Tutorial

  function new();
     super.new("Custom_env");
  endfunction

  virtual function void gen_cfg();
            super.gen_cfg();
            `vmm_note(this.log,"Start of gen_cfg() method ");
            `vmm_note(this.log,"End of gen_cfg() method ");
          endfunction

  virtual function void build();
            super.build();
            `vmm_note(this.log,"Start of build() method ");
            `vmm_note(this.log,"End of build() method ");
          endfunction

  virtual task reset_dut();
            super.reset_dut();
            `vmm_note(this.log,"Start of reset_dut() method ");
            `vmm_note(this.log,"End of reset_dut() method ");
          endtask

  virtual task cfg_dut();
            super.cfg_dut();
            `vmm_note(this.log,"Start of cfg_dut() method ");
            `vmm_note(this.log,"End of cfg_dut() method ");
          endtask

  virtual task start();
            super.start();
            `vmm_note(this.log,"Start of start() method ");
            `vmm_note(this.log,"End of start() method ");
          endtask

  virtual task wait_for_end();
            super.wait_for_end();
            `vmm_note(this.log,"Start of  wait_for_end() method ");
            `vmm_note(this.log,"End of  wait_for_end() method ");
          endtask

  virtual task stop();
            super.stop();
            `vmm_note(this.log,"Start of stop() method ");
            `vmm_note(this.log,"End of stop() method ");
          endtask

  virtual task cleanup();
            super.cleanup();
            `vmm_note(this.log,"Start of cleanup() method ");
            `vmm_note(this.log,"End of cleanup() method ");
          endtask

  virtual task report();
            super.report();
            `vmm_note(this.log,"Start of report() method \n\n\n");
            `vmm_note(this.log,"End of report() method");
          endtask

endclass

In addition to the methods that have already been discussed earlier, vmm_env also
contains a run() method which does not require any user extension. This method is
called from the testcase. When this method is called, individual steps in vmm_env are
called in a sequence in the following order:

gen_cfg => build => cfg_dut_t => start_t => wait_for_end_t => stop_t => cleanup_t =>

http://testbench.in/VM_03_VMM_ENV.html[9/26/2012 2:24:38 PM]


WWW.TESTBENCH.IN - VMM Tutorial

report

Now we will see the testcase implementation. VMM recommends the TestBench to be
implemented in program block. In a program block, create an object of the
Custom_env class and call the run() method.

program test();

   Custom_env env = new();


  
   initial
     env.run();

endprogram

Download the files

vmm_env_1.tar
Browse the code in vmm_env_1.tar

Simulation commands
vcs -sverilog -f filelist -R -ntb_opts rvm -ntb_opts dtm

Log file report:

Normal[NOTE] on Custom_env() at                    0:


    Start of gen_cfg() method
Normal[NOTE] on Custom_env() at                    0:
    End of gen_cfg() method
Normal[NOTE] on Custom_env() at                    0:
    Start of build() method
Normal[NOTE] on Custom_env() at                    0:
    End of build() method
Normal[NOTE] on Custom_env() at                    0:
    Start of reset_dut() method
Normal[NOTE] on Custom_env() at                    0:
    End of reset_dut() method
Normal[NOTE] on Custom_env() at                    0:
    Start of cfg_dut() method

http://testbench.in/VM_03_VMM_ENV.html[9/26/2012 2:24:38 PM]


WWW.TESTBENCH.IN - VMM Tutorial

Normal[NOTE] on Custom_env() at                    0:


    End of cfg_dut() method
Normal[NOTE] on Custom_env() at                    0:
    Start of start() method
Normal[NOTE] on Custom_env() at                    0:
    End of start() method
Normal[NOTE] on Custom_env() at                    0:
    Start of  wait_for_end() method
Normal[NOTE] on Custom_env() at                    0:
    End of  wait_for_end() method
Normal[NOTE] on Custom_env() at                    0:
    Start of stop() method
Normal[NOTE] on Custom_env() at                    0:
    End of stop() method
Normal[NOTE] on Custom_env() at                    0:
    Start of cleanup() method
Normal[NOTE] on Custom_env() at                    0:
    End of cleanup() method
Simulation PASSED on /./ (/./) at                    0 (0 warnings, 0 demoted errors & 0
demoted warnings)
Normal[NOTE] on Custom_env() at                    0:
    Start of report() method
    
    
    
Normal[NOTE] on Custom_env() at                    0:
    End of report() method
$finish at simulation time                    0

Log file report shows that individual methods in vmm_env are called in a ordered
sequence upon calling run() method.

When you call build() and if gen_cfg() is not called before that, gen_cfg() will be
called first then build will execute.

Same way, if you call gen_cfg() followed by cfg_dut() followed by run(), then
cfg_dut() will make sure to call build() followed by reset_dut() first before executing
its user defined logic, run() will make sure to call start(), wait_for_end(), stop(),
clean(), report()in the order given.

program test();

   vmm_env env = new();


  
   initial 
   begin
     $display("*************** Before Calling env.gen_cfg() ***************");
     env.gen_cfg();
     $display("*************** Before Calling env.cfg_dut() ***************");
     env.cfg_dut();
     $display("*************** Before Calling env.run()     ***************");
     env.run();
   end

endprogram

Download the files

vmm_env_2.tar
Browse the code in vmm_env_2.tar

Simulation commands
vcs -sverilog -f filelist -R -ntb_opts rvm -ntb_opts dtm +vmm_log_default=VERBOSE

Log file report:

http://testbench.in/VM_03_VMM_ENV.html[9/26/2012 2:24:38 PM]


WWW.TESTBENCH.IN - VMM Tutorial

*************** Before Calling env.gen_cfg() ***************


Trace[INTERNAL] on Verif Env() at                    0:
    Generating test configuration...
*************** Before Calling env.cfg_dut() ***************
Trace[INTERNAL] on Verif Env() at                    0:
    Building verification environment...
Trace[INTERNAL] on Verif Env() at                    0:
    Reseting DUT...
Trace[INTERNAL] on Verif Env() at                    0:
    Configuring...
*************** Before Calling env.run()     ***************
Trace[INTERNAL] on Verif Env() at                    0:
    Starting verification environment...
Trace[INTERNAL] on Verif Env() at                    0:
    Saving RNG state information...
Trace[INTERNAL] on Verif Env() at                    0:
    Waiting for end of test...
Trace[INTERNAL] on Verif Env() at                    0:
    Stopping verification environment...
Trace[INTERNAL] on Verif Env() at                    0:
    Cleaning up...
Simulation PASSED on /./ (/./) at                    0 (0 warnings, 0 demoted errors & 0
demoted warnings)

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/VM_03_VMM_ENV.html[9/26/2012 2:24:38 PM]


WWW.TESTBENCH.IN - VMM Tutorial

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS VMM DATA Index


Introduction
SystemVerilog Vmm Log
Verification vmm_data class is to be used to model all transactions in the infrastructure . It Vmm Env
provides a standard set of methods expected to be found in all transactions. All Vmm Data
Constructs transactions in the verification environment inherit this object and override its main Vmm Channel
Interface generic virtual tasks such as copy(), byte_pack(), byte_unpack(), compare() and Vmm Atomic Generator
psdisplay(). Vmm Xactor
OOPS Vmm Callback
Randomization vmm_data has 3 unique identifiers for identifying transaction instance. Vmm Test
Vmm Channel Record
Functional Coverage And Playback
int stream_id;  // Stream identifier
Assertion int scenario_id;// Sequence identifier within stream Vmm Scenario Generator
int data_id;    // instance identifier within sequence Vmm Opts
DPI
UVM Tutorial This class is used to generate random, constraint random and directed transactions. Report a Bug or Comment
on This section - Your
VMM Tutorial
We will see the implementation of some methods. input is what keeps
OVM Tutorial Testbench.in improving
Let us implement a simple packet using vmm_data. with time!
Easy Labs : SV
Easy Labs : UVM Packet Specification
Easy Labs : OVM -------------------------------
Packet has DA,SA,Len and ..... few more feilds.
Easy Labs : VMM All the feilds are 8 bit.
AVM Switch TB
1) Define a packet class by extending vmm_data
VMM Ethernet sample
   class Packet extends vmm_data;

Verilog 2) Define all the packet fields as rand variables


Verification
    rand bit [7:0] da;
Verilog Switch TB     rand bit [7:0] sa;
Basic Constructs     rand bit [7:0] length;
    ....
    ....
OpenVera 3) Constraint the rand variables based on the specification.
Constructs
Switch TB     constraint address_c { da inside {`P0,`P1,`P2,`P3} ; }
    ....
RVM Switch TB     .....
RVM Ethernet sample
4) Define psdisplay() method.
  
 psdisplay() method displays the current value of the transaction or data described by
Specman E this instance in a human-readable format on the standard output.
Interview Questions
    virtual function string psdisplay(string prefix = "");
         int i;
 
         $write(psdisplay, "   %s%s   da:0x%h\n", psdisplay, prefix,this.da);
         $write(psdisplay, "   %s%s   sa:0x%h\n", psdisplay, prefix,this.sa);
         $write(psdisplay, "   %s%s   length:0x%h
(data.size=%0d)\n", psdisplay, prefix,this.length,this.data.size());
         .........
          
    endfunction

http://testbench.in/VM_04_VMM_DATA.html[9/26/2012 2:24:48 PM]


WWW.TESTBENCH.IN - VMM Tutorial

5) Define copy() method.


 
 copy() method copies the current value of the object instance to the specified object
instance.

 
     virtual function vmm_data copy(vmm_data to = null);
         Packet cpy;
         cpy = new;
        
         super.copy_data(cpy);
        
         cpy.da = this.da;
         cpy.sa = this.sa;
         cpy.length = this.length;
         ...........

6) Define compare() method.

 Compare method compares the current value of the object instance with the current
value of the specified object instance.

    virtual function bit compare(input vmm_data   to,output string diff,input int  
kind = -1);
        Packet cmp;
    
        compare = 1; // Assume success by default.
        diff    = "No differences found";
        
        // data types are the same, do comparison:
        if (this.da != cmp.da) 
        begin
           diff = $psprintf("Different DA values: %b != %b", this.da, cmp.da);
           compare = 0;
        end 
          
        if (this.sa != cmp.sa) 
        begin
           diff = $psprintf("Different SA values: %b != %b", this.sa, cmp.sa);
           compare = 0;
        end 
        ........
        ........

7) Define byte_pack() method.

   byte_pack() method Packs the content of the transaction or data into the specified
dynamic array of bytes.

   virtual function int unsigned byte_pack(
                     ref logic [7:0] bytes[],
                     input int unsigned offset =0 ,
                     input int   kind = -1);
      byte_pack = 0;
      bytes = new[this.data.size() + 4];
      bytes[0] = this.da;
      bytes[1] = this.sa;
      bytes[2] = this.length;
      ........
      ........

8) Define byte_unpack() method.

   byte_unpack() method unpacket the array in to different data feilds.

    virtual function int unsigned byte_unpack(
                     const ref logic [7:0] bytes[],
                     input int unsigned offset = 0,

http://testbench.in/VM_04_VMM_DATA.html[9/26/2012 2:24:48 PM]


WWW.TESTBENCH.IN - VMM Tutorial

                     input int len = -1,
                     input int kind = -1);
      this.da = bytes[0];
      this.sa = bytes[1];
      this.length = bytes[2];
      .........
      .........

Complete Packet Class

class Packet extends vmm_data;

static vmm_log log = new("Packet","Class");

rand bit [7:0] length;
rand bit [7:0] da;
rand bit [7:0] sa;
rand bit [7:0] data[];//Payload using Dynamic array,size is generated on the fly
rand byte fcs;

constraint payload_size_c { data.size inside { [1 : 6]};}

function new();
     super.new(this.log);
endfunction:new

virtual function vmm_data allocate();
     Packet pkt;
     pkt = new();
     return pkt;
endfunction:allocate

virtual function string psdisplay(string prefix = "");
    int i;
 
    $write(psdisplay, "   %s   packet
#%0d.%0d.%0d\n", prefix,this.stream_id, this.scenario_id, this.data_id);
    $write(psdisplay, "   %s%s   da:0x%h\n", psdisplay, prefix,this.da);
    $write(psdisplay, "   %s%s   sa:0x%h\n", psdisplay, prefix,this.sa);
    $write(psdisplay, "   %s%s   length:0x%h
(data.size=%0d)\n", psdisplay, prefix,this.length,this.data.size());
    $write(psdisplay, "   %s%s   data[%0d]:0x%h", psdisplay, prefix,0,data[0]);
    if(data.size() > 1)
        $write(psdisplay, "   data[%0d]:0x%h", 1,data[1]);
    if(data.size() > 4)
        $write(psdisplay, "  ....  ");
    if(data.size() > 2)
        $write(psdisplay, "   data[%0d]:0x%h", data.size() -2,data[data.size() -2]);
    if(data.size() > 3)
        $write(psdisplay, "   data[%0d]:0x%h", data.size() -1,data[data.size() -1]);
    $write(psdisplay, "\n   %s%s   fcs:0x%h \n", psdisplay, prefix, this.fcs);
    
 endfunction
 
 
virtual function vmm_data copy(vmm_data to = null);
    Packet cpy;
 
    // Copying to a new instance?
    if (to == null) 
       cpy = new;
     else
 
    // Copying to an existing instance. Correct type?
    if (!$cast(cpy, to))    
       begin
       `vmm_fatal(this.log, "Attempting to copy to a non packet instance");
       copy = null;
       return copy;
       end
    

http://testbench.in/VM_04_VMM_DATA.html[9/26/2012 2:24:48 PM]


WWW.TESTBENCH.IN - VMM Tutorial

 
    super.copy_data(cpy);
    
    cpy.da = this.da;
    cpy.sa = this.sa;
    cpy.length = this.length;
    cpy.data = new[this.data.size()];
    foreach(data[i])
        begin
       cpy.data[i] = this.data[i];
        end                    
    cpy.fcs = this.fcs;
    copy = cpy;
 endfunction:copy
 
 
 
virtual function bit compare(input vmm_data   to,output string diff,input int   kind
= -1);
    Packet cmp;
 
    compare = 1; // Assume success by default.
    diff    = "No differences found";
    
    if (!$cast(cmp, to)) 
    begin
       `vmm_fatal(this.log, "Attempting to compare to a non packet instance");
       compare = 0;
       diff = "Cannot compare non packets";
       return compare;
     end 
 
    // data types are the same, do comparison:
    if (this.da != cmp.da) 
    begin
       diff = $psprintf("Different DA values: %b != %b", this.da, cmp.da);
       compare = 0;
       return compare;
    end 
      
    if (this.sa != cmp.sa) 
    begin
       diff = $psprintf("Different SA values: %b != %b", this.sa, cmp.sa);
       compare = 0;
       return compare;
    end 
    if (this.length != cmp.length) 
    begin
       diff = $psprintf("Different LEN values: %b != %b", this.length, cmp.length);
       compare = 0;
       return compare;
    end 
 
    foreach(data[i]) 
       if (this.data[i] != cmp.data[i]) 
       begin
          diff = $psprintf("Different data[%0d] values: 0x%h !=
0x%h",i, this.data[i], cmp.data[i]);
          compare = 0;
          return compare;
       end 
    if (this.fcs != cmp.fcs) 
    begin
       diff = $psprintf("Different FCS values: %b != %b", this.fcs, cmp.fcs);
       compare = 0;
       return compare;
    end 
 endfunction:compare

virtual function int unsigned byte_pack(
                     ref logic [7:0] bytes[],
                     input int unsigned offset =0 ,
                     input int   kind = -1);
      byte_pack = 0;

http://testbench.in/VM_04_VMM_DATA.html[9/26/2012 2:24:48 PM]


WWW.TESTBENCH.IN - VMM Tutorial

      bytes = new[this.data.size() + 4];
      bytes[0] = this.da;
      bytes[1] = this.sa;
      bytes[2] = this.length;

      foreach(data[i])
          bytes[3+i] = data[i];

      bytes[this.data.size() + 3 ] = fcs;
      byte_pack = this.data.size() + 4;
endfunction:byte_pack    

virtual function int unsigned byte_unpack(
                     const ref logic [7:0] bytes[],
                     input int unsigned offset = 0,
                     input int len = -1,
                     input int kind = -1);
      this.da = bytes[0];
      this.sa = bytes[1];
      this.length = bytes[2];
      this.fcs = bytes[bytes.size() -1];
      this.data = new[bytes.size() - 4];
      foreach(data[i])
      this.data[i] = bytes[i+3];
      return bytes.size();
endfunction:byte_unpack

endclass

Vmm_data Methods
 
      virtual function string psdisplay ( string prefix = "" );
      virtual function bit is_valid ( bit silent = 1, int kind = -1 );
      virtual function vmm_data allocate ( );
      virtual function vmm_data copy ( vmm_data to = null );
      virtual function bit compare (
      input vmm_data to, output string diff, input int kind = -1 );
      function void display(string prefix = "");
      virtual protected function void copy_data ( vmm_data to );
      virtual function int unsigned byte_pack (
      ref logic [7:0] bytes [ ], int unsigned offset = 0, int kind = -1 );
      virtual function int unsigned byte_unpack (
      const ref logic [7:0] bytes [ ], input int unsigned offset = 0,
      input int len = -1, input int kind = -1 );
      virtual function int unsigned byte_size ( int kind = -1 );
      virtual function int unsigned max_byte_size ( int kind = -1 );
      virtual function void save ( int file );
      virtual function bit load ( int file ); 

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/VM_04_VMM_DATA.html[9/26/2012 2:24:48 PM]


WWW.TESTBENCH.IN - VMM Tutorial

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS VMM CHANNEL Index


Introduction
SystemVerilog Vmm Log
Verification The channel is the interface mechanism used by transactors to transfer transactions. Vmm Env
Transaction objects are produced or consumed by a transactor. Transactor can be a Vmm Data
Constructs generator or a driver or a scoreboard. In Transaction-level modeling multiple Vmm Channel
Interface processes communicate with each other by sending transactions through channels. For Vmm Atomic Generator
example, to transfer a transaction from generator to a driver, we don't need to send Vmm Xactor
OOPS Vmm Callback
at signal level. To transfer a transaction from Driver to DUT, physical signals are used.
Randomization The channel transfers transactions between the verification components, and it serves Vmm Test
as a synchronizing agent between them. Vmm Channel Record
Functional Coverage And Playback
Assertion Vmm Scenario Generator
Vmm Opts
DPI
UVM Tutorial Report a Bug or Comment
on This section - Your
VMM Tutorial
input is what keeps
OVM Tutorial Testbench.in improving
with time!
Easy Labs : SV
Easy Labs : UVM
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

Verilog Channels are similar to SystemVerilog mailboxes with advanced features. Vmm
Channels provides much richer feature functionality than a SV mailbox. vmm channels
Verification
are superset of mailboxs.  
Verilog Switch TB Some of the the benefits of channels over mailboxes:
Basic Constructs Dynamic reconfiguration
Inbuilt notifications
Strict type checking
OpenVera Out of order usage
Constructs task tee() for easy scoreboarding
Record and playback
Switch TB task sneak() for monitors
RVM Switch TB
RVM Ethernet sample
 Using `vmm_channel() macro , channels can be created.  

    `vmm_channel(Custom_vmm_data)  
Specman E
The above macro creates a channel Custom_vmm_data_channel . There are various
Interview Questions
methods to access the channels.

In the following example, we will see


1) Channel creation using macros.
2) Constructing a channel.
3) Pushing a transaction in to channel.
4) Popping out a transaction from the channel.

We will create a channel for vmm_data for this example. Users can create a channel
for any transaction which is derived from the vmm_data class. You can try this

http://testbench.in/VM_05_VMM_CHANNEL.html[9/26/2012 2:24:58 PM]


WWW.TESTBENCH.IN - VMM Tutorial

example by creating channel for Packet class which is discussed in previous section.

1) Define a channel using macro

    `vmm_channel(vmm_data)

2) Construct an object of channel which is defined by the above macro.

     vmm_data_channel p_c =  new("p_c","chan",10);

3) Push a packet p_put in to p_c channel.

     p_c.put(p_put); 

4) Get a packet from p_c channel.

     p_c.get(p_put); 

Complete Example

`vmm_channel(vmm_data)

program test_channel();
  vmm_data p_put,p_get;

  vmm_data_channel p_c =  new("p_c","chan",10);

  int i;

  initial
     repeat(10)
         begin
             #( $urandom()%10);
             p_put = new(null);
             p_put.stream_id = i++;
             $display(" Pushed a packet in to channel with id %d",p_put.stream_id);
             p_c.put(p_put); // Pushing a transaction in to channel
         end    

   initial 
      forever 
         begin
         p_c.get(p_get); // popping a transaction from channel.
         $display(" Popped a packet from channel with id %d",p_get.stream_id);
         end 
endprogram 

Download the file

vmm_channel.tar
Browse the code in vmm_channel.tar

Command to run the simulation


vcs -sverilog -f filelist -R -ntb_opts rvm -ntb_opts dtm
Log report

 Pushed a packet in to channel with id           0


 Popped a packet from channel with id           0
 Pushed a packet in to channel with id           1
 Popped a packet from channel with id           1
 Pushed a packet in to channel with id           2
 Popped a packet from channel with id           2
 Pushed a packet in to channel with id           3
 Popped a packet from channel with id           3
 Pushed a packet in to channel with id           4

http://testbench.in/VM_05_VMM_CHANNEL.html[9/26/2012 2:24:58 PM]


WWW.TESTBENCH.IN - VMM Tutorial

 Popped a packet from channel with id           4


 Pushed a packet in to channel with id           5
 Popped a packet from channel with id           5
 Pushed a packet in to channel with id           6
 Popped a packet from channel with id           6
 Pushed a packet in to channel with id           7
 Popped a packet from channel with id           7
 Pushed a packet in to channel with id           8
 Popped a packet from channel with id           8
 Pushed a packet in to channel with id           9
 Popped a packet from channel with id           9

Vmm Channel Methods.

function new ( string name, string instance,
int unsigned full = 1, int unsigned empty = 0, bit fill_as_bytes = 0 );
function void reconfigure (int full = -1, int empty = -1, logic fill_as_bytes = 1'bx );
function int unsigned full_level ( );
function int unsigned empty_level ( );
function int unsigned level ( );
function int unsigned size ( );
function bit is_full ( );
function void flush ( );
function void sink ( );
function void flow ( );
function void lock ( bit [1:0] who );
function void unlock ( bit [1:0] who );
function bit is_locked ( bit [1:0] who );
task put ( class_name obj, int offset = -1 );
function void sneak ( class_name obj, int offset = -1 );
function class_name unput ( int offset = -1 );
task get ( output class_name obj, input int offset = 0 );
task peek ( output class_name obj, input int offset = 0 );
task activate ( output class_name obj, input int offset = 0 );
function class_name active_slot ( );
function class_name start ( );
function class_name complete ( vmm_data status = null );
function class_name remove ( );
function active_status_e status ( );
task tee ( output class_name obj );
function bit tee_mode ( bit is_on );
function void connect ( vmm_channel downstream );
function class_name for_each ( bit reset = 0 );
function int unsigned for_each_offset ( );
function bit record ( string filename );
task bit playback ( output bit success, input string filename,
input vmm_data loader, input bit metered = 0 );

Refer to VMM book for details of each method.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/VM_05_VMM_CHANNEL.html[9/26/2012 2:24:58 PM]


WWW.TESTBENCH.IN - VMM Tutorial

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS VMM ATOMIC GENERATOR Index


Introduction
SystemVerilog Vmm Log
Verification VMM has two types of generators. Atomic generator and Scenario generator. Vmm Env
Vmm Data
Constructs Atomic generator is a simple generator which generates transactions randomly. Vmm Channel
Interface Vmm Atomic Generator
`vmm_atomic_gen is a macro which is used to define a class named Vmm Xactor
OOPS
<class_name>_atomic_gen for any user-specified class derived from vmm_data, using Vmm Callback
Randomization a process similar to the `vmm_channel macro. Vmm Test
Vmm Channel Record
Functional Coverage And Playback
Assertion Vmm Scenario Generator
Vmm Opts
DPI
UVM Tutorial Report a Bug or Comment
on This section - Your
VMM Tutorial
input is what keeps
OVM Tutorial Testbench.in improving
with time!
Easy Labs : SV
Easy Labs : UVM
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

 
To use <class_name>_atomic_gen class, a <class_name>_channel must exist.
Verilog <class_name>_atomic_gen generates transactions and pushes it to
Verification <class_name>_channel. A <class_name>_channel object can be passed to generator
Verilog Switch TB while constructing.

Basic Constructs function new(string instance,


            int stream_id = -1,
            <class_name>_channel out_chan = null);
OpenVera
Constructs
The generator will stop generating the transaction after generating
Switch TB stop_after_n_insts.  User can set the stop_after_n_insts to any unsigned int value. By
default this values is 0.
RVM Switch TB
RVM Ethernet sample If stop_after_n_insts is 0, then generator generates infinite number of transactions.
If stop_after_n_insts is non zero positive number, then generator generates
stop_after_n_insts transactions.
Specman E
We will see an example of creating a atomic generator for a packet class. Packet class
Interview Questions is in file Packet.sv .

1) define `vmm_atomic_gen macro for packet class. This macro creates a


packet_atomic_gen class creates and randomizes packet transactions.

    `vmm_atomic_gen(packet,"packet atomic generator")

2) define `vmm_channel for the packet class. This macro creates a packet_channel
which will be used by the packet_atomic_gen to store the transactions. Any other
component can take the transactions from this channel.

http://testbench.in/VM_06_VMM_ATOMIC_GENERATOR.html[9/26/2012 2:25:08 PM]


WWW.TESTBENCH.IN - VMM Tutorial

     `vmm_channel(packet)

3) Create an object of pcakt_atomic_gen.

    packet_atomic_gen pkt_gen = new("Atomic Gen","test"); 

4) Set the number of transactions to be generated to 4

    pkt_gen.stop_after_n_insts = 4;

5) Start the generator to generate transactions. These transactions are available to


access through pkt_chan as soon as they are generated.

    pkt_gen.start_xator(); 

6) Collect the packets from the pkt_chan and display the packet content to terminal.

    pkt_gen.out_chan.get(pkt);
    pkt.display();

Completed Example

`vmm_channel(Packet)
`vmm_atomic_gen(Packet,"Atomic Packet Generator")

program test_atomic_gen();
  
  Packet_atomic_gen pkt_gen = new("Atomic Gen","test"); 
  Packet pkt;
    initial
       begin 
          pkt_gen.stop_after_n_insts = 4;
          #100; pkt_gen.start_xactor();
       end

    initial
       #200 forever
            begin
                pkt_gen.out_chan.get(pkt);
                pkt.display();
            end
    
endprogram 

Download the example

vmm_atomic_gen.tar
Browse the code in vmm_atomic_gen.tar

Commands to run the simulation


vcs -sverilog -f filelist -R -ntb_opts rvm -ntb_opts dtm

Log file report

      packet #1952805748.0.0
      da:0xdb
      sa:0x71
      length:0x0e (data.size=1)
      data[0]:0x63
      fcs:0xe9

      packet #1952805748.0.1
      da:0xa7
      sa:0x45
      length:0xa4 (data.size=5)
      data[0]:0x00   data[1]:0x4f  ....     data[3]:0xe7   data[4]:0xd8
      fcs:0x31

http://testbench.in/VM_06_VMM_ATOMIC_GENERATOR.html[9/26/2012 2:25:08 PM]


WWW.TESTBENCH.IN - VMM Tutorial

      packet #1952805748.0.2
      da:0x15
      sa:0xe6
      length:0xa1 (data.size=1)
      data[0]:0x80
      fcs:0x01

      packet #1952805748.0.3
      da:0xd7
      sa:0xa9
      length:0xdc (data.size=3)
      data[0]:0xcc   data[1]:0x7c   data[1]:0x7c
      fcs:0x67

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/VM_06_VMM_ATOMIC_GENERATOR.html[9/26/2012 2:25:08 PM]


WWW.TESTBENCH.IN - VMM Tutorial

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS VMM XACTOR Index


Introduction
SystemVerilog Vmm Log
Verification Vmm Env
This base class is to be used as the basis for all transactors, including bus-functional Vmm Data
Constructs models, monitors and generators. It provides a standard control mechanism expected Vmm Channel
Interface to be found in all transactors. Vmm Atomic Generator
Vmm Xactor
OOPS Vmm Callback
virtual function void start_xactor();
Randomization Starts the execution threads in this transactor instance. This method is called by Vmm Test
Environment class which is extended from vmm_env start() method. Vmm Channel Record
Functional Coverage And Playback
Assertion Vmm Scenario Generator
virtual function void stop_xactor(); Vmm Opts
DPI Stops the execution threads in this transactor instance. This method is called by
Environment class which is extended from vmm_env stop() method.
UVM Tutorial Report a Bug or Comment
on This section - Your
VMM Tutorial protected task wait_if_stopped() input is what keeps
OVM Tutorial protected task wait_if_stopped_or_empty(vmm_channel chan) Testbench.in improving
Blocks the thread execution if the transactor has been stopped via the stop_xactor() with time!
Easy Labs : SV method or if the specified input channel is currently empty.
Easy Labs : UVM
protected virtual task main();
Easy Labs : OVM This task is forked off whenever the start_xactor() method is called. It is terminated
Easy Labs : VMM whenever the reset_xactor() method is called. The functionality of a user-defined
transactor must be implemented in this method.
AVM Switch TB
VMM Ethernet sample Let us see an example of using vmm_xactor.
1) Extend vmm_xactor to create a custom_xtor.

class Driver extends vmm_xactor;
Verilog
Verification 2) Define constructor. In this example, we don't have any interfaces of channels, we
Verilog Switch TB will not implement them.
   Call the super.new() method.
Basic Constructs
function new();
   super.new("Driver Transactor", "inst", 0);
OpenVera endfunction: new
Constructs
3) Define main() method.
Switch TB
RVM Switch TB    First call the super.main() method.
   Then define the activity which you want to do.
RVM Ethernet sample
task main();
   super.main();
Specman E
   forever begin
Interview Questions         #100;
        $display(" Driver : %d",$time);
   end
endtask: main

Now we will see how to use the above defined Custom_xtor class.
 1) Create a object of Custom_xtor.

    Driver drvr = new();

http://testbench.in/VM_07_VMM_XACTOR.html[9/26/2012 2:25:17 PM]


WWW.TESTBENCH.IN - VMM Tutorial

 2) Call the start_xactor() methods of Custom_xtor object.


    Now the main() method which is defined starts gets executed.

  #100 drvr.start_xactor();

 3) Call the stop_xactor() methos.


    This will stop the execution of main() method.

       #1000 drvr.stop_xactor();

Complete Vmm_xactor Example

class Driver extends vmm_xactor;

function new();
   super.new("Driver Transactor", "inst", 0);
endfunction: new

task main();
   super.main();

   forever begin
        #100;
        $display(" Driver : %d",$time);
   end
endtask: main

endclass:Driver

program test();

  Driver drvr = new();


  
  initial
     fork
      #100 drvr.start_xactor();
      #1000 drvr.stop_xactor();
     join
endprogram

Download the files

vmm_xactor.tar
Browse the code in vmm_xactor.tar

Command to run the simulation


vcs -sverilog -f filelist -R -ntb_opts rvm -ntb_opts dtm

Log file report

 Driver :                  200
 Driver :                  300
 Driver :                  400
 Driver :                  500
 Driver :                  600
 Driver :                  700
 Driver :                  800
 Driver :                  900
 Driver :                 1000
$finish at simulation time                 1000

Vmm_xactor Members

function new ( string name, string instance, int stream_id = -1 );
virtual function string get_name ( );
virtual function string get_instance ( );

http://testbench.in/VM_07_VMM_XACTOR.html[9/26/2012 2:25:17 PM]


WWW.TESTBENCH.IN - VMM Tutorial

vmm_log log;
int stream_id;
virtual function void prepend_callback ( vmm_xactor_callbacks cb );
virtual function void append_callback ( vmm_xactor_callbacks cb );
virtual function void unregister_callback ( vmm_xactor_callbacks cb );
vmm_notify notify;
// Enumeration values for the state of the transactor:
enum { XACTOR_IDLE, XACTOR_BUSY,
XACTOR_STARTED, XACTOR_STOPPED, XACTOR_RESET };
virtual function void start_xactor ( );
virtual function void stop_xactor ( );
virtual function void reset_xactor ( reset_e rst_typ = SOFT_RST );
protected task wait_if_stopped ( );
protected task wait_if_stopped_or_empty ( vmm_channel chan );
protected virtual task main ( );
virtual function void save_rng_state ( );
virtual function void restore_rng_state ( );
virtual function void xactor_status ( string prefix = "" );
// Macro to simplify the calling of callback methods:
`vmm_callback ( callback_class_name, method ( args ) )

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/VM_07_VMM_XACTOR.html[9/26/2012 2:25:17 PM]


WWW.TESTBENCH.IN - VMM Tutorial

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS VMM CALLBACK Index


Introduction
SystemVerilog Callback mechanism is used for altering the behavior of the transactor without Vmm Log
Verification modifying the transactor. One of the many promises of Object-Oriented programming Vmm Env
is that it will allow for plug-and-play re-usable verification components. Verification Vmm Data
Constructs Designers will hook the transactors together to make a verification environment. In Vmm Channel
Interface SystemVerilog, this hooking together of transactors can be tricky. Callbacks provide a Vmm Atomic Generator
mechanism whereby independently developed objects may be connected together in Vmm Xactor
OOPS Vmm Callback
simple steps.
Randomization Vmm Test
This article describes vmm callbacks. Vmm callback might be used for simple Vmm Channel Record
Functional Coverage And Playback
notification, two-way communication, or to distribute work in a process. Some
Assertion requirements are often unpredictable when the transactor is first written. So a Vmm Scenario Generator
transactor should provide some kind of hooks for executing the code which is defined Vmm Opts
DPI
afterwards. In vmm, these hooks are created using callback methods. For instance, a
UVM Tutorial driver is developed and an empty method is called before driving the transaction to Report a Bug or Comment
the DUT. Initially this empty method does nothing. As the implementation goes, user on This section - Your
VMM Tutorial
may realize that he needs to print the state of the transaction or to delay the input is what keeps
OVM Tutorial transaction driving to DUT or inject an error into transaction. Callback mechanism Testbench.in improving
allows executing the user defined code in place of the empty callback method.  Other with time!
Easy Labs : SV
example of callback usage is in monitor. Callbacks can be used in a monitor for
Easy Labs : UVM collecting coverage information or for hooking up to scoreboard to pass transactions
Easy Labs : OVM for self checking. With this, user is able to control the behavior of the transactor in
verification environment and individual testcases without doing any modifications to
Easy Labs : VMM the transactor itself.  
AVM Switch TB
Following are the steps to be followed to create a transactor with callbacks. We will
VMM Ethernet sample see simple example of creating a Driver transactor to support callback mechanism.

1) Define a facade class.


Verilog    Extend the vmm_xactor_callbacks class to create a faced class.
Verification    Define required callback methods. All the callback methods must be virtual.
   In this example, we will create callback methods which will be called before driving
Verilog Switch TB the packet and after driving the packet to DUT.
Basic Constructs
class Driver_callbacks extends vmm_xactor_callbacks;

  virtual task pre_send(); endtask
OpenVera   virtual task post_send(); endtask
Constructs
Switch TB endclass 
RVM Switch TB 2) Calling callback method.
RVM Ethernet sample    Inside the transactor, callback methods should be called whenever something
interesting happens.
   We will call the callback method before driving the packet and after driving the
packet. We defined 2 methods in facade class. We will call pre_send() method before
Specman E sending the packet and post_send() method after sending the packet.
Interview Questions
   Using a `vmm_callback(,) macro, callback methods are called.
   There are 2 argumentd to `vmm_callback(,) macro.
   First argument must be the facade class.
   Second argument must be the callback method in the facade class.
 
   To call pre_send() method , use macro
   `vmm_callback(Driver_callbacks,pre_send());
   and simillary to call post_send() method,
   `vmm_callback(Driver_callbacks,post_send());

http://testbench.in/VM_08_VMM_CALLBACK.html[9/26/2012 2:25:28 PM]


WWW.TESTBENCH.IN - VMM Tutorial

   Place the above macros before and after driving the packet.

    virtual task main();
   super.main();
    
     forever begin 
        `vmm_callback(Driver_callbacks,pre_send());
         $display(" Driver: Started Driving the packet ...... %d",$time);  
         // Logic to drive the packet goes hear
         // let's consider that it takes 40 time units to drive a packet.
         #40; 
         $display(" Driver: Finished Driving the packet ...... %d",$time);  
        `vmm_callback(Driver_callbacks,post_send());
     end
   endtask

   With this, the Driver implementation is completed with callback support.

Complete Source Code


  
class Driver_callbacks extends vmm_xactor_callbacks;

  virtual task pre_send(); endtask
  virtual task post_send(); endtask

endclass 

class Driver extends vmm_xactor;

 function new();
   super.new("Driver","class");
 endfunction
 
 virtual task main();
   super.main();
    
     forever begin 
        `vmm_callback(Driver_callbacks,pre_send());
         $display(" Driver: Started Driving the packet ...... %d",$time);  
         // Logic to drive the packet goes hear
         // let's consider that it takes 40 time units to drive a packet.
         #40; 
         $display(" Driver: Finished Driving the packet ...... %d",$time);  
        `vmm_callback(Driver_callbacks,post_send());
     end
  endtask

endclass

Let's run the driver in simple testcase. In this testcase, we are not changing any
callback methods definitions.

Testcase 1 Source Code

 program testing_callbacks();
   Driver drvr =  new();
  initial
    begin
    #100 drvr.start_xactor();
    #200 drvr.stop_xactor();
    end
  endprogram

Download files

http://testbench.in/VM_08_VMM_CALLBACK.html[9/26/2012 2:25:28 PM]


WWW.TESTBENCH.IN - VMM Tutorial

vmm_callback.tar
Browse the code in vmm_callback.tar

Command to run the simulation


vcs -sverilog -f filelist -R -ntb_opts rvm -ntb_opts dtm

Log report

 Driver: Started Driving the packet ......                  100


 Driver: Finished Driving the packet ......                  140
 Driver: Started Driving the packet ......                  140
 Driver: Finished Driving the packet ......                  180
 Driver: Started Driving the packet ......                  180
 Driver: Finished Driving the packet ......                  220
 Driver: Started Driving the packet ......                  220
 Driver: Finished Driving the packet ......                  260
 Driver: Started Driving the packet ......                  260
 Driver: Finished Driving the packet ......                  300
 Driver: Started Driving the packet ......                  300
$finish at simulation time                  300

Following steps are to be performed for using callback mechanism to do required


functionality.
We will see how to use the callbacks which are implemented in the above defined
driver in a testcase.

1) Implement the user defined callback method by extending facade class of the
driver class.
   We will delay the driving of packet be 20 time units using the pre_send() call back
method.
   We will just print a message from post_send() callback method.

     class Custom_Driver_callbacks_1 extends Driver_callbacks;


  
     virtual task pre_send();
       $display("CB_1:pre_send: Delaying the packet driving by 20 time units.
%d",$time);
       #20;
     endtask
  
     virtual task post_send();
      $display("CB_1:post_send: Just a message from  post send callback method \n");
     endtask

2) Construct the user defined facade class object.

     Custom_Driver_callbacks CDc = new();

3) Register the callback method. vmm_xactor class has append_callback() which is


used to register the callback.

   drvr.append_callback(CDc_1);

Testcase 2 Source Code

   program testing_callbacks();
   Driver drvr =  new();

   class Custom_Driver_callbacks_1 extends Driver_callbacks;
  
     virtual task pre_send();
       $display("CB_1:pre_send: Delaying the packet driving by 20 time units.
%d",$time);
       #20;
     endtask
  
     virtual task post_send();
      $display("CB_1:post_send: Just a message from  post send callback method \n");
     endtask
 

http://testbench.in/VM_08_VMM_CALLBACK.html[9/26/2012 2:25:28 PM]


WWW.TESTBENCH.IN - VMM Tutorial

   endclass 

   Custom_Driver_callbacks_1 CDc_1 = new();


  initial
    begin
    drvr.append_callback(CDc_1);
    #100 drvr.start_xactor();
    #200 drvr.stop_xactor();
    end
  endprogram

Download the example

vmm_callback_1.tar
Browse the code in vmm_callback_1.tar

Simulation Command
vcs -sverilog -f filelist -R -ntb_opts rvm -ntb_opts dtm

  Run the testcase. See the log results; We delayed the driving of packet by 20 time
units using callback mechanism. See the difference between the previous testcase log
and this log.

Log report

CB_1:pre_send: Delaying the packet driving by 20 time units.                  100


 Driver: Started Driving the packet ......                  120
 Driver: Finished Driving the packet ......                  160
CB_1:post_send: Just a message from  post send callback method

CB_1:pre_send: Delaying the packet driving by 20 time units.                  160


 Driver: Started Driving the packet ......                  180
 Driver: Finished Driving the packet ......                  220
CB_1:post_send: Just a message from  post send callback method

CB_1:pre_send: Delaying the packet driving by 20 time units.                  220


 Driver: Started Driving the packet ......                  240
 Driver: Finished Driving the packet ......                  280
CB_1:post_send: Just a message from  post send callback method

CB_1:pre_send: Delaying the packet driving by 20 time units.                  280


 Driver: Started Driving the packet ......                  300
$finish at simulation time                  300

  

Now we will see registering 2 callback methods.


   1) Define another user defined callback methods by extending facade class.

     class Custom_Driver_callbacks_2 extends Driver_callbacks;


  
     virtual task pre_send();
       $display("CB_2:pre_send: Hai .... this is from Second callback %d",$time);
     endtask
  
    endclass 

   2) Construct the user defined facade class object.

      Custom_Driver_callbacks_2 CDc_2 = new();

   3) Register the object

      drvr.append_callback(CDc_2);

Testcase 3 Source Code


    
  program testing_callbacks();
   Driver drvr =  new();

   class Custom_Driver_callbacks_1 extends Driver_callbacks;
  

http://testbench.in/VM_08_VMM_CALLBACK.html[9/26/2012 2:25:28 PM]


WWW.TESTBENCH.IN - VMM Tutorial

     virtual task pre_send();
       $display("CB_1:pre_send: Delaying the packet driving by 20 time units.
%d",$time);
       #20;
     endtask
  
     virtual task post_send();
      $display("CB_1:post_send: Just a message from  post send callback method \n");
     endtask
 
   endclass 

   class Custom_Driver_callbacks_2 extends Driver_callbacks;
  
     virtual task pre_send();
       $display("CB_2:pre_send: Hai .... this is from Second callback %d",$time);
     endtask
  
 
   endclass 

   Custom_Driver_callbacks_1 CDc_1 = new();


   Custom_Driver_callbacks_2 CDc_2 = new();
  initial
    begin
    drvr.append_callback(CDc_1);
    drvr.append_callback(CDc_2);
    #100 drvr.start_xactor();
    #200 drvr.stop_xactor();
    end
  endprogram

Download source code

vmm_callback_2.tar
Browse the code in vmm_callback_2.tar

Command to run the simulation


vcs -sverilog -f filelist -R -ntb_opts rvm -ntb_opts dtm

 Run the testcase and analyze the result.

Log report

CB_1:pre_send: Delaying the packet driving by 20 time units.                  100


CB_2:pre_send: Hai .... this is from Second callback                  120
 Driver: Started Driving the packet ......                  120
 Driver: Finished Driving the packet ......                  160
CB_1:post_send: Just a message from  post send callback method

CB_1:pre_send: Delaying the packet driving by 20 time units.                  160


CB_2:pre_send: Hai .... this is from Second callback                  180
 Driver: Started Driving the packet ......                  180
 Driver: Finished Driving the packet ......                  220
CB_1:post_send: Just a message from  post send callback method

CB_1:pre_send: Delaying the packet driving by 20 time units.                  220


CB_2:pre_send: Hai .... this is from Second callback                  240
 Driver: Started Driving the packet ......                  240
 Driver: Finished Driving the packet ......                  280
CB_1:post_send: Just a message from  post send callback method

CB_1:pre_send: Delaying the packet driving by 20 time units.                  280


CB_2:pre_send: Hai .... this is from Second callback                  300
 Driver: Started Driving the packet ......                  300
$finish at simulation time                  300

 The log results show that pre_send() method of CDc_1 is called first and then
pre_send() method of Cdc_2. This is beacuse of the order of the registering callbacks.

    drvr.append_callback(CDc_1);

http://testbench.in/VM_08_VMM_CALLBACK.html[9/26/2012 2:25:28 PM]


WWW.TESTBENCH.IN - VMM Tutorial

    drvr.append_callback(CDc_2);

Now we will see how to change the order of the callback method calls.
Use prepend_callback() method for registering instead of append_callback() method.

Testcase 4 Source Code

 program testing_callbacks();
   Driver drvr =  new();

   class Custom_Driver_callbacks_1 extends Driver_callbacks;
  
     virtual task pre_send();
       $display("CB_1:pre_send: Delaying the packet driving by 20 time units.
%d",$time);
       #20;
     endtask
  
     virtual task post_send();
      $display("CB_1:post_send: Just a message from  post send callback method \n");
     endtask
 
   endclass 

   class Custom_Driver_callbacks_2 extends Driver_callbacks;
  
     virtual task pre_send();
       $display("CB_2:pre_send: Hai .... this is from Second callback %d",$time);
     endtask
  
 
   endclass 

   Custom_Driver_callbacks_1 CDc_1 = new();


   Custom_Driver_callbacks_2 CDc_2 = new();
  initial
    begin
    drvr.append_callback(CDc_1);
    drvr.prepend_callback(CDc_2);
    #100 drvr.start_xactor();
    #200 drvr.stop_xactor();
    end
  endprogram

Download the source code

vmm_callback_3.tar
Browse the code in vmm_callback_3.tar

Command to run the simulation


vcs -sverilog -f filelist -R -ntb_opts rvm -ntb_opts dtm

Run and analyze the results.


Log results show that, pre_send() method of CDs_1 is called after calling CDs_2
pre_send() method.

Log file report

CB_2:pre_send: Hai .... this is from Second callback                  100


CB_1:pre_send: Delaying the packet driving by 20 time units.                  100
 Driver: Started Driving the packet ......                  120
 Driver: Finished Driving the packet ......                  160
CB_1:post_send: Just a message from  post send callback method

CB_2:pre_send: Hai .... this is from Second callback                  160


CB_1:pre_send: Delaying the packet driving by 20 time units.                  160
 Driver: Started Driving the packet ......                  180
 Driver: Finished Driving the packet ......                  220
CB_1:post_send: Just a message from  post send callback method

CB_2:pre_send: Hai .... this is from Second callback                  220


CB_1:pre_send: Delaying the packet driving by 20 time units.                  220

http://testbench.in/VM_08_VMM_CALLBACK.html[9/26/2012 2:25:28 PM]


WWW.TESTBENCH.IN - VMM Tutorial

 Driver: Started Driving the packet ......                  240


 Driver: Finished Driving the packet ......                  280
CB_1:post_send: Just a message from  post send callback method

CB_2:pre_send: Hai .... this is from Second callback                  280


CB_1:pre_send: Delaying the packet driving by 20 time units.                  280
 Driver: Started Driving the packet ......                  300
$finish at simulation time                  300

Vmm also provides method to remove the callback methods which are registered.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/VM_08_VMM_CALLBACK.html[9/26/2012 2:25:28 PM]


WWW.TESTBENCH.IN - VMM Tutorial

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS VMM TEST Index


Introduction
SystemVerilog Vmm Log
Verification vmm_test is introduced in vmm 1.1. Vmm Env
Vmm Data
Constructs To know the vmm version which you are using, use this command Vmm Channel
Interface vcs -R -sverilog -ntb_opts dtm Vmm Atomic Generator
         +incdir+$VMM_HOME/sv $VMM_HOME/sv/vmm_versions.sv Vmm Xactor
OOPS Vmm Callback
Randomization Vmm Test
Functional Coverage
vmm_test is used for compiling all the testcases in one compilation. The simulation of Vmm Channel Record
each testcase is done individually. Traditionally for each testcase, compile and And Playback
Assertion simulation are done per testcase file. With this new approach, which dose compilation Vmm Scenario Generator
only once, will save lot of cup. Vmm Opts
DPI
 
UVM Tutorial Report a Bug or Comment
 Generally each testcase can be divided into two parts. on This section - Your
VMM Tutorial
input is what keeps
OVM Tutorial Procedural code part. Testbench.in improving
with time!
Easy Labs : SV
  The procedural code part (like passing the above new constrained transaction
Easy Labs : UVM definition to some atomic generator, calling the env methods etc) has to be defined
Easy Labs : OVM between these macros. vmm provides 2 macros to define testcase procedural part.
Easy Labs : VMM   `vmm_test_begin(testcase_name,vmm_env,"Test Case Name String")
AVM Switch TB   `vmm_test_env(testcase_name)
VMM Ethernet sample Declarative code part.

  The declarative part( like new constrained transacting definition) is defined outside
Verilog these macros.
Verification
Verilog Switch TB Writing A Testcase
Basic Constructs
  Let us see an example of writing a testcase.
  Inside the testcase, we will define a new transaction and pass this transaction to the
atomic generator.
OpenVera
Constructs
Switch TB Declarative part:
RVM Switch TB 1)   Define all the declarative code.
RVM Ethernet sample
  class constrained_tran extends pcie_transaction;
 
  // Add some constraints
Specman E   // Change some method definitions
Interview Questions
  end class

2) Define a handle to the above object.

  constrained_tran c_tran_obj; 

Procedural part:

 Use a `vmm_test_begin . There are 3 arguments to macro.

http://testbench.in/VM_09_VMM_TEST.html[9/26/2012 2:25:39 PM]


WWW.TESTBENCH.IN - VMM Tutorial

The first argument is the name of the testcase class and will also be used as the name
of the testcase in the global testcase registry.

The second argument is the name of the environment class that will be used to
execute the testcase. A data member of that type named "env" will be defined and
assigned, ready to be used.

The third argument is a string documenting the purpose of the test.


 

  `vmm_test_begin(test_1,vmm_env,"Test_1")

  In this testcase, we want to pass the c_tran_obj object. The steps t pass the
c_tran_obj as per the vmm_env is

  env.build();
  c_tran_obj = new(" ");
  env.atomic_gen.randomized_obj = c_tran_obj;

  Start the vmm_env execution.

  env.run();

  Now use `vmm_test_end to define the end of the testcase. The argument to this is
the testcase name.

  `vmm_test_end(test_1)

Following is the full testcase source code which we discussed above.


Testcase source code
  
  class constrained_tran extends pcie_transaction;

  end class
 
  constrained_tran c_tran_obj

`vmm_test_begin(test_1,vmm_env,"Test_1")
   $display(" Start of Testcase :  Test_1 ");
   env.build();
   c_tran_obj = new(" ");
   env.atomic_gen.randomized_obj = c_tran_obj;
   env.run();
   $display(" End of Testcase : Test_1 "); 
`vmm_test_end(test_1)

Like this you can write many testcases in separate file or single file.

Example Of Using Vmm_test

Now we will implement 3 simple testcases and a main testcase which will be used for
selecting any one of the 3 testcases.

testcase_1

Write this testcase in a testcase_1.sv file

// Define all the declarative code hear. I done have anything to show you.
//
//  class constrained_tran extends pcie_transaction;
//
//  end class
//
//  constrained_tran c_tran_obj

http://testbench.in/VM_09_VMM_TEST.html[9/26/2012 2:25:39 PM]


WWW.TESTBENCH.IN - VMM Tutorial

`vmm_test_begin(test_1,vmm_env,"Test_1")
   $display(" Start of Testcase :  Test_1 ");
   // This is procedural part. You can call build method.
   env.build();
 
   // You can pass the above created transaction to atomic gen.
   // c_tran_obj = new(" ");
   // env.atomic_gen.randomized_obj = c_tran_obj;
   //
   //
  
   env.run();
   $display(" End of Testcase : Test_1 "); 
`vmm_test_end(test_1)

testcase_2

 Write this testcase in a testcase_2.sv file

`vmm_test_begin(test_2,vmm_env,"Test_2")
   $display(" Start of Testcase :  Test_2 ");
   // Do something like this ....
   env.build();
   // like this ....
   env.run();
   $display(" End of Testcase : Test_2 "); 
`vmm_test_end(test_2)

testcase_3

 Write this testcase in a testcase_3.sv file

`vmm_test_begin(test_3,vmm_env,"Test_3")
   $display(" Start of Testcase :  Test_3 ");
   // Do something like this ....
   env.build();
   // like this ....
   env.run();
   $display(" End of Testcase : Test_3 "); 
`vmm_test_end(test_3)

main testcase

 Now we will write the main testcase. This doesn't have any test scenario, it is only
used for handling the above 3 testcases.

  This should be written in program block.

1)  First include all the above testcases inside the program block.

  `include "testcase_1.sv"
  `include "testcase_2.sv"
  `include "testcase_3.sv"

2)  Define env class object.

  vmm_env env = new();

  As I dont have a custom env class to show, I used vmm_env. You can use your custom
defined env.
  
3)  In the initial block call the run() method of vmm_test_registry class and pass the
above env object as argument. This run method of vmm_test_registry is a static
method, so there is no need to create an object of this class.

 vmm_test_registry::run(env);

Main testcase source code

http://testbench.in/VM_09_VMM_TEST.html[9/26/2012 2:25:39 PM]


WWW.TESTBENCH.IN - VMM Tutorial

`include "vmm.sv"
program main();

  `include "testcase_1.sv"
  `include "testcase_2.sv"
  `include "testcase_3.sv"

   vmm_env env;
  
   initial
   begin
   $display(" START OF TEST CASE ");
   env = new();
   vmm_test_registry::run(env);
   $display(" START OF TEST CASE ");
   end
  
  
endprogram

 Now compile the above code using command.


 
 vcs -sverilog main_testcase.sv +incdir+$VMM_HOME/sv

 Now simulate the above compiled code.

 To simulate , just do ./simv and see the log.


 You can see the list of the testcases. This simulation will not ececute any testcase.

LOG

  START OF TEST CASE


*FATAL*[FAILURE] on vmm_test_registry(class) at                    0:
    No test was selected at runtime using +vmm_test=<test>.
    Available tests are:
       0) Default : Default testcase that simply calls env::run()
       1) test_1  : Test_1
       2) test_2  : Test_2
       3) test_3  : Test_3

 To run testcase_1 use ./simv +vmm_test=test_1

LOG

   START OF TEST CASE


Normal[NOTE] on vmm_test_registry(class) at                    0:
    Running test "test_1"...
 Start of Testcase :  Test_1
Simulation PASSED on /./ (/./) at                    0 (0 warnings, 0 demoted errors & 0
demoted warnings)
 End of Testcase : Test_1
 START OF TEST CASE

  Simillarly to run testcase_2 ./simv +vmm_test=test_2

LOG

 START OF TEST CASE


Normal[NOTE] on vmm_test_registry(class) at                    0:
    Running test "test_2"...
 Start of Testcase :  Test_2
Simulation PASSED on /./ (/./) at                    0 (0 warnings, 0 demoted errors & 0
demoted warnings)
 End of Testcase : Test_2
 START OF TEST CASE

 You can also call the Default testcase, which just calls the  env::run()

 ./simv +vmm_test=Default

http://testbench.in/VM_09_VMM_TEST.html[9/26/2012 2:25:39 PM]


WWW.TESTBENCH.IN - VMM Tutorial

LOG

 START OF TEST CASE


Normal[NOTE] on vmm_test_registry(class) at                    0:
    Running test "Default"...
Simulation PASSED on /./ (/./) at                    0 (0 warnings, 0 demoted errors & 0
demoted warnings)
 START OF TEST CASE

  
Download the source code

vmm_test.tar
Browse the code in vmm_test.tar

Command to compile

   vcs -sverilog -ntb_opts dtm +incdir+$VMM_HOME/sv main_testcase.sv

Commands to simulate testcases

  ./simv
  ./simv +vmm_test=Default
  ./simv +vmm_test=test_1
  ./simv +vmm_test=test_2
  ./simv +vmm_test=test_3

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/VM_09_VMM_TEST.html[9/26/2012 2:25:39 PM]


WWW.TESTBENCH.IN - VMM Tutorial

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS VMM CHANNEL RECORD AND PLAYBACK Index


Introduction
SystemVerilog Vmm Log
Verification The purpose of this channel feature is to save all the incoming transaction to the Vmm Env
specified file and play back the transaction from the file. Vmm Data
Constructs Vmm Channel
Interface This will be useful when we want to recreate a random scenario in different Vmm Atomic Generator
environment. For example, you found a very interesting random scenario in 10G speed Vmm Xactor
OOPS Vmm Callback
Ethernet. Now you want to use the same random scenario on 1G Ethernet. It may not
Randomization be possible to reproduce the same scenario at 1G speed even with the SV random Vmm Test
stability. The other way is to write a directed testcase to recreate the same scenario. Vmm Channel Record
Functional Coverage And Playback
Using this Record/playback feature, we can record the transaction in the 10G speed
Assertion Ethernet and then play this scenario at 1G speed Ethernet. Vmm Scenario Generator
Vmm Opts
DPI
One more advantage of this feature is, it allows us to shutdown the activities of some
UVM Tutorial components. For Example, consider a layered protocol, the Ethernet. The Verification Report a Bug or Comment
environment can be developed with layers of transactors corresponding to each on This section - Your
VMM Tutorial
protocol layer like, TCP over IP laver, IP fragment and reassembly layer, IP fragment input is what keeps
OVM Tutorial over Ethernet and Ethernet layer. All these layers will be connected using channels. Testbench.in improving
With record/playback feature, the input transaction to Ethernet layer can be with time!
Easy Labs : SV
recorded and in the next simulation, we can shutdown the   TCP over IP laver, IP
Easy Labs : UVM fragment and reassembly layer, IP fragment over Ethernet layers transactors and by
Easy Labs : OVM playing back the recorded transactions. This will improve the memory consumption
and execution speed.
Easy Labs : VMM
AVM Switch TB Record/Playback is independent of Random stability. Changing the seed value will not
affect the playback. This will give us an opportunity to test the DUT using a specific
VMM Ethernet sample scenario of the high layer (Consider the previous example: Some interested scenario
in IP fragment over Ethernet) with lot of different randomization using different seeds
of lower layer protocol (Ethernet layer).
Verilog
Verification This will also help, when we cannot reproduce the random scenario using Seed. If you
found a Bug in the DUT, and still you are in the development stage of your
Verilog Switch TB environment, you cannot stop the development in the environment till the bug is
Basic Constructs fixed. There are chances that the changes in the environment will not allow you to
reproduce the same scenario even with the same seed. In this case, if you have stored
the transactions, you can playback the transaction.
OpenVera
Constructs Now we will learn about the implementation.
Switch TB
Recording
RVM Switch TB
RVM Ethernet sample To record the flow of transaction descriptors added through the channel instance, call
the record method of that instance.

function bit record(string filename);
Specman E
Interview Questions The vmm_data::save() method must be implemented for recording.  All the
transaction which are added to channel using the vmm_channel::put() method are
recorded and are avilabe for playback. A null filename stops the recording process.
vmm_channel::record() method returns TRUE if the specified file was successfully
opened.

RECORDING notification is indicated by vmm_channel::notify, when recording.

Playing Back

To playback the transactions in the recorded file, use the vmm_channel::playback()

http://testbench.in/VM_10_VMM_CHANNEL_RECORD_AND_PLAYBACK.html[9/26/2012 2:25:48 PM]


WWW.TESTBENCH.IN - VMM Tutorial

method.

task playback(output bit success,      
              input  string      filename,      
              input  vmm_data    factory,      
              input  bit         metered = 0,  
              input  vmm_scenario grabber = null);

This method will block the sources of the current channel like vmm_channl::put()
method till the playback is completed. The vmm_data::load() method must be
implemented for playback. The order of the transaction will be same as the order
while recording. If the metered argument is TRUE, the transaction descriptors are
added to the channel with the same relative time interval as they were originally put
in when the file was recorded.

The success argument is set to TRUE if the playback was successful. If the playback
process encounters an error condition such as a NULL (empty string) filename, a
corrupt file or an empty file, then success is set to FALSE.

PLAYBACK_DONE notification is indicated by vmm_channel::notify, when playback is


completed.

EXAMPLE

Let us write an example to see how the record and playback works.

Record & Playback of channels can be used with atomic generator and scenario
generators. Here is a simple transaction with its channel and atomic generator. We
will use this atomic generator to generate transaction. The atomic generator has
out_chan channel, this channel is used send the generated transaction. We will record
and playback the transaction in the out_chan. I used Vmm_data macros for
implementing all the required methods.

  class trans extends vmm_data;
    typedef enum bit {BAD_FCS=1'b0, GOOD_FCS=1'b1} kind_e;
  
    rand bit [47:0] DA;
    rand bit [47:0] SA;
    rand int        length;
    rand kind_e     kind;
  
    `vmm_data_member_begin(trans)
       `vmm_data_member_scalar(DA, DO_ALL)
       `vmm_data_member_scalar(SA, DO_ALL)
       `vmm_data_member_scalar(length, DO_ALL)
       `vmm_data_member_enum(kind, DO_ALL)
    `vmm_data_member_end(trans)
  endclass
  
  
  // for declaring trans_channel
  `vmm_channel(trans)
  
  // for declaring trans_atomic_gen
  `vmm_atomic_gen(trans, "Gen")
  

Now we will write a simple program to record and play back the above defined
transaction.

Use the trans_atomic_gen to generate the transactions. This also the put the
transactions in to out_chan channel. Call the start_xactor() method of the generator
to start the generator of transaction. Call the record() method of out_chan to record
the incoming transactions.

http://testbench.in/VM_10_VMM_CHANNEL_RECORD_AND_PLAYBACK.html[9/26/2012 2:25:48 PM]


WWW.TESTBENCH.IN - VMM Tutorial

          gen.stop_after_n_insts = 3;
          gen.start_xactor(); 
          gen.out_chan.record("Trans_recordes.tr"); 

To play back the recorded transactions, call the playback method. Then check if the
playback is fine.

          tr = new();
          gen.out_chan.playback(success,"Trans_recordes.tr",tr);
          if(!success)
                $display(" Failed to playback Trans_recordes.tr");         ]

Now we will write a logic which gets the transaction from the channel and prints the
content to terminal, so that we can observe the results.
The above the logic generates 3 transactions. Get the 3 transaction from the channel
and print the content.

  initial
     repeat(3) 
     begin
        #10;
        gen.out_chan.get(tr);
        tr.display();
     end
  

Complete source code


  
   program main();
   trans tr;
   trans_atomic_gen gen = new("Atomic Gen",1);
   bit success;
  
   // This is the producer logic.
   // Transactions are produced from Atomic generator in RECORD mode.
   // Transactions are produced from recorded file in PLAYBACK mode.
  
    initial
        begin
          
           if($test$plusargs("RECORD"))
           begin
               $display(" RECORDING started "); 
               gen.stop_after_n_insts = 3;
               gen.start_xactor(); 
               gen.out_chan.record("Trans_recordes.tr");
           end 
           else  if($test$plusargs("PLAYBACK"))
           begin 
               $display(" PLAYBACK started ");
               tr = new();
               gen.out_chan.playback(success,"Trans_recordes.tr",tr);
               if(!success)
                     $display(" Failed to playback Trans_recordes.tr");
           end
           else
               $display(" give +RECORD or +PLAYBACK with simulation command"); 
        end
  
   // This is consumer logic.
    initial
        repeat(3) 
        begin
           #10;
           gen.out_chan.get(tr);
           tr.display();
        end
  
   endprogram
  
  

Download the source code

http://testbench.in/VM_10_VMM_CHANNEL_RECORD_AND_PLAYBACK.html[9/26/2012 2:25:48 PM]


WWW.TESTBENCH.IN - VMM Tutorial

 This works with vmm 1.1 and above.


vmm_record_playback.tar
Browse the code in vmm_record_playback.tar

Command to record the transaction

vcs -R -sverilog +incdir+$VMM_HOME/sv record_playback.sv +RECORD

Log file

     RECORDING started

     trans (1.0.0):


     DA='haecd55f5b651
     SA='h13db0b1a590e
     length='hd8a7d371
     kind=GOOD_FCS

     trans (1.0.1):


     DA='h5e980e9b7ce9
     SA='h44a4bbdaf703
     length='h5714c3a7
     kind=GOOD_FCS

     trans (1.0.2):


     DA='hba4f5a021300
     SA='h2de750b6cc3e
     length='h22ca2bd8
     kind=GOOD_FCS

 You can also see a file named "Trans_recordes.tr" in your simulation directory.

Command to playback the transaction

  vcs -R -sverilog +incdir+$VMM_HOME/sv trans.sv +PLAYBACK

Log File

     PLAYBACK started

     trans (0.0.0):


     DA='haecd55f5b651
     SA='h13db0b1a590e
     length='hd8a7d371
     kind=GOOD_FCS

     trans (0.0.0):


     DA='h5e980e9b7ce9
     SA='h44a4bbdaf703
     length='h5714c3a7
     kind=GOOD_FCS

     trans (0.0.0):


     DA='hba4f5a021300
     SA='h2de750b6cc3e
     length='h22ca2bd8
     kind=GOOD_FCS

 Look, the same transactions which were generated while RECORDING are played
back.

http://testbench.in/VM_10_VMM_CHANNEL_RECORD_AND_PLAYBACK.html[9/26/2012 2:25:48 PM]


WWW.TESTBENCH.IN - VMM Tutorial

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/VM_10_VMM_CHANNEL_RECORD_AND_PLAYBACK.html[9/26/2012 2:25:48 PM]


WWW.TESTBENCH.IN - VMM Tutorial

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS VMM SCENARIO GENERATOR Index


Introduction
SystemVerilog Vmm Log
Verification Atomic generator generates individual data items or transaction descriptors. Each Vmm Env
item is generated independently of other items in a random fashion. Atomic generator Vmm Data
Constructs is simple to describe and use. Vmm Channel
Interface Vmm Atomic Generator
Unlike atomic generator, a scenario generator generates a sequence of transaction. Vmm Xactor
OOPS Vmm Callback
Randomization Example of sequence of transaction: Vmm Test
Vmm Channel Record
Functional Coverage And Playback
  CPU instructions like LOAD__A,LOAD__B,ADD_A_B,STORE_C.  
Assertion Vmm Scenario
  Packets with incrementing length. Generator
DPI   Do write operation to address "123" and then do the read to address "123". Vmm Opts
UVM Tutorial
  
It is very unlikely that atomic generator to generate transaction in the above ordered Report a Bug or Comment
VMM Tutorial sequence. With scenario generator, we can generate these sequence of transaction. on This section - Your
OVM Tutorial input is what keeps
 VMM provides `vmm_scenario_gen() macro for quickly creating a scenario generator. Testbench.in improving
Easy Labs : SV
with time!
Easy Labs : UVM `vmm_scenario_gen(class_name, "Class Description");
Easy Labs : OVM The macro defines classes named <class_name>_scenario_gen,
Easy Labs : VMM <class_name>_scenario, <class_name>_scenario_election ,
<class_name>_scenario_gen_callbacks and <class_name>_atomic_scenario.
AVM Switch TB
VMM Ethernet sample     class custom_scenario_gen extends vmm_xactor;
    class custom_scenario extends vmm_data;
    class custom_atomic_scenario extends custom_scenario;
    class custom_scenario_election;
Verilog     class custom_scenario_gen_callbacks extends vmm_xactor_callbacks
Verification
Verilog Switch TB <class_name>_scenario:
Basic Constructs This scenario generator can generate more than one scenario. Each scenario which
can contain more than one transaction is described in a class which is extended from
<class_name>_scenario.
OpenVera
For each scenario, following variables must be constraint.
Constructs
Length: number of transactions in an array.
Switch TB Repeated: number of times to repeat this scenario.
RVM Switch TB
<class_name>_atomic_scenario:
RVM Ethernet sample
This class is a atomic scenario. This is the default scenario. This scenario is a random
transactions.
Specman E
<class_name>_scenario_election:
Interview Questions
This class is the arbiter which determines the order that the known scenarios are
applied. By default, scenarios are elected atomically. User can extend this class to
define an order in which the scenarios should be picked.

<class_name>_scenario_gen:

This class is the scenario generator which generates the transactions and sends out
using output channel. This class has a queue of scenario objects. Each scenario
contains transaction instances in an array.  

http://testbench.in/VM_11_VMM_SCENARIO_GENERATOR.html[9/26/2012 2:25:58 PM]


WWW.TESTBENCH.IN - VMM Tutorial

<class_name>_scenario_gen_callbacks:

This class provides callback mechanism. There are two callback methods define.
pre_scenario_randomize() and post_scenario_gen() which are called at pre-
randomization of the scenario and post-generation of the scenario respectively.

Example

Let us write an example.

Following is the transaction class which we will use to write a scenario generator.

class instruction extends vmm_data;
   vmm_log log;
   typedef enum {LOAD__A,LOAD__B,ADD_A_B,SUB_A_B,STORE_C } kinds_e;
   rand kinds_e inst;

   function new();
      super.new(this.log);
   endfunction:new

   virtual function string psdisplay(string prefix = "");
         psdisplay =  $psprintf("  Instruction : %s | stream_id : %0d | scenario_id : %0d
",inst.name(),stream_id,scenario_id);
   endfunction:psdisplay

   virtual function vmm_data allocate();
      instruction tr = new;
      allocate = tr;
   endfunction:allocate

   virtual function vmm_data copy(vmm_data cpy = null);


      instruction to;
      if (cpy == null)
         to = new;
       else
         if (!$cast(to, cpy)) begin
            `vmm_fatal(this.log, "Attempting to copy to a non instruction instance");
            return null;
        end
      super.copy_data(to);
      to.inst = this.inst;

http://testbench.in/VM_11_VMM_SCENARIO_GENERATOR.html[9/26/2012 2:25:58 PM]


WWW.TESTBENCH.IN - VMM Tutorial

      copy = to;
   endfunction:copy
endclass

  

The above transaction crests CPU instructions.

Let us consider that sequence of instruction LOAD__A,LOAD__B,ADD_A_B,STORE_C  is


a interesting scenario and LOAD__A,LOAD__B,SUB_A_B,STORE_C is also an interesting
scenario.
When instructions are generated, we want to generate these 2 sequences of
instruction. Let us see how to generate these 2 sequence of instructions .

As we have already discussed, `vmm_scenario_gen() creates use full class for


cscenario generation.

1) Use  `vmm_scenario_gen() macro to declare the scenario classes.

`vmm_scenario_gen(instruction, "Instruction Scenario Generator")

   This macro will create following classs

    instruction_scenario_gen
    instruction_scenario
    instruction_atomic_scenario
    instruction_scenario_election
    instruction_scenario_gen_callbacks

2) Define interesting scenarios by extending inst_scenario;

class instruction_scenario_add_sub extends instruction_scenario;

3) Define the first scenario. It is sequence of instructions for addition operation.

   a) Declare a variable for identifying the scenario.

          int addition_scenario_id  ;

   Each scenario has more than one inductions. All these instructions are in a queue
"items"   which is already defined in    "instruction_scenario".

   The rand varible "scenario_kind", which pre defined in the vmm_scenario class, will
randomly select one of the defined scenarios. "scenario_kind" varible has the id of the
current scenario. So we have to define the addition scenario, when the
"scenario_kind" value is addition_scenario_id.

   b) Constrain the scenario kind,  

      constraint addition_scenario_items {
                if($void(scenario_kind) == addition_scenario_id) {

   c)  The number of instructions define in a scenario is specified by the predefined


variable "length". In our example, we have 4 instructions. So constrain the length to 4.

        length == 4;

   d) The predefined variable "repeated" used to control if the VMM scenario generator
would run the scenario more than once each time it is created. We are not interested
in repeating so, constrain it to 0

        repeated == 0;

   e) Constrain the individual items based on the requirements if this scenario is


selected. Our requirement in this example is that "inst" should follow the sequence
LOAD__A,LOAD__B,ADD_A_B,STORE_C

   foreach(items[i])
        if(i == 0) 
           this.items[i].inst == instruction::LOAD__A;
        else if(i == 1) 
           this.items[i].inst == instruction::LOAD__B;
        else if(i == 2) 
           this.items[i].inst == instruction::ADD_A_B;

http://testbench.in/VM_11_VMM_SCENARIO_GENERATOR.html[9/26/2012 2:25:58 PM]


WWW.TESTBENCH.IN - VMM Tutorial

        else if(i == 3) 
           this.items[i].inst == instruction::STORE_C;

4)Define second scenario. It is Sequence of instructions for subtraction operation.    

   a) Declare a variable for identifying the scenario.

      int subtraction_scenario_id ;

   b) Constrain the scenario kind,  

      constraint subtraction_scenario_items {
              if($void(scenario_kind) == subtraction_scenario_id) {

   c) Constrain the length

      length == 4;

   d) Constrain the repeated

      repeated == 0;

   e) Constrain the items

     foreach(items[i])
        if(i == 0) 
           this.items[i].inst == instruction::LOAD__A;
        else if(i == 1) 
           this.items[i].inst == instruction::LOAD__B;
        else if(i == 2) 
           this.items[i].inst == instruction::SUB_A_B;
        else if(i == 3) 
           this.items[i].inst == instruction::STORE_C;

5)Define constructor method.


  
   a) call the super.new() method.
    
      Get a unique Ids from the define_scenario() method for each scenario.
      define_scenario() is predefined in  *_scenario class.  

         function new();
             this.addition_scenario_id = define_scenario(" ADDITION ",4);
             this.subtraction_scenario_id = define_scenario(" SUBSTRACTION ",4);
         endfunction

  With this, we completed the implementation of scenarios.

Scenario Code

`vmm_scenario_gen(instruction,"Instruction Scenario Generator")

class instruction_scenario_add_sub extends instruction_scenario;

///////////////////////////////////////////////////////////////
//////              ADDITION SCENARIO                //////////
///////////////////////////////////////////////////////////////

  int addition_scenario_id  ;

  constraint addition_scenario_items {
       if($void(scenario_kind) == addition_scenario_id) {
        repeated == 0;
        length == 4;
        foreach(items[i])
        if(i == 0) 
           this.items[i].inst == instruction::LOAD__A;
        else if(i == 1) 
           this.items[i].inst == instruction::LOAD__B;
        else if(i == 2) 
           this.items[i].inst == instruction::ADD_A_B;

http://testbench.in/VM_11_VMM_SCENARIO_GENERATOR.html[9/26/2012 2:25:58 PM]


WWW.TESTBENCH.IN - VMM Tutorial

        else if(i == 3) 
           this.items[i].inst == instruction::STORE_C;
       }
  }

///////////////////////////////////////////////////////////////
//////            ASUBTRACTION SCENARIO              //////////
///////////////////////////////////////////////////////////////

  int subtraction_scenario_id ;

  constraint subtraction_scenario_items {
       if($void(scenario_kind) == subtraction_scenario_id) {
        repeated == 0;
        length == 4;
        foreach(items[i])
        if(i == 0) 
           this.items[i].inst == instruction::LOAD__A;
        else if(i == 1) 
           this.items[i].inst == instruction::LOAD__B;
        else if(i == 2) 
           this.items[i].inst == instruction::SUB_A_B;
        else if(i == 3) 
           this.items[i].inst == instruction::STORE_C;
       }
   }

   function new();
       this.addition_scenario_id = define_scenario(" ADDITION ",4);
       this.subtraction_scenario_id = define_scenario(" SUBSTRACTION ",4);
   endfunction

endclass

Testcase

  Now we will write a test case to see how to above defined scenario works.

1) Declare scenario generator

     instruction_scenario_gen gen;

2) Declare the scenario which we defined earlier.

     instruction_scenario_add_sub sce_add_sub;

3) Construct the generator and scenarios.

     gen = new("gen",0);


     sce_add_sub = new();

4) set the number of instances and scenarios generated by generator to 20 and 4


respectevy.

     gen.stop_after_n_insts = 20;


     gen.stop_after_n_scenarios = 4;

5) Scenario generators store all the scenarios in scenario_set queue. So, we have to
add the scenario which we constructed above to the queue.

     gen.scenario_set[0] = sce_add_sub;

6) Start the generator

     gen.start_xactor();

7) Similar t the Atomic generator, the transactions  created by the scenario generator


are sent to out_chan channel.
   Get the instructions from the out_chan channel and print the content.

     repeat(20) begin
     gen.out_chan.get(inst);
     inst.display();

http://testbench.in/VM_11_VMM_SCENARIO_GENERATOR.html[9/26/2012 2:25:58 PM]


WWW.TESTBENCH.IN - VMM Tutorial

Testcase code

 program test();

     instruction_scenario_gen gen;


     instruction_scenario_add_sub sce_add_sub;
     instruction inst;

     initial
     begin
         gen = new("gen",0);
         sce_add_sub = new();

         //gen.log.set_verbosity(vmm_log::DEBUG_SEV,"/./","/./");
         gen.stop_after_n_insts = 20;
         gen.stop_after_n_scenarios = 4;

         gen.scenario_set[0] = sce_add_sub;

         gen.start_xactor();

         repeat(20) begin
         gen.out_chan.get(inst);
         inst.display();
         end

     end

 endprogram

Down load the source code

vmm_scenario.tar
Browse the code in vmm_scenario.tar

Command to simulate
vcs -sverilog -ntb_opts rvm -f filelist -R

Observe the log file, you can see the both the scenarios.

Logfile

  Instruction : LOAD__A | stream_id : 0 | scenario_id : 0


  Instruction : LOAD__B | stream_id : 0 | scenario_id : 0
  Instruction : ADD_A_B | stream_id : 0 | scenario_id : 0
  Instruction : STORE_C | stream_id : 0 | scenario_id : 0

  Instruction : LOAD__A | stream_id : 0 | scenario_id : 1


  Instruction : LOAD__B | stream_id : 0 | scenario_id : 1
  Instruction : ADD_A_B | stream_id : 0 | scenario_id : 1
  Instruction : STORE_C | stream_id : 0 | scenario_id : 1

  Instruction : LOAD__A | stream_id : 0 | scenario_id : 2


  Instruction : LOAD__B | stream_id : 0 | scenario_id : 2
  Instruction : SUB_A_B | stream_id : 0 | scenario_id : 2
  Instruction : STORE_C | stream_id : 0 | scenario_id : 2

  Instruction : LOAD__A | stream_id : 0 | scenario_id : 3


  Instruction : LOAD__B | stream_id : 0 | scenario_id : 3
  Instruction : ADD_A_B | stream_id : 0 | scenario_id : 3
  Instruction : STORE_C | stream_id : 0 | scenario_id : 3

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/VM_11_VMM_SCENARIO_GENERATOR.html[9/26/2012 2:25:58 PM]


WWW.TESTBENCH.IN - VMM Tutorial

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/VM_11_VMM_SCENARIO_GENERATOR.html[9/26/2012 2:25:58 PM]


WWW.TESTBENCH.IN - VMM Tutorial

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS VMM OPTS Index


Introduction
SystemVerilog Vmm Log
Verification Some of the test parameters in functional verification are passed from the command Vmm Env
line. Passing Parameters from the command line allows simulating the same testcase Vmm Data
Constructs file with different scenario. For example, let say you are verifying Ethernet protocol. Vmm Channel
Interface Insert_crc_error.sv is a testcase file which verifies the DUT by sending CRC error Vmm Atomic Generator
packets. Now you can use the same testcase file to verify the DUT in 3 different Vmm Xactor
OOPS Vmm Callback
modes , 10G 1000M and 100M modes by passing these parameters from the command
Randomization prompt, this increases the testcase reusability. Vmm Test
Vmm Channel Record
Functional Coverage And Playback
 As parameters became one of the most important techniques in reusing the testcases,
Assertion vmm has added vmm_opts class to manage parameters efficiently. Vmm Scenario Generator
vmm_opts captures parameter from run time options. Vmm Opts
DPI
UVM Tutorial There are 2 ways to specify the parameters during runtime. Report a Bug or Comment
on This section - Your
VMM Tutorial
1) Command line input is what keeps
OVM Tutorial    vmm_opts internally uses $plusargs to recognize the options specified on command Testbench.in improving
line. with time!
Easy Labs : SV
Easy Labs : UVM
2) text file
   If you have lot of parameters to mentions, then you can also mention all the
Easy Labs : OVM parameters in a text file and pass it as command line options.  
Easy Labs : VMM
vmm_opts can recognize 3 types of parameters. They are
AVM Switch TB
VMM Ethernet sample String type parameters
Integer type parameters
Bit type parameters
Verilog
Following are the 3 static methods which are defined in vmm_opts to get the
Verification parameter values.
Verilog Switch TB
Static function bit get_bit(string name, string doc = "");    
Basic Constructs
Static function int get_int(string name,int dflt = 0, string doc = "");

OpenVera Static function string get_string(string name, string dflt = "", string doc = "");


Constructs
The first argument is the name of the parameter and the argument "doc" is description
Switch TB of the runtime argument that will be displayed by the vmm_opts::get_help() method.
RVM Switch TB as these methods are static, user dont need to construct the object of vmm_opts.
RVM Ethernet sample Argument "dflt" is the default value.  

How to give options


Specman E
To supply a Boolean runtime option "foo" , use "+vmm_opts+...+foo+..." command-line
Interview Questions option, or "+vmm_foo" command-line option, or the line "+foo" in the option file.

To supply a integer value "5" for runtime option "foo", use the
"+vmm_opts+...+foo=5+..." command-line option, or "+vmm_foo=5" command-line
option, or the line "+foo=5" in the option file.

To supply a string value "bar" for runtime option "foo" , use the
"+vmm_opts+...+foo=bar+..." command-line option, or "+vmm_foo=bar" command-line
option, or the line "+foo=bar" in the option file.

To supply a textfile which contains the runtime options, use

http://testbench.in/VM_12_VMM_OPTS.html[9/26/2012 2:26:08 PM]


WWW.TESTBENCH.IN - VMM Tutorial

"+vmm_opts_file=finename.txt"

+vmm_help command line option will print the run time options help. This option will
call the vmm_opts::get_help() method.

The following is a basic example of how these parameters could be received using
vmm_opts

EXAMPLE

`include "vmm.sv"

class my_env extends vmm_env;

  virtual function void gen_cfg();
     integer foo1;
     string foo2;
     bit foo3;

     super.gen_cfg();
     `vmm_note(log,"START OF GEN_CFG ");
      foo1 = vmm_opts::get_int("foo1" , 10 , "Help for the option foo1: pass any integer
between 0 to 100");
      foo2 = vmm_opts::get_string("foo2" , "default_string" , "Help for the option foo2:
pass any string");
      foo3 = vmm_opts::get_int("foo3" , "Help for the option foo3: just use foo3 to
enable ");
      `vmm_note(log,$psprintf("\n   Run time Options  \n       foo1 : %0d \n       foo2 : %s
\n       foo3 : %b \n",foo1,foo2,foo3));  
     `vmm_note(log,"END OF GEN_CFG ");
  endfunction
 
endclass

program main();

   initial
   begin
      my_env env;
      env = new();
      env.run();  
   end

endprogram

Download the example

vmm_opts.tar
Browse the code in vmm_opts.tar

Commands to complie

  This works with vmm 1.1 and above.


  vcs -sverilog -ntb_opts dtm +incdir+$VMM_HOME/sv main_testcase.sv

Commands to complie

./simv
./simv +vmm_foo1=101
./simv +vmm_opts+foo1=101+foo2=Testbench.in

Following is log file generated using runtime option  +vmm_foo1=101


+vmm_foo2=Testbench.in

http://testbench.in/VM_12_VMM_OPTS.html[9/26/2012 2:26:08 PM]


WWW.TESTBENCH.IN - VMM Tutorial

Log

Normal[NOTE] on Verif Env() at                    0:


    START OF GEN_CFG
WARNING[FAILURE] on vmm_opts(class) at                    0:
    No documentation specified for option "foo3".
Normal[NOTE] on Verif Env() at                    0:
    
       Run time Options  
           foo1 : 101
           foo2 : Testbench.in
           foo3 : 0
    
Normal[NOTE] on Verif Env() at                    0:
    END OF GEN_CFG
Simulation PASSED on /./ (/./) at                    0 (1 warnings, 0 demoted errors & 0
demoted warnings)

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/VM_12_VMM_OPTS.html[9/26/2012 2:26:08 PM]


WWW.TESTBENCH.IN - OVM Tutorial

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INTRODUCTION Index


Introduction
SystemVerilog Ovm Testbench
Verification Ovm Reporting
The OVM Class Library provides the building blocks needed to quickly develop well- Ovm Transaction
Constructs constructed and reusable verification components and test environments in Ovm Factory
Interface SystemVerilog. Ovm Sequence 1
Ovm Sequence 2
OOPS Ovm Sequence 3
OVM library contains:
Randomization Component classes for building testbench components like Ovm Sequence 4
generator/driver/monitor etc. Ovm Sequence 5
Functional Coverage Ovm Sequence 6
Reporting classes for logging, Ovm Configuration
Assertion
Factory for object substitution.
DPI Synchronization classes for managing concurrent process. Report a Bug or Comment
UVM Tutorial Policy classes for printing, comparing, recording, packing, and unpacking of on This section - Your
ovm_object based classes. input is what keeps
VMM Tutorial
TLM Classes for transaction level interface. Testbench.in improving
OVM Tutorial Sequencer and Sequence classes for generating realistic stimulus. with time!
Easy Labs : SV And Macros which can be used for shorthand notation of complex implementation.
Easy Labs : UVM
Easy Labs : OVM In this tutorial, we will learn some of the OVM concepts with examples.
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

Verilog
Verification
Verilog Switch TB
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/OT_01_INTRODUCTION.html[9/26/2012 2:26:16 PM]


WWW.TESTBENCH.IN - OVM Tutorial

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OT_01_INTRODUCTION.html[9/26/2012 2:26:16 PM]


WWW.TESTBENCH.IN - OVM Tutorial

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS OVM TESTBENCH Index


Introduction
SystemVerilog Ovm Testbench
Verification Ovm components, ovm env and ovm test are the three main building blocks of a Ovm Reporting
testbench in ovm based verification. Ovm Transaction
Constructs Ovm Factory
Interface Ovm Sequence 1
Ovm_env Ovm Sequence 2
OOPS Ovm Sequence 3
Randomization Ovm_env is extended from ovm_componented and does not contain any extra Ovm Sequence 4
functionality. Ovm_env is used to create and connect the ovm_components like Ovm Sequence 5
Functional Coverage Ovm Sequence 6
driver, monitors ,  sequeners etc.  A environment class can also be used as sub-
Assertion environment in another environment.  As there is no difference between ovm_env and Ovm Configuration
DPI ovm_component , we will discuss about ovm_component, in the next section.  
Report a Bug or Comment
UVM Tutorial on This section - Your
Verification Components input is what keeps
VMM Tutorial
Testbench.in improving
OVM Tutorial Ovm verification component classes are derived from ovm_component class which with time!
Easy Labs : SV provides features like hierarchy searching, phasing, configuration , reporting , factory
and transaction recording.  
Easy Labs : UVM
Easy Labs : OVM Following are some of the ovm component classes
Ovm_agent
Easy Labs : VMM
Ovm_monitor
AVM Switch TB Ovm_scoreboard
VMM Ethernet sample Ovm_driver
Ovm_sequencer

Verilog NOTE: ovm_env and ovm_test are also extended from ovm_component.
Verification A typical ovm verification environment:
Verilog Switch TB
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/OT_02_OVM_TESTBENCH.html[9/26/2012 2:26:24 PM]


WWW.TESTBENCH.IN - OVM Tutorial

An agent typically contains three subcomponents: a driver, sequencer, and


monitor.  If the agent is active, subtypes should contain all three subcomponents.  If
the agent is passive, subtypes should contain only the monitor.

About Ovm_component Class:

Ovm_compoenent class is inherited from ovm_report_object which is inherited from


ovm_object.
As I mentioned previously, ovm_component class provides features like hierarchy
searching, phasing, configuration , reporting , factory and transaction recording.
We will discuss about phasing concept in this section and rest of the features will be
discussed as separate topics.  

OVM phases

OVM Components execute their behavior in strictly ordered, pre-defined phases. Each
phase is defined by its own virtual method, which derived components can override to
incorporate component-specific behavior. By default , these methods do nothing.

--> virtual function void build()

This phase is used to construct various child components/ports/exports and configures


them.

--> virtual function void connect()

This phase is used for connecting the ports/exports of the components.

http://testbench.in/OT_02_OVM_TESTBENCH.html[9/26/2012 2:26:24 PM]


WWW.TESTBENCH.IN - OVM Tutorial

--> virtual function void end_of_elaboration()

This phase is used for configuring the components if required.

--> virtual function void start_of_simulation()

This phase is used to print the banners and topology.

--> virtual task run()

In this phase , Main body of the test is executed where all threads are forked off.

--> virtual function void extract()

In this phase, all the required information is gathered.

--> virtual function void check()

In this phase, check the results of the extracted information such as un responded
requests in scoreboard, read statistics registers etc.

--> virtual function void report()

This phase is used for reporting the pass/fail status.

Only  build() method is executed in top down manner. i.e after executing


parent  build() method, child objects build() methods are executed.  All other
methods are executed in bottom-up manner.  The run() method is the only method
which is time consuming. The run() method is forked, so the order in which all
components run() method are executed is undefined.

Ovm_test

Ovm_test is derived from ovm_component class and there is no extra functionality is


added.  The advantage of used ovm_test for defining the user defined test is that the
test case selection can be done from command line option
+OVM_TESTNAME=<testcase_string> . User can also select the testcase by passing the
testcase name as string to ovm_root::run_test(<testcase_string>)  method.

In the above <testcase_string> is the  object type of the testcase class.

 
Lets implement environment for the following topology. I will describe the
implementation of environment , testcase and top module. Agent, monitor and driver
are implemented similar to environment.  

1)Extend ovm_env class and define user environment.

    class env extends ovm_env;

2)Declare the utility macro. This utility macro provides the implementation of create()

http://testbench.in/OT_02_OVM_TESTBENCH.html[9/26/2012 2:26:24 PM]


WWW.TESTBENCH.IN - OVM Tutorial

and get_type_name() methods and all the requirements needed for factory.

    `ovm_component_utils(env)

3)Declare the objects for agents.

   agent ag1;
   agent ag2;

4)Define the constructor. In the constructor, call the super methods and pass the
parent object. Parent is the object in which environment is instantiated.

    function new(string name , ovm_component parent = null);


        super.new(name, parent);
    endfunction: new

5)Define build method. In the build method, construct the agents.


To construct agents, use  create() method.  The advantage of create() over new() is
that when create() method is called, it will check if there is a factory override and
constructs the object of override type.

   function void build();
       super.build();
       ovm_report_info(get_full_name(),"Build", OVM_LOG);
       ag1 = agent::type_id::create("ag1",this);  
       ag2 = agent::type_id::create("ag2",this);  
   endfunction

6)Define
connect(),end_of_elaboration(),start_of_simulation(),run(),extract(),check(),report()
methods.
Just print a message from these methods, as we dont have any logic in this example
to define.

     function void connect();
        ovm_report_info(get_full_name(),"Connect", OVM_LOG);
     endfunction

Complete code of environment class:

class env extends ovm_env;

 `ovm_component_utils(env)
  agent ag1;
  agent ag2;
  
 function new(string name, ovm_component parent);
     super.new(name, parent);
 endfunction

 function void build();
     ovm_report_info(get_full_name(),"Build", OVM_LOG);
     ag1 = agent::type_id::create("ag1",this);  
     ag2 = agent::type_id::create("ag2",this);  
 endfunction

 function void connect();
     ovm_report_info(get_full_name(),"Connect", OVM_LOG);
 endfunction

 function void end_of_elaboration();
     ovm_report_info(get_full_name(),"End_of_elaboration", OVM_LOG);
 endfunction

 function void start_of_simulation();
     ovm_report_info(get_full_name(),"Start_of_simulation", OVM_LOG);
 endfunction

 task run();
     ovm_report_info(get_full_name(),"Run", OVM_LOG);
 endtask

 function void extract();

http://testbench.in/OT_02_OVM_TESTBENCH.html[9/26/2012 2:26:24 PM]


WWW.TESTBENCH.IN - OVM Tutorial

     ovm_report_info(get_full_name(),"Extract", OVM_LOG);
 endfunction

 function void check();
     ovm_report_info(get_full_name(),"Check", OVM_LOG);
 endfunction

 function void report();
     ovm_report_info(get_full_name(),"Report", OVM_LOG);
 endfunction

endclass

Now we will implement the testcase.


1)Extend ovm_test and define the test case

   class test1 extends ovm_test;

2)Declare component ustilits using utility macro.

   `ovm_component_utils(test1)

2)Declare environment class handle.

   env t_env;

3)Define constructor method. In the constructor, call the super method and construct
the environment object.

    function new (string name="test1", ovm_component parent=null);
        super.new (name, parent);
        t_env = new("t_env",this);
    endfunction : new 

4)Define the end_of_elaboration method. In this method, call the print() method. This
print() method will print the topology of the test.

    function void end_of_elaboration();
        ovm_report_info(get_full_name(),"End_of_elaboration", OVM_LOG);
        print();
    endfunction

4)Define the run method and call the global_stop_request() method.

    task run ();
        #1000;
        global_stop_request();
    endtask : run

Testcase source code:

class test1 extends ovm_test;

   `ovm_component_utils(test1)
    env t_env;
 
    function new (string name="test1", ovm_component parent=null);
        super.new (name, parent);
        t_env = new("t_env",this);
    endfunction : new 

    function void end_of_elaboration();
        ovm_report_info(get_full_name(),"End_of_elaboration", OVM_LOG);
        print();
    endfunction
 
    task run ();
        #1000;
        global_stop_request();
    endtask : run

http://testbench.in/OT_02_OVM_TESTBENCH.html[9/26/2012 2:26:24 PM]


WWW.TESTBENCH.IN - OVM Tutorial

endclass

Top Module:

To start the testbench, run_test() method must be called from initial block.
Run_test() mthod Phases all components through all registered phases.

module top;

  initial
      run_test();

endmodule

Download the source code

ovm_phases.tar
Browse the code in ovm_phases.tar

Command to run the simulation

your_tool_simulation_command +path_to_ovm_pkg -f filelist +OVM_TESTNAME=test1

Log file:

[RNTST] Running test test1...


ovm_test_top.t_env [ovm_test_top.t_env] Build
ovm_test_top.t_env.ag1 [ovm_test_top.t_env.ag1] Build
ovm_test_top.t_env.ag1.drv [ovm_test_top.t_env.ag1.drv] Build
ovm_test_top.t_env.ag1.mon [ovm_test_top.t_env.ag1.mon] Build
ovm_test_top.t_env.ag2 [ovm_test_top.t_env.ag2] Build
ovm_test_top.t_env.ag2.drv [ovm_test_top.t_env.ag2.drv] Build
ovm_test_top.t_env.ag2.mon [ovm_test_top.t_env.ag2.mon] Build
ovm_test_top.t_env.ag1.drv [ovm_test_top.t_env.ag1.drv] Connect
ovm_test_top.t_env.ag1.mon [ovm_test_top.t_env.ag1.mon] Connect
ovm_test_top.t_env.ag1 [ovm_test_top.t_env.ag1] Connect
ovm_test_top.t_env.ag2.drv [ovm_test_top.t_env.ag2.drv] Connect
ovm_test_top.t_env.ag2.mon [ovm_test_top.t_env.ag2.mon] Connect
ovm_test_top.t_env.ag2 [ovm_test_top.t_env.ag2] Connect
ovm_test_top.t_env [ovm_test_top.t_env] Connect
ovm_test_top.t_env.ag1.drv [ovm_test_top.t_env.ag1.drv] End_of_elaboration
ovm_test_top.t_env.ag1.mon [ovm_test_top.t_env.ag1.mon] End_of_elaboration
ovm_test_top.t_env.ag1 [ovm_test_top.t_env.ag1] End_of_elaboration
ovm_test_top.t_env.ag2.drv [ovm_test_top.t_env.ag2.drv] End_of_elaboration
ovm_test_top.t_env.ag2.mon [ovm_test_top.t_env.ag2.mon] End_of_elaboration
ovm_test_top.t_env.ag2 [ovm_test_top.t_env.ag2] End_of_elaboration
ovm_test_top.t_env [ovm_test_top.t_env] End_of_elaboration
ovm_test_top [ovm_test_top] End_of_elaboration
----------------------------------------------------------------------
Name                     Type                Size                Value
----------------------------------------------------------------------
ovm_test_top             test1               -          ovm_test_top@2
  t_env                  env                 -                 t_env@4
    ag1                  agent               -                   ag1@6
      drv                driver              -                  drv@12
        rsp_port         ovm_analysis_port   -             rsp_port@16
        sqr_pull_port    ovm_seq_item_pull_+ -        sqr_pull_port@14
      mon                monitor             -                  mon@10
    ag2                  agent               -                   ag2@8
      drv                driver              -                  drv@20
        rsp_port         ovm_analysis_port   -             rsp_port@24
        sqr_pull_port    ovm_seq_item_pull_+ -        sqr_pull_port@22
      mon                monitor             -                  mon@18

ovm_test_top.t_env.ag1.drv[ovm_test_top.t_env.ag1.drv]Start_of_simulation
ovm_test_top.t_env.ag1.mon[ovm_test_top.t_env.ag1.mon]Start_of_simulation
ovm_test_top.t_env.ag1[ovm_test_top.t_env.ag1]Start_of_simulation
ovm_test_top.t_env.ag2.drv[ovm_test_top.t_env.ag2.drv]Start_of_simulation
ovm_test_top.t_env.ag2.mon[ovm_test_top.t_env.ag2.mon]Start_of_simulatio

..

http://testbench.in/OT_02_OVM_TESTBENCH.html[9/26/2012 2:26:24 PM]


WWW.TESTBENCH.IN - OVM Tutorial

..
..
..

Observe the above log report:

1)Build method was called in top-down fashion. Look at the following part of message.

ovm_test_top.t_env [ovm_test_top.t_env] Build


ovm_test_top.t_env.ag1 [ovm_test_top.t_env.ag1] Build
ovm_test_top.t_env.ag1.drv [ovm_test_top.t_env.ag1.drv] Build
ovm_test_top.t_env.ag1.mon [ovm_test_top.t_env.ag1.mon] Build
ovm_test_top.t_env.ag2 [ovm_test_top.t_env.ag2] Build
ovm_test_top.t_env.ag2.drv [ovm_test_top.t_env.ag2.drv] Build
ovm_test_top.t_env.ag2.mon [ovm_test_top.t_env.ag2.mon] Build

2)Connect method was called in bottopm up fashion. Look at the below part of log
file,

ovm_test_top.t_env.ag1.drv [ovm_test_top.t_env.ag1.drv] Connect


ovm_test_top.t_env.ag1.mon [ovm_test_top.t_env.ag1.mon] Connect
ovm_test_top.t_env.ag1 [ovm_test_top.t_env.ag1] Connect
ovm_test_top.t_env.ag2.drv [ovm_test_top.t_env.ag2.drv] Connect
ovm_test_top.t_env.ag2.mon [ovm_test_top.t_env.ag2.mon] Connect
ovm_test_top.t_env.ag2 [ovm_test_top.t_env.ag2] Connect
ovm_test_top.t_env [ovm_test_top.t_env] Connect

3)Following part of log file shows the testcase topology.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OT_02_OVM_TESTBENCH.html[9/26/2012 2:26:24 PM]


WWW.TESTBENCH.IN - OVM Tutorial

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS OVM REPORTING Index


Introduction
SystemVerilog The ovm_report_object provides an interface to the OVM reporting facility.  Through Ovm Testbench
Verification this interface, components issue the various messages with different severity levels Ovm Reporting
that occur during simulation. Users can configure what actions are taken and what Ovm Transaction
Constructs file(s) are output for individual messages from a particular component or for all Ovm Factory
Interface messages from all components in the environment.   Ovm Sequence 1
Ovm Sequence 2
OOPS Ovm Sequence 3
A report consists of an id string, severity, verbosity level, and the textual message
Randomization itself.   If the verbosity level of a report is greater than the configured maximum Ovm Sequence 4
verbosity level of its report object, it is ignored. Ovm Sequence 5
Functional Coverage Ovm Sequence 6
Assertion Reporting Methods: Ovm Configuration
DPI Report a Bug or Comment
Following are the primary reporting methods in the OVM.
UVM Tutorial on This section - Your
virtual function void ovm_report_info input is what keeps
VMM Tutorial
  (string id,string message,int verbosity=OVM_MEDIUM,string filename="",int line=0) Testbench.in improving
OVM Tutorial with time!
Easy Labs : SV virtual function void ovm_report_warning
  (string id,string message,int verbosity=OVM_MEDIUM,string filename="",int line=0)
Easy Labs : UVM
Easy Labs : OVM virtual function void ovm_report_error
  (string id,string message,int verbosity=OVM_LOW,   string filename="",int line=0)
Easy Labs : VMM
AVM Switch TB virtual function void ovm_report_fatal
  (string id,string message,int verbosity=OVM_NONE,  string filename="",int line=0)
VMM Ethernet sample
Arguments description:

Verilog id -- a unique id to form a group of messages.


Verification
Verilog Switch TB
message -- The message text

Basic Constructs verbosity -- the verbosity of the message, indicating its relative importance. If this
number is less than or equal to the effective verbosity level, then the report is issued,
subject to the configured action and file descriptor settings.  
OpenVera
Constructs filename/line -- If required to print filename and line number from where the
message is issued, use macros, `__FILE__ and `__LINE__.
Switch TB
RVM Switch TB
Actions:
RVM Ethernet sample
These methods associate the specified action or actions with reports of the
givenseverity, id, or severity-id pair.
Specman E
Following are the actions defined:
Interview Questions
OVM_NO_ACTION -- Do nothing
OVM_DISPLAY -- Display report to standard output
OVM_LOG  -- Write to a file
OVM_COUNT -- Count up to a max_quit_count value before exiting
OVM_EXIT -- Terminates simulation immediately
OVM_CALL_HOOK -- Callback the hook method .

Configuration:

http://testbench.in/OT_03_OVM_REPORTING.html[9/26/2012 2:26:32 PM]


WWW.TESTBENCH.IN - OVM Tutorial

Using these methods, user can set the verbosity levels and set actions.

function void set_report_verbosity_level
     (int verbosity_level)
function void set_report_severity_action
     (ovm_severity severity,ovm_action action)
function void set_report_id_action
     (string id,ovm_action action)
function void set_report_severity_id_action
     (ovm_severity severity,string id,ovm_action action) 

Example

Lets see an example:

In the following example, messages from rpting::run() method are of different


verbosity level. In the top module, 3 objects of rpting are created and different
verbosity levels are set using set_report_verbosity_level() method.  

`include "ovm.svh"
 import ovm_pkg::*;

class rpting extends ovm_threaded_component;

  `ovm_component_utils(rpting)
 
  function new(string name,ovm_component parent);
    super.new(name, parent);
  endfunction

  task run();

    ovm_report_info(get_full_name(),
      "Info Message : Verbo lvl - OVM_NONE  ",OVM_NONE,`__FILE__,`__LINE__);

http://testbench.in/OT_03_OVM_REPORTING.html[9/26/2012 2:26:32 PM]


WWW.TESTBENCH.IN - OVM Tutorial

    ovm_report_info(get_full_name(),
      "Info Message : Verbo lvl - OVM_LOW   ",OVM_LOW);

    ovm_report_info(get_full_name(),
      "Info Message : Verbo lvl - 150       ",150);

    ovm_report_info(get_full_name(),
      "Info Message : Verbo lvl - OVM_MEDIUM",OVM_MEDIUM);

    ovm_report_warning(get_full_name(),
      "Warning Messgae from rpting",OVM_LOW);

    ovm_report_error(get_full_name(),
      "Error Message from rpting \n\n",OVM_LOG);
  endtask

endclass

module top;

 rpting rpt1;
 rpting rpt2;
 rpting rpt3;

 initial begin
   rpt1 = new("rpt1",null);
   rpt2 = new("rpt2",null);
   rpt3 = new("rpt3",null);

   rpt1.set_report_verbosity_level(OVM_MEDIUM);
   rpt2.set_report_verbosity_level(OVM_LOW);
   rpt3.set_report_verbosity_level(OVM_NONE);
   run_test();

 end
endmodule

Download the source code

ovm_reporting.tar
Browse the code in ovm_reporting.tar

Command to run the simulation

your_tool_simulation_command +path_to_ovm_pkg ovm_log_example.sv

Log file:

OVM_INFO reporting.sv(13)@0:rpt1[rpt1]Info Message:Verbo lvl - OVM_NONE  


OVM_INFO @0:rpt1[rpt1] Info Message : Verbo lvl - OVM_LOW  
OVM_INFO @0:rpt1[rpt1] Info Message : Verbo lvl - 150      
OVM_INFO @0:rpt1[rpt1] Info Message : Verbo lvl - OVM_MEDIUM
OVM_WARNIN@0:rpt[rpt1] Warning Messgae from rpting
OVM_ERROR @0:rpt1[rpt1] Error Message from rpting

OVM_INFOreporting.sv(13)@0:rpt2[rpt2]Info Message:Verbo lvl - OVM_NONE  


OVM_INFO@ 0:rpt2[rpt2] Info Message : Verbo lvl - OVM_LOW  
OVM_WARNING@0:rpt2[rpt2] Warning Messgae from rpting
OVM_ERROR@0:rpt2[rpt2] Error Message from rpting

OVM_INFOreporting.sv(13)@0:rpt3[rpt3]Info Message:Verbo lvl - OVM_NONE  


OVM_ERROR @ 9200 [TIMOUT] Watchdog timeout of '23f0' expired.

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/OT_03_OVM_REPORTING.html[9/26/2012 2:26:32 PM]


WWW.TESTBENCH.IN - OVM Tutorial

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OT_03_OVM_REPORTING.html[9/26/2012 2:26:32 PM]


WWW.TESTBENCH.IN - OVM Tutorial

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS OVM TRANSACTION Index


Introduction
SystemVerilog Ovm Testbench
Verification A transaction is data item which is eventually or directly processed by the DUT. The Ovm Reporting
packets, instructions, pixels are data items. In ovm, transactions are extended from Ovm Transaction
Constructs ovm_transactions class or  ovm_sequence_item class. Generally transactions are Ovm Factory
Interface extended from ovm_transaction  if randomization is not done in sequence and Ovm Sequence 1
transactions are extended from ovm_sequence_item if the randomization is done in Ovm Sequence 2
OOPS Ovm Sequence 3
sequence. In this section, we will see ovm_transaction only, ovm_sequence_item will
Randomization be addressed in another section. Ovm Sequence 4
Ovm Sequence 5
Functional Coverage Ovm Sequence 6
Assertion Example of a transaction: Ovm Configuration
DPI Report a Bug or Comment
class Packet extends ovm_transaction;
UVM Tutorial     rand bit [7:0] da; on This section - Your
    rand bit [7:0] sa; input is what keeps
VMM Tutorial
    rand bit [7:0] length; Testbench.in improving
OVM Tutorial     rand bit [7:0] data[]; with time!
Easy Labs : SV     rand byte fcs;
endclass
Easy Labs : UVM
Easy Labs : OVM
Core Utilities:
Easy Labs : VMM
AVM Switch TB ovm_transaction class is extended from ovm_object.  Ovm_transaction adds more
features line transaction recording , transaction id  and timings of the transaction.
VMM Ethernet sample
The methods used to model, transform or operate on transactions like print, copying,
cloning, comparing, recording, packing and unpacking are already defined in
Verilog ovm_object.
Verification
Verilog Switch TB
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

FIG:  OVM OBJECT UTILITIES

http://testbench.in/OT_04_OVM_TRANSACTION.html[9/26/2012 2:26:41 PM]


WWW.TESTBENCH.IN - OVM Tutorial

User Defined Implementations:

User should define these methods in the transaction using do_<method_name> and
call them using <method_name>.  Following table shows calling methods and user-
defined hook do_<method_name> methods.  Clone and create methods, does not
use  hook methods concepts.

Shorthand Macros:

Using the field automation concept of ovm, all the above defines methods can be
defined automatically.
To use these field automation macros, first declare all the data fields, then place the
field automation macros between the `ovm_object_utils_begin and
`ovm_object_utils_end macros.

Example of field automation macros:

class Packet extends ovm_transaction;
  
   rand bit [7:0] da;
   rand bit [7:0] sa;
   rand bit [7:0] length;
   rand bit [7:0] data[];
   rand byte      fcs;

    `ovm_object_utils_begin(Packet)
       `ovm_field_int(da, OVM_ALL_ON|OVM_NOPACK)
       `ovm_field_int(sa, OVM_ALL_ON|OVM_NOPACK)
       `ovm_field_int(length, OVM_ALL_ON|OVM_NOPACK)
       `ovm_field_array_int(data, OVM_ALL_ON|OVM_NOPACK)
       `ovm_field_int(fcs, OVM_ALL_ON|OVM_NOPACK)
    `ovm_object_utils_end

endclass.

http://testbench.in/OT_04_OVM_TRANSACTION.html[9/26/2012 2:26:41 PM]


WWW.TESTBENCH.IN - OVM Tutorial

For most of the data types in systemverilog, ovm defined corresponding field
automation macros. Following table shows all the field automation macros.

Each `ovm_field_* macro has at least two arguments: ARG and FLAG.
ARG is the instance name of the variable and FLAG is used to control the field usage in
core utilities operation.

Following table shows ovm field automation flags:

http://testbench.in/OT_04_OVM_TRANSACTION.html[9/26/2012 2:26:41 PM]


WWW.TESTBENCH.IN - OVM Tutorial

By default, FLAG is set to OVM_ALL_ON. All these flags can be ored. Using NO_* flags,
can turn of particular field usage in a paerticuler method. NO_* flags takes
precedency over other flags.

Example of Flags:

    `ovm_field_int(da, OVM_ALL_ON|OVM_NOPACK)

The above macro will use the field "da" in all utilities methods except Packing and
unpacking methods.

Lets see a example:

In the following example, all the utility methods are defined using field automation
macros except Packing and unpacking methods.  Packing and unpacking methods are
done  in do_pack() amd do_unpack() method.

 `include "ovm.svh"
 import ovm_pkg::*;

//Define the enumerated types for packet types


typedef enum { GOOD_FCS, BAD_FCS } fcs_kind_t;

class Packet extends ovm_transaction;

    rand fcs_kind_t     fcs_kind;
    
    rand bit [7:0] length;
    rand bit [7:0] da;
    rand bit [7:0] sa;
    rand bit [7:0] data[];
    rand byte fcs;
    
    constraint payload_size_c { data.size inside { [1 : 6]};}
    
    constraint length_c {  length == data.size; } 
                    
    constraint solve_size_length { solve  data.size before length; }
    
    function new(string name = "");
         super.new(name);
    endfunction : new
    
    function void post_randomize();
         if(fcs_kind == GOOD_FCS)
             fcs = 8'b0;

http://testbench.in/OT_04_OVM_TRANSACTION.html[9/26/2012 2:26:41 PM]


WWW.TESTBENCH.IN - OVM Tutorial

         else
            fcs = 8'b1;
         fcs = cal_fcs();
    endfunction : post_randomize
    
    ///// method to calculate the fcs /////
    virtual function byte cal_fcs;
         integer i;
         byte result ;
         result = 0;
         result = result ^ da;
         result = result ^ sa;
         result = result ^ length;
         for (i = 0;i< data.size;i++)
         result = result ^ data[i];
         result = fcs ^ result;
         return result;
    endfunction : cal_fcs
    
    `ovm_object_utils_begin(Packet)
       `ovm_field_int(da, OVM_ALL_ON|OVM_NOPACK)
       `ovm_field_int(sa, OVM_ALL_ON|OVM_NOPACK)
       `ovm_field_int(length, OVM_ALL_ON|OVM_NOPACK)
       `ovm_field_array_int(data, OVM_ALL_ON|OVM_NOPACK)
       `ovm_field_int(fcs, OVM_ALL_ON|OVM_NOPACK)
    `ovm_object_utils_end
    
    function void do_pack(ovm_packer packer);
        super.do_pack(packer);
        packer.pack_field_int(da,$bits(da));
        packer.pack_field_int(sa,$bits(sa));
        packer.pack_field_int(length,$bits(length));
        foreach(data[i])
          packer.pack_field_int(data[i],8);
        packer.pack_field_int(fcs,$bits(fcs));
    endfunction : do_pack
    
    function void do_unpack(ovm_packer packer);
        int sz;
        super.do_pack(packer);
    
        da = packer.unpack_field_int($bits(da));
        sa = packer.unpack_field_int($bits(sa));
        length = packer.unpack_field_int($bits(length));
        
        data.delete();
        data = new[length];
        foreach(data[i])
          data[i] = packer.unpack_field_int(8);
        fcs = packer.unpack_field_int($bits(fcs));
    endfunction : do_unpack

endclass : Packet

/////////////////////////////////////////////////////////
////    Test to check the packet implementation      ////
/////////////////////////////////////////////////////////
module test;

    Packet pkt1 = new("pkt1");


    Packet pkt2 = new("pkt2");
    byte unsigned pkdbytes[];

    initial
    repeat(10)
       if(pkt1.randomize)
       begin
          $display(" Randomization Sucessesfull.");
          pkt1.print();
          ovm_default_packer.use_metadata = 1;    
          void'(pkt1.pack_bytes(pkdbytes));
          $display("Size of pkd bits %d",pkdbytes.size());
          pkt2.unpack_bytes(pkdbytes);

http://testbench.in/OT_04_OVM_TRANSACTION.html[9/26/2012 2:26:41 PM]


WWW.TESTBENCH.IN - OVM Tutorial

          pkt2.print();
          if(pkt2.compare(pkt1))
              $display(" Packing,Unpacking and compare worked");
          else
              $display(" *** Something went wrong in Packing or Unpacking or compare ***
\n \n");
       end
       else
       $display(" *** Randomization Failed ***");
    
endmodule

Download the source code

ovm_transaction.tar
Browse the code in ovm_transaction.tar

Command to run the simulation

your_tool_simulation_command +path_to_ovm_pkg -packet.sv

Log report:

 Randomization Sucessesfull.
-------------------------------------------------------------------
---
Name                     Type                Size                Value
-------------------------------------------------------------------
---
pkt1                     Packet              -                  pkt1@3
  da                     integral            8                    'h1d
  sa                     integral            8                    'h26
  length                 integral            8                     'h5
  data                   da(integral)        5                       -
    [0]                  integral            8                    'hb1
    [1]                  integral            8                    'h3f
    [2]                  integral            8                    'h9e
    [3]                  integral            8                    'h38
    [4]                  integral            8                    'h8d
  fcs                    integral            8                    'h9b
-------------------------------------------------------------------
---
Size of pkd bits           9
-------------------------------------------------------------------
---
Name                     Type                Size                Value
-------------------------------------------------------------------
---
pkt2                     Packet              -                  pkt2@5
  da                     integral            8                    'h1d
  sa                     integral            8                    'h26
  length                 integral            8                     'h5
  data                   da(integral)        5                       -
    [0]                  integral            8                    'hb1
    [1]                  integral            8                    'h3f
    [2]                  integral            8                    'h9e
    [3]                  integral            8                    'h38
    [4]                  integral            8                    'h8d
  fcs                    integral            8                    'h9b
-------------------------------------------------------------------
---
 Packing,Unpacking and compare worked

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/OT_04_OVM_TRANSACTION.html[9/26/2012 2:26:41 PM]


WWW.TESTBENCH.IN - OVM Tutorial

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OT_04_OVM_TRANSACTION.html[9/26/2012 2:26:41 PM]


WWW.TESTBENCH.IN - OVM Tutorial

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS OVM FACTORY Index


Introduction
SystemVerilog Ovm Testbench
Verification The factory pattern is an well known object-oriented design pattern. The factory Ovm Reporting
method design pattern defining a separate method for creating the objects. ,  whose Ovm Transaction
Constructs subclasses can then override to specify the derived type of object that will be Ovm Factory
Interface created. Ovm Sequence 1
Ovm Sequence 2
OOPS Ovm Sequence 3
Using this method, objects are constructed dynamically based on the specification
Randomization type of the object. User can alter the behavior of the pre-build code without Ovm Sequence 4
modifying the code. From the testcase, user from environment or testcase can replace Ovm Sequence 5
Functional Coverage Ovm Sequence 6
any object which is at any hierarchy level with the user defined object.
Assertion Ovm Configuration
DPI For example: In your environment, you have a driver component. You would like the
extend the driver component for error injection scenario. After defining the extended Report a Bug or Comment
UVM Tutorial driver class  with error injection,  how will you  replace the base driver component on This section - Your
which is deep in the hierarchy of your environment ?   Using hierarchical path, you input is what keeps
VMM Tutorial
could replace the driver object with the extended driver. This could not be easy if Testbench.in improving
OVM Tutorial there are many driver objects. Then you should also take care of its connections with with time!
Easy Labs : SV the other components of testbenchs like scoreboard etc.
Easy Labs : UVM One more example: In your Ethernet verification environment, you have different
Easy Labs : OVM drivers to support different interfaces for 10mbps,100mps and 1G. Now you want to
reuse the same environment for 10G verification.  Inside somewhere deep in the
Easy Labs : VMM hierarchy, while building the components, as a driver components ,your current
AVM Switch TB environment can only select 10mmps/100mps/1G drivers using configuration
settings.  How to add one more driver to the current drivers list of drivers so that
VMM Ethernet sample from the testcase you could configure the environment to work for 10G.  

Using the ovm fatroy, it is very easy to solve the above two requirements.  Only classs
Verilog extended from ovm_object and ovm_component are supported for this.
Verification
There are three basic steps to be followed for using ovm factory.
Verilog Switch TB
Basic Constructs 1) Registration
2) Construction
3) Overriding
OpenVera
Constructs
The factory makes it is possible to override the type of ovm component /object  or
instance of a ovm component/object  in2 ways. They are based on ovm
Switch TB component/object type or  ovm compoenent/object  name.  
RVM Switch TB
Registration:
RVM Ethernet sample
While defining a class , its type has to be registered with the ovm factory. To do this
job easier, ovm has predefined macros.
Specman E
Interview Questions `ovm_component_utils(class_type_name)
`ovm_component_param_utils(class_type_name #(params))
`ovm_object_utils(class_type_name)
`ovm_object_param_utils(class_type_name #(params))

For ovm_*_param_utils are used for parameterized classes and other two macros for
non-parameterized class.  Registration is required for name-based overriding , it is
not required for type-based overriding.

EXAMPLE: Example of above macros

http://testbench.in/OT_05_OVM_FACTORY.html[9/26/2012 2:26:49 PM]


WWW.TESTBENCH.IN - OVM Tutorial

class packet extends ovm_object;
  `ovm_object_utils(packet)
endclass

class packet #(type T=int, int mode=0) extends ovm_object;
  `ovm_object_param_utils(packet #(T,mode))
endclass

class driver extends ovm_component;
  `ovm_component_utils(driver)
endclass

class monitor #(type T=int, int mode=0) extends ovm_component;
  `ovm_component_param_utils(driver#(T,mode))
endclass

Construction:

To construct a ovm based component or ovm based objects, static method create()
should be used. This function constructs the appropriate object based on the
overrides and constructs the object and returns it. So while constructing the ovm
based components or ovm based objects , do not use new() constructor.

Syntax :

static function T create(string name,    
                         ovm_component parent,  
                         string context = " ")

The Create() function returns an instance of the component type, T, represented by


this proxy, subject to any factory overrides based on the context provided by the
parents full name.  The context argument, if supplied, supersedes the parents
context.  The new instance will have the given leaf name and parent.

EXAMPLE:
class_type object_name;

object_name = class_type::type_id::creat("object_name",this);

For ovm_object based classes, doesnt need the parent handle as second argument.

Overriding:

If required, user could override the registered classes or objects. User can override
based of name string or class-type.  

There are 4 methods defined for overriding:

function void set_inst_override_by_type
       (ovm_object_wrapper original_type,
        ovm_object_wrapper override_type,
        string full_inst_path )

The above method is used to override the object instances of "original_type" with
"override_type" . "override_type" is extended from"original_type".

function void set_inst_override_by_name
       (string original_type_name,
        string override_type_name,
        string full_inst_path )

http://testbench.in/OT_05_OVM_FACTORY.html[9/26/2012 2:26:49 PM]


WWW.TESTBENCH.IN - OVM Tutorial

Original_type_name and override_type_name are the class names which are registered
in the factory. All the instances of objects with name "Original_type_name" will be
overriden with objects of name "override_type_name" using
set_inst_override_by_name() method.

function void set_type_override_by_type
       (ovm_object_wrapper original_type,    
        ovm_object_wrapper override_type,    
        bit replace = 1 )

Using the above method, request to create an object of  original_type can be


overriden with override_type.

function void set_type_override_by_name
      (string original_type_name,    
       string override_type_name,    
       bit replace = 1)

Using the above method, request to create an object of  original_type_name can be


overriden with override_type_name.

When multiple overrides are done , then using the argument "replace" , we can
control whether to override the previous override or not. If argument "replace" is 1,
then previous overrides will be replaced otherwise, previous overrides will remain.  

print() method, prints the state of the ovm_factory, registered types, instance
overrides, and type overrides.

Now we will see a complete example. This example is based on the environment build
in topic OVM TESTBENCH . Refer to that section for more information about this
example.

Lets look at the 3 steps which I discussed above using the example defined in OVM
TESTBENCH

1) Registration

In all the class, you can see the macro  `ovm_component_utils(type_name)

2) Construction

In file agant.sv file,  monitor and driver are constructed using create() method.

mon = monitor::type_id::create("mon",this);
drv = driver::type_id::create("drv",this);

3)In this example, a one testcase is already developed in topic OVM_TESTBENCH.


There are no over rides in this test case.

Topology of this test environment is shown below.

http://testbench.in/OT_05_OVM_FACTORY.html[9/26/2012 2:26:49 PM]


WWW.TESTBENCH.IN - OVM Tutorial

In this example, there is one driver class and one monitor class.  In this testcase , By
extending driver class , we will define driver_2 class and by extending monitor class,
we will define monitor_2 class.

From the testcase , Using set_type_override_by_type, we will override driver with


driver_2 and Using set_type_override_by_name, we will override monitor with
monitor_2.

To know about the overrides which are done, call print_all_overrides() method of
factory class.

class driver_2 extends driver;

   `ovm_component_utils(driver_2)

    function new(string name, ovm_component parent);
        super.new(name, parent);
    endfunction

endclass

class monitor_2 extends monitor;

   `ovm_component_utils(monitor_2)

    function new(string name, ovm_component parent);
        super.new(name, parent);
    endfunction

endclass

class test_factory extends ovm_test;

   `ovm_component_utils(test_factory)
    env t_env;
 
    function new (string name="test1", ovm_component parent=null);
        super.new (name, parent);

        factory.set_type_override_by_type(driver::get_type(),driver_2::get_type(),"*");
        factory.set_type_override_by_name("monitor","monitor_2","*");
        factory.print_all_overrides();
        t_env = new("t_env",this);
    endfunction : new 

http://testbench.in/OT_05_OVM_FACTORY.html[9/26/2012 2:26:49 PM]


WWW.TESTBENCH.IN - OVM Tutorial

    function void end_of_elaboration();
        ovm_report_info(get_full_name(),"End_of_elaboration", OVM_LOG);
        print();
    endfunction : end_of_elaboration
 
    task run ();
        #1000;
        global_stop_request();
    endtask : run

endclass

Download the example:

ovm_factory.tar
Browse the code in ovm_factory.tar

Command to simulate

Command to run the example with the testcase which is defined above:
Your_tool_simulation_command +incdir+path_to_ovm -f filelist
+OVM_TESTNAME=test_factory

Method factory.print_all_overrides() displayed all the overrides as shown below in the


log file.

#### Factory Configuration (*)

No instance overrides are registered with this factory


Type Overrides:

  Requested Type  Override Type


  --------------  -------------
  driver          driver_2
  monitor         monitor_2

In the below text printed by print_topology() method ,we can see overridden driver
and monitor.  

-------------------------------------------------------------------
---
Name                     Type                Size                Value
-------------------------------------------------------------------
---
ovm_test_top             test_factory        -          ovm_test_top@2
  t_env                  env                 -                 t_env@4
    ag1                  agent               -                   ag1@6
      drv                driver_2            -                  drv@12
        rsp_port         ovm_analysis_port   -             rsp_port@16
        sqr_pull_port    ovm_seq_item_pull_+ -        sqr_pull_port@14
      mon                monitor_2           -                  mon@10
    ag2                  agent               -                   ag2@8
      drv                driver_2            -                  drv@20
        rsp_port         ovm_analysis_port   -             rsp_port@24
        sqr_pull_port    ovm_seq_item_pull_+ -        sqr_pull_port@22
      mon                monitor_2           -                  mon@18
-------------------------------------------------------------------
---

In the below text printed by print_topology() method ,with testcase test1 which does
note have overrides.

Command to run this example with test1 is  


your_tool_simulation_command +incdir+path_to_ovm -f filelist +OVM_TESTNAME=test1

-------------------------------------------------------------------
---
Name                     Type                Size                Value
-------------------------------------------------------------------
---
ovm_test_top             test1               -          ovm_test_top@2

http://testbench.in/OT_05_OVM_FACTORY.html[9/26/2012 2:26:49 PM]


WWW.TESTBENCH.IN - OVM Tutorial

  t_env                  env                 -                 t_env@4


    ag1                  agent               -                   ag1@6
      drv                driver              -                  drv@12
        rsp_port         ovm_analysis_port   -             rsp_port@16
        sqr_pull_port    ovm_seq_item_pull_+ -        sqr_pull_port@14
      mon                monitor             -                  mon@10
    ag2                  agent               -                   ag2@8
      drv                driver              -                  drv@20
        rsp_port         ovm_analysis_port   -             rsp_port@24
        sqr_pull_port    ovm_seq_item_pull_+ -        sqr_pull_port@22
      mon                monitor             -                  mon@18
-------------------------------------------------------------------
---

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OT_05_OVM_FACTORY.html[9/26/2012 2:26:49 PM]


WWW.TESTBENCH.IN - OVM Tutorial

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS OVM SEQUENCE 1 Index


Introduction
SystemVerilog Introduction Ovm Testbench
Verification Ovm Reporting
Ovm Transaction
Constructs A sequence is a series of transaction.  User can define the complex stimulus. Ovm Factory
Interface sequences can be reused, extended, randomized, and combined sequentially and Ovm Sequence 1
hierarchically in various ways. Ovm Sequence 2
OOPS Ovm Sequence 3
 
Randomization For example, for a processor, lets say PUSH_A,PUSH_B,ADD,SUB,MUL,DIV and POP_C Ovm Sequence 4
are the instructions. If the instructions are generated randomly, then to excursing a Ovm Sequence 5
Functional Coverage Ovm Sequence 6
meaningful operation like "adding 2 variables" which requires a series of transaction
Assertion "PUSH_A  PUSH_B  ADD  POP_C " will take longer time. By defining these series of Ovm Configuration
DPI "PUSH_A  PUSH_B  ADD  POP_C ", it would be easy to exercise the DUT.
Report a Bug or Comment
UVM Tutorial Advantages of ovm sequences : on This section - Your
Sequences can be reused. input is what keeps
VMM Tutorial
Testbench.in improving
Stimulus generation is independent of testbench.
OVM Tutorial with time!
Easy to control the generation of transaction.
Easy Labs : SV Sequences can be combined sequentially and hierarchically.  
Easy Labs : UVM
A complete sequence generation requires following 4 classes.
Easy Labs : OVM 1- Sequence item.
Easy Labs : VMM 2- Sequence
3- Sequencer
AVM Switch TB 4- Driver
VMM Ethernet sample

Ovm_sequence_item :
Verilog User has to define a transaction by extending
ovm_sequence_item.  ovm_sequence_item class provides the basic functionality for
Verification objects, both sequence items and sequences, to operate in the sequence mechanism.
Verilog Switch TB For more information about  ovm_sequence_item  Refer to link  
Basic Constructs
OVM_TRANSACTION  

Ovm_sequence:
OpenVera User should extend ovm_sequence class and define the construction of sequence of
Constructs transactions. These transactions can be directed, constrained randomized or fully
randomized. The ovm_sequence class provides the interfaces necessary in order to
Switch TB
create streams of sequence items and/or other sequences.  
RVM Switch TB
RVM Ethernet sample
    virtual class ovm_sequence #(
       type REQ  =  ovm_sequence_item,
       type RSP  =  REQ
Specman E     )
Interview Questions
Ovm_sequencer:
Ovm_sequencer is responsible for the coordination between sequence and driver.
Sequencer sends the transaction to driver and gets the response from the driver. The
response transaction from the driver is optional. When multiple sequences are running
in parallel, then sequencer is responsible for arbitrating between the parallel
sequences. There are two types of sequencers : ovm_sequencer and
ovm_push_sequencer

http://testbench.in/OT_06_OVM_SEQUENCE_1.html[9/26/2012 2:26:58 PM]


WWW.TESTBENCH.IN - OVM Tutorial

    class ovm_sequencer #(
      type  REQ  =  ovm_sequence_item,
      type  RSP  =  REQ
    )
    
    class ovm_push_sequencer #(
      type  REQ  =  ovm_sequence_item,
      type  RSP  =  REQ
    )

Ovm driver:
User should extend ovm_driver class to define driver component. ovm driver is a
component that initiate requests for new transactions and drives it to lower level
components. There are two types of drivers: ovm_driver and ovm_push_driver.

    class ovm_driver #(
      type  REQ  =  ovm_sequence_item,
      type  RSP  =  REQ
    ) 
    
    class ovm_push_driver #(
      type  REQ  =  ovm_sequence_item,
      type  RSP  =  REQ
    )

In pull mode , ovm_sequencer is connected to ovm_driver , in push


mode  ovm_push_sequencer is connectd to ovm_push_driver.  

Ovm_sequencer and ovm_driver are parameterized components with request and


response transaction types. REQ and RSP types by default are ovm_sequence_type
types. User can specify REQ and RSP of different transaction types. If user specifies
only REQ type, then RSP will be REQ type.

Sequence And Driver Communication:

The above image shows how a transaction from a sequence is sent to driver and the
response from the driver is sent to sequencer.  There are multiple methods called
during this operation.

First when the body() method is called

http://testbench.in/OT_06_OVM_SEQUENCE_1.html[9/26/2012 2:26:58 PM]


WWW.TESTBENCH.IN - OVM Tutorial

1) A transaction is created using "create()" method. If a transaction is created using


"create()" method, then it can be overridden if required using ovm factory.

2) After a transaction is created, wait_for_grant() method is called. This method is


blocking method.

3) In the run task of the driver, when "seq_item_port.get_next_item()" is called, then


the sequencer un blocks wait_for_grant() method. If more than one sequence is
getting executed by sequencer, then based on arbitration rules, un blocks the
wait_for_grant() method.

4) After the wait_for_grant() un blocks, then transaction can be randomized, or its


properties can be filled directly. Then using the send_request() method, send the
transaction to the driver.

5) After calling the send_request() method, "wait_for_item_done()" method is called.


This is a blocking method and execution gets blocks at this method call.

6) The transaction which is sent from sequence , in the driver this transaction is
available as "seq_item_port.get_next_item(req)" method argument. Then driver can
drive this transaction to bus or lower level.

7) Once the driver operations are completed, then  by calling


"seq_item_port.put(rsp)", wait_for_item_done() method of sequence gest unblocked.
Using get_responce(res), the response transaction from driver is taken by sequence
and processes it.

After this step, again the steps 1 to 7 are repeated five times.

If a response from driver is not required, then steps 5,6,7 can be skipped and
item_done() method from driver should be called as shown in above image.

Simple Example

Lest write an example: This is a simple example of  processor instruction. Various


instructions which are supported by the processor are
PUSH_A,PUSH_B,ADD,SUB,MUL,DIV and POP_C.

Sequence Item

1) Extend ovm_sequence_item and define instruction class.

    class instruction extends ovm_sequence_item;

2) Define the instruction as enumerated types and declare a variable of instruction


enumerated type.

http://testbench.in/OT_06_OVM_SEQUENCE_1.html[9/26/2012 2:26:58 PM]


WWW.TESTBENCH.IN - OVM Tutorial

    typedef enum {PUSH_A,PUSH_B,ADD,SUB,MUL,DIV,POP_C} inst_t; 
    rand inst_t inst;

3) Define operational method using ovm_field_* macros.

   `ovm_object_utils_begin(instruction)
     `ovm_field_enum(inst_t,inst, OVM_ALL_ON)
   `ovm_object_utils_end

4) Define the constructor.

   function new (string name = "instruction");
      super.new(name);
   endfunction 

Sequence item code:


class instruction extends ovm_sequence_item;
  typedef enum {PUSH_A,PUSH_B,ADD,SUB,MUL,DIV,POP_C} inst_t; 
  rand inst_t inst;

  `ovm_object_utils_begin(instruction)
    `ovm_field_enum(inst_t,inst, OVM_ALL_ON)
  `ovm_object_utils_end

  function new (string name = "instruction");
    super.new(name);
  endfunction 

endclass

Sequence

We will define a operation addition using ovm_sequence. The instruction sequence


should be "PUSH A  PUSH B  ADD  POP C".
 
1) Define a sequence by extending ovm_sequence. Set REQ parameter to "instruction"
type.

    class operation_addition extends ovm_sequence #(instruction);

2) Define the constructor.

    function new(string name="operation_addition");
       super.new(name);
    endfunction

3) Lets name the sequencer which we will develop is "instruction_sequencer".


Using the `ovm_sequence_utils macro, register the "operation_addition" sequence
with "instruction_sequencer" sequencer. This macro adds the sequence to the
sequencer list. This macro will also register the sequence for factory overrides.

    `ovm_sequence_utils(operation_addition, instruction_sequencer)    

4)
In the body() method, first call wait_for_grant(), then construct a transaction and set
the instruction enum to PUSH_A . Then send the transaction to driver using
send_request() method. Then call the wait_for_item_done() method. Repeat the
above steps for other instructions PUSH_B, ADD and POP_C.
 
For construction of a transaction, we will use the create() method.

  virtual task body();
    req = instruction::type_id::create("req");
      wait_for_grant();
      assert(req.randomize() with {
         inst == instruction::PUSH_A;
      });
      send_request(req);
      wait_for_item_done();
      //get_response(res); This is optional. Not using in this example.

      req = instruction::type_id::create("req");
      wait_for_grant();

http://testbench.in/OT_06_OVM_SEQUENCE_1.html[9/26/2012 2:26:58 PM]


WWW.TESTBENCH.IN - OVM Tutorial

      req.inst = instruction::PUSH_B;
      send_request(req);
      wait_for_item_done();
      //get_response(res);

      req = instruction::type_id::create("req");
      wait_for_grant();
      req.inst = instruction::ADD;
      send_request(req);
      wait_for_item_done();
      //get_response(res);

      req = instruction::type_id::create("req");
      wait_for_grant();
      req.inst = instruction::POP_C;
      send_request(req);
      wait_for_item_done();
      //get_response(res);
  endtask

Sequence code

class operation_addition extends ovm_sequence #(instruction);

  instruction req;
 
  function new(string name="operation_addition");
    super.new(name);
  endfunction
  
  `ovm_sequence_utils(operation_addition, instruction_sequencer)    

  virtual task body();
    req = instruction::type_id::create("req");
      wait_for_grant();
      assert(req.randomize() with {
         inst == instruction::PUSH_A;
      });
      send_request(req);
      wait_for_item_done();
      //get_response(res); This is optional. Not using in this example.

      req = instruction::type_id::create("req");
      wait_for_grant();
      req.inst = instruction::PUSH_B;
      send_request(req);
      wait_for_item_done();
      //get_response(res);

      req = instruction::type_id::create("req");
      wait_for_grant();
      req.inst = instruction::ADD;
      send_request(req);
      wait_for_item_done();
      //get_response(res);

      req = instruction::type_id::create("req");
      wait_for_grant();
      req.inst = instruction::POP_C;
      send_request(req);
      wait_for_item_done();
      //get_response(res);
  endtask
  
endclass 

Sequencer:

Ovm_sequence has  a property called default_sequence. Default sequence is a


sequence which will be started automatically. Using set_config_string, user can
override the default sequence to any user defined sequence, so that when a
sequencer is started, automatically a user defined sequence will be started.  If over
rides are not done with user defined sequence, then a random transaction are
generated.  Using "start_default_sequence()" method, "default_sequence" can also be

http://testbench.in/OT_06_OVM_SEQUENCE_1.html[9/26/2012 2:26:58 PM]


WWW.TESTBENCH.IN - OVM Tutorial

started.
Ovm sequencer has seq_item_export and res_export tlm ports for connecting to ovm
driver.

1) Define instruction_sequencer by extending ovm_sequencer.

    class instruction_sequencer extends ovm_sequencer #(instruction);

2) Define the constructor.


Inside the constructor, place the macro `ovm_update_sequence_lib_and_item().
This macro creates 3 predefined sequences. We will discuss about the predefined
sequences in next section.

    function new (string name, ovm_component parent);
      super.new(name, parent);
      `ovm_update_sequence_lib_and_item(instruction)
    endfunction 

3) Place the ovm_sequencer_utils macro. This macro registers the sequencer for
factory overrides.

    `ovm_sequencer_utils(instruction_sequencer)

Sequencer Code;
class instruction_sequencer extends ovm_sequencer #(instruction);

  function new (string name, ovm_component parent);
    super.new(name, parent);
    `ovm_update_sequence_lib_and_item(instruction)
  endfunction 

  `ovm_sequencer_utils(instruction_sequencer)

endclass

Driver:

ovm_driver is a class which is extended from ovm_componenet. This driver is used in


pull mode. Pull mode means, driver pulls the transaction from the sequencer when it
requires.
Ovm driver has 2 TLM ports.
1) Seq_item_port: To get a item from sequencer, driver uses this port. Driver can also
send response back using this port.
2) Rsp_port :  This can also be used to send response back to sequencer.

Seq_item_port methods:

Lets implement a driver:

1) Define a driver which takes the instruction from the sequencer and does the

http://testbench.in/OT_06_OVM_SEQUENCE_1.html[9/26/2012 2:26:58 PM]


WWW.TESTBENCH.IN - OVM Tutorial

processing. In this example we will just print the instruction type and wait for some
delay.

    class instruction_driver extends ovm_driver #(instruction);

2) Place the ovm_component_utils macro to define virtual methods like


get_type_name and create.

   `ovm_component_utils(instruction_driver)

3) Define  Constructor method.

    function new (string name, ovm_component parent);
      super.new(name, parent);
    endfunction 

4) Define the run() method. Run() method is executed in the "run phase". In this
methods, transactions are taken from the sequencer and drive them on to dut
interface or to other components.
Driver class has a port "seq_item_port". Using the method
seq_item_port.get_next_item(), get the transaction from the sequencer and process
it.  Once the processing is done, using the item_done() method, indicate to the
sequencer that the request is completed. In this example, after taking the
transaction, we will print the transaction and wait for 10 units time.  

  task run ();
    while(1) begin
      seq_item_port.get_next_item(req);
      $display("%0d: Driving Instruction  %s",$time,req.inst.name());
      #10;
      seq_item_port.item_done();
    end
  endtask

endclass 

Driver class code:

class instruction_driver extends ovm_driver #(instruction);

  // Provide implementations of virtual methods such as get_type_name and create


  `ovm_component_utils(instruction_driver)

  // Constructor
  function new (string name, ovm_component parent);
    super.new(name, parent);
  endfunction 

  task run ();
    forever begin
      seq_item_port.get_next_item(req);
      $display("%0d: Driving Instruction  %s",$time,req.inst.name());
      #10;
      // rsp.set_id_info(req);   These two steps are required only if
      // seq_item_port.put(esp); responce needs to be sent back to sequence
      seq_item_port.item_done();
    end
  endtask

endclass 

Driver And Sequencer Connectivity:

Deriver and sequencer are connected using TLM. Ovm_driver has seq_item_port which
is used to get the transaction from ovm sequencer. This port is connected to
ovm_sequencer seq_item_export  Using
"<driver>.seq_item_port.connect(<sequencer>.seq_item_export);" driver and
sequencer can be connected. Simillarly  "res_port" of driver which is used to send
response from driver to sequencer is connected to "res_export" of the sequencer using
""<driver>.res_port.connect(<sequencer>.res_export);".

http://testbench.in/OT_06_OVM_SEQUENCE_1.html[9/26/2012 2:26:58 PM]


WWW.TESTBENCH.IN - OVM Tutorial

Testcase:

This testcase is used only for the demo purpose of this tutorial session. Actually, the
sequencer and the driver and instantiated and their ports are connected in a agent
component and used.  Lets implement a testcase

1) Take instances of sequencer and driver and construct both components.

    sequencer = new("sequencer", null); 
    sequencer.build();
    driver = new("driver", null); 
    driver.build();

2)
Connect the seq_item_export to the drivers seq_item_port.

    driver.seq_item_port.connect(sequencer.seq_item_export);

3) Using set_confg_string() method, set the default sequence of the sequencer to


"operation_addition". Operation_addition is the sequence which we defined previous.

    set_config_string("sequencer", "default_sequence", "operation_addition");

4) Using the start_default_sequence() method of the sequencer, start the default


sequence of the sequencer. In the previous step we configured the addition operation
as default sequene. When you run the simulation, you will see the PUSH_A,PUSH_B
ADD and POP_C series of transaction.

    sequencer.start_default_sequence();

Testcase Code:

module test;

  instruction_sequencer sequencer;
  instruction_driver driver;

  initial begin
    set_config_string("sequencer", "default_sequence", "operation_addition");
    sequencer = new("sequencer", null); 
    sequencer.build();
    driver = new("driver", null); 
    driver.build();

http://testbench.in/OT_06_OVM_SEQUENCE_1.html[9/26/2012 2:26:58 PM]


WWW.TESTBENCH.IN - OVM Tutorial

    driver.seq_item_port.connect(sequencer.seq_item_export);
    sequencer.print();
    fork 
      begin
        run_test();
        sequencer.start_default_sequence();
      end
      #2000 global_stop_request();
    join
  end

endmodule

Download the example:

ovm_basic_sequence.tar
Browse the code in ovm_basic_sequence.tar

Command to simulate

Your_tool_simulation_command +incdir+path_to_ovm testcase.sv

Log file Output

OVM_INFO @ 0 [RNTST] Running test ...


0: Driving Instruction  PUSH_A
10: Driving Instruction  PUSH_B
20: Driving Instruction  ADD
30: Driving Instruction  POP_C

From the above log , we can see that transactions are generates as we defined in ovm
sequence.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OT_06_OVM_SEQUENCE_1.html[9/26/2012 2:26:58 PM]


WWW.TESTBENCH.IN - OVM Tutorial

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS OVM SEQUENCE 2 Index


Introduction
SystemVerilog Ovm Testbench
Verification Pre Defined Sequences: Ovm Reporting
Ovm Transaction
Constructs Every sequencer in ovm has 3 pre defined sequences. They are Ovm Factory
Interface   Ovm Sequence 1
1)Ovm_random_sequence Ovm Sequence 2
OOPS Ovm Sequence 3
2)Ovm_exhaustive_sequence. Ovm Sequence 4
Randomization 3)Ovm_simple_sequence Ovm Sequence 5
Functional Coverage All the user defined sequences which are registered by user and the above three Ovm Sequence 6
predefined sequences are stored in sequencer queue.   Ovm Configuration
Assertion
DPI Report a Bug or Comment
UVM Tutorial on This section - Your
input is what keeps
VMM Tutorial
Testbench.in improving
OVM Tutorial with time!
Easy Labs : SV
Easy Labs : UVM
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

Verilog
Verification
Verilog Switch TB Ovm_random_sequence :
Basic Constructs
This sequence randomly selects and executes a sequence from the sequencer
sequence library, excluding ovm_random_sequence itself, and
ovm_exhaustive_sequence. From the above image, from sequence id 2 to till the last
OpenVera sequence, all the sequences are executed randomly.  If the "count" variable of the
Constructs sequencer is set to 0, then non of the sequence is executed. If the "count" variable of
Switch TB the sequencer is set to -1, then some random number of sequences from 0 to
"max_random_count" are executed. By default "mac_random_count" is set to
RVM Switch TB 10.  "Count" and "mac_random_count" can be changed using set_config_int().
RVM Ethernet sample
The sequencer when automatically started executes the sequence which is point by
default_sequence. By default  default_sequence variable points to
ovm_random_sequence.
Specman E
Interview Questions ovm_exaustive_sequence:

This sequence randomly selects and executes each sequence from the sequencers
sequence library once in a randc style, excluding itself and ovm_random_sequence.

ovm_simple_sequence:

This sequence simply executes a single sequence item.

In the previous example from OVM_SEQUENCE_1 section.

http://testbench.in/OT_07_OVM_SEQUENCE_2.html[9/26/2012 2:27:07 PM]


WWW.TESTBENCH.IN - OVM Tutorial

The print() method of the sequencer in that example printed the following

-------------------------------------------------------------------
---
Name                     Type                Size                Value
-------------------------------------------------------------------
---
sequencer                instruction_sequen+ -             sequencer@2
  rsp_export             ovm_analysis_export -            rsp_export@4
  seq_item_export        ovm_seq_item_pull_+ -      seq_item_export@28
  default_sequence       string              18     operation_addition
  count                  integral            32                     -1
  max_random_count       integral            32                   'd10
  sequences              array               4                       -
    [0]                  string              19    ovm_random_sequence
    [1]                  string              23   ovm_exhaustive_sequ+
    [2]                  string              19    ovm_simple_sequence
    [3]                  string              18     operation_addition
  max_random_depth       integral            32                    'd4
  num_last_reqs          integral            32                    'd1
  num_last_rsps          integral            32                    'd1
-------------------------------------------------------------------
---

Some observations from the above log:

 The count  is set to -1.  The default sequencer is set to operations_addition. There


are 3 predefined sequences and 1 user defined sequence.  

Lets look at a example: In the attached example, in file sequence.sv file, there are 4
seuqneces, they are operation_addition, operation_subtraction,
operation_multiplication.

In the testcase.sv file, the "default_seuence" is set to "ovm_exhaustive_sequence"


using the set_config_string.

    set_config_string("sequencer", "default_sequence", "ovm_exhaustive_sequence");

Download the example

ovm_sequence_1.tar
Browse the code in ovm_sequence_1.tar

Command to run the summation

Your_tool_simulation_command +incdir+path_to_ovm testcase.sv

Log File

0: Driving Instruction  PUSH_B

10: Driving Instruction  PUSH_A


20: Driving Instruction  PUSH_B
30: Driving Instruction  SUB
40: Driving Instruction  POP_C

50: Driving Instruction  PUSH_A


60: Driving Instruction  PUSH_B
70: Driving Instruction  MUL
80: Driving Instruction  POP_C

90: Driving Instruction  PUSH_A


100: Driving Instruction  PUSH_B
110: Driving Instruction  ADD
120: Driving Instruction  POP_C

http://testbench.in/OT_07_OVM_SEQUENCE_2.html[9/26/2012 2:27:07 PM]


WWW.TESTBENCH.IN - OVM Tutorial

From the above log , we can see that all the 3 user defined sequences and predefined
ovm_simple_sequence are executed.

Sequence Action Macro:

In the previous sections, we have seen the implementation of body() method of


sequence. The body() method implementation requires some steps.  We have seen
these steps as  Creation of item, wait for grant, randomize the item, send the item.  

All these steps have be automated using "sequence action macros". There are some
more additional steps added in these macros. Following are the steps defined with the
"sequence action macro".

Pre_do(), mid_do() and post_do() are callback methods which are in ovm sequence.  If
user is interested , he can use these methods. For example, in  mid_do() method, user
can print the transaction or  the randomized transaction can be fined tuned.  These
methods should not be clled by user directly.  

Syntax:

virtual task pre_do(bit is_item)
virtual function void mid_do(ovm_sequence_item this_item)
virtual function void post_do(ovm_sequence_item this_item)

Pre_do() is a task , if  the method consumes simulation cycles, the behavior may be
unexpected.

Example Of Pre_do,Mid_do And Post_do

Lets look at a example:   We will define a sequence using `ovm_do macro. This macro
has all the above defined phases.
  
1)Define the body method using the `ovm_do() macro. Before and after this macro,
just call messages.

  virtual task body();
     ovm_report_info(get_full_name(),
            "Seuqnce Action Macro Phase  : Before ovm_do macro ",OVM_LOW);
     `ovm_do(req);
     ovm_report_info(get_full_name(),
            "Seuqnce Action Macro Phase  : After ovm_do macro ",OVM_LOW);
  endtask

2)Define pre_do() method. Lets just print a message from this method.

  virtual task pre_do(bit is_item);
       ovm_report_info(get_full_name(),
            "Seuqnce Action Macro Phase  : PRE_DO   ",OVM_LOW);

http://testbench.in/OT_07_OVM_SEQUENCE_2.html[9/26/2012 2:27:07 PM]


WWW.TESTBENCH.IN - OVM Tutorial

  endtask

3)Define mid_do() method. Lets just print a message from this method.

  virtual function void mid_do(ovm_sequence_item this_item);
       ovm_report_info(get_full_name(),
            "Seuqnce Action Macro Phase  : MID_DO   ",OVM_LOW);
  endfunction

4)Define post_do() method. Lets just print a message from this method.

  virtual function void post_do(ovm_sequence_item this_item);
       ovm_report_info(get_full_name(),
            "Seuqnce Action Macro Phase  : POST_DO   ",OVM_LOW);
  endfunction 

Complet sequence code:

class demo_ovm_do extends ovm_sequence #(instruction);

  instruction req;
 
  function new(string name="demo_ovm_do");
    super.new(name);
  endfunction
  
  `ovm_sequence_utils(demo_ovm_do, instruction_sequencer)    

  virtual task pre_do(bit is_item);
       ovm_report_info(get_full_name(),
           "Seuqnce Action Macro Phase  : PRE_DO   ",OVM_LOW);
  endtask

  virtual function void mid_do(ovm_sequence_item this_item);
       ovm_report_info(get_full_name(),
           "Seuqnce Action Macro Phase  : MID_DO   ",OVM_LOW);
  endfunction

  virtual function void post_do(ovm_sequence_item this_item);
       ovm_report_info(get_full_name(),
           "Seuqnce Action Macro Phase  : POST_DO   ",OVM_LOW);
  endfunction 

  virtual task body();
     ovm_report_info(get_full_name(),
           "Seuqnce Action Macro Phase  : Before ovm_do macro ",OVM_LOW);
     `ovm_do(req);
     ovm_report_info(get_full_name(),
           "Seuqnce Action Macro Phase  : After ovm_do macro ",OVM_LOW);
  endtask
  
endclass 

Download the example

ovm_sequence_2.tar
Browse the code in ovm_sequence_2.tar

Command to run the simulation

Your_tool_simulation_command +incdir+path_to_ovm testcase.sv

Log file report:

OVM_INFO@0:reporter[sequencer.demo_ovm_do]
    Seuqnce Action Macro Phase  : Before ovm_do macro
OVM_INFO@0:reporter[sequencer.demo_ovm_do]
    Seuqnce Action Macro Phase  : PRE_DO  
OVM_INFO@0:reporter[sequencer.demo_ovm_do]
    Seuqnce Action Macro Phase  : MID_DO  

0: Driving Instruction  MUL

OVM_INFO@10:reporter[sequencer.demo_ovm_do]

http://testbench.in/OT_07_OVM_SEQUENCE_2.html[9/26/2012 2:27:07 PM]


WWW.TESTBENCH.IN - OVM Tutorial

    Seuqnce Action Macro Phase  : POST_DO  


OVM_INFO@10:reporter[sequencer.demo_ovm_do]
    Seuqnce Action Macro Phase  : After ovm_do macro  

The above log file shows the  messages from pre_do,mid_do and post_do methods.

List Of Sequence Action Macros:

These macros are used to start sequences and sequence items that were either
registered with a <`ovm-sequence_utils> macro or whose associated sequencer was
already set using the <set_sequencer> method.

`ovm_create(item/sequence)

This action creates the item or sequence using the factory. Only the create phase will
be executed.

`ovm_do(item/sequence)

This macro takes as an argument a ovm_sequence_item variable or sequence . All the


above defined 7 phases will be executed.

`ovm_do_with(item/sequence, Constraint block)

This is the same as `ovm_do except that the constraint block in the 2nd argument is
applied to the item or sequence in a randomize with statement before execution.

`ovm_send(item/sequence)

Create phase and randomize phases are skipped, rest all the phases will be executed.
Using `ovm_create, create phase can be executed.  Essentially, an `ovm_do without
the create or randomization.

`ovm_rand_send(item/sequence)

Only create phase is skipped. rest of all the phases will be executed. User should use
`ovm_create to create the sequence or item.

`ovm_rand_send_with(item/sequence , Constraint block)

 Only create phase is skipped. rest of all the phases will be executed. User should use
`ovm_create to create the sequence or item.  Constraint block will be applied which
randomization.

`ovm_do_pri(item/sequence, priority )

This is the same as `ovm_do except that the sequence item or sequence is executed
with the priority specified in the argument.

`ovm_do_pri_with(item/sequence , constraint block , priority)

This is the same as `ovm_do_pri except that the given constraint block is applied to
the item or sequence in a randomize with statement  before execution.

`ovm_send_pri(item/sequence,priority)

This is the same as `ovm_send except that the sequence item or sequence is executed
with the priority specified in the argument.

`ovm_rand_send_pri(item/sequence,priority)

This is the same as `ovm_rand_send except that the sequence item or sequence is
executed with the priority specified in the argument.

`ovm_rand_send_pri_with(item/sequence,priority,constraint block)

This is the same as `ovm_rand_send_pri except that the given constraint block is
applied to the item or sequence in a randomize with statement before execution.  

Following  macros are used on sequence or sequence items on a different sequencer.

http://testbench.in/OT_07_OVM_SEQUENCE_2.html[9/26/2012 2:27:07 PM]


WWW.TESTBENCH.IN - OVM Tutorial

`ovm_create_on(item/sequence,sequencer)

This is the same as `ovm_create except that it also sets the parent sequence to the
sequence in which the macro is invoked, and it sets the sequencer to the specified
sequencer argument.

`ovm_do_on(item/sequence,sequencer)

This is the same as `ovm_do except that it also sets the parent sequence to the
sequence in which the macro is invoked, and it sets the sequencer to the specified
sequencer  argument.

`ovm_do_on_pri(item/sequence,sequencer, priority)

This is the same as `ovm_do_pri except that it also sets the parent sequence to the
sequence in which the macro is invoked, and it sets the sequencer to the specified
sequencer  argument.

`ovm_do_on_with(item/sequence,sequencer, constraint block)

This is the same as `ovm_do_with except that it also sets the parent sequence to the
sequence in which the macro is invoked, and it sets the  sequencer to the specified
sequencer  argument.  The user must supply brackets around the constraints.

`ovm_do_on_pri_with(item/sequence,sequencer,priority,constraint block)

This is the same as `ovm_do_pri_with except that it also sets the parent sequence to
the sequence in which the macro is invoked, and it sets the sequencer to the specified
sequencer argument.

Examples With Sequence Action Macros:

  virtual task body();
      ovm_report_info(get_full_name(),
          "Executing Sequence Action Macro ovm_do",OVM_LOW);
      `ovm_do(req)
  endtask

  virtual task body();
      ovm_report_info(get_full_name(),
          "Executing Sequence Action Macro ovm_do_with ",OVM_LOW);
      `ovm_do_with(req,{ inst == ADD; })
  endtask

  virtual task body();
      ovm_report_info(get_full_name(),
           "Executing Sequence Action Macro ovm_create and ovm_send",OVM_LOW);
      `ovm_create(req)
      req.inst = instruction::PUSH_B;
      `ovm_send(req)
  endtask
  
  virtual task body();
      ovm_report_info(get_full_name(),
           "Executing Sequence Action Macro ovm_create and
ovm_rand_send",OVM_LOW);
      `ovm_create(req)
      `ovm_rand_send(req)
  endtask
  

Download the example

ovm_sequence_3.tar
Browse the code in ovm_sequence_3.tar

Command to sun the simulation

Your_tool_simulation_command +incdir+path_to_ovm testcase.sv

http://testbench.in/OT_07_OVM_SEQUENCE_2.html[9/26/2012 2:27:07 PM]


WWW.TESTBENCH.IN - OVM Tutorial

Log file report

0: Driving Instruction  PUSH_B
OVM_INFO@10:reporter[***]Executing Sequence Action Macro ovm_do_with
10: Driving Instruction  ADD
OVM_INFO@20:reporter[***]Executing Sequence Action Macro ovm_create and
ovm_send
20: Driving Instruction  PUSH_B
OVM_INFO@30:reporter[***]Executing Sequence Action Macro ovm_do
30: Driving Instruction  DIV
OVM_INFO@40:reporter[***]Executing Sequence Action Macro ovm_create and
ovm_rand_send
40: Driving Instruction  MUL

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OT_07_OVM_SEQUENCE_2.html[9/26/2012 2:27:07 PM]


WWW.TESTBENCH.IN - OVM Tutorial

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS OVM SEQUENCE 3 Index


Introduction
SystemVerilog Body Callbacks: Ovm Testbench
Verification Ovm Reporting
Ovm sequences has two callback methods pre_body() and post_body(), which are Ovm Transaction
Constructs executed before and after the sequence body() method execution. These callbacks Ovm Factory
Interface are called only when start_sequence() of sequencer or start() method of the sequence Ovm Sequence 1
is called. User should not call these methods. Ovm Sequence 2
OOPS Ovm Sequence 3
Randomization Ovm Sequence 4
virtual task pre_body() Ovm Sequence 5
Functional Coverage Ovm Sequence 6
virtual task post_body()
Assertion Ovm Configuration
DPI Example
Report a Bug or Comment
UVM Tutorial In this example, I just printed messages from pre_body() and post_body() methods. on This section - Your
VMM Tutorial These methods can be used for initialization, synchronization with some events or input is what keeps
cleanup. Testbench.in improving
OVM Tutorial with time!
Easy Labs : SV
class demo_pre_body_post_body extends ovm_sequence #(instruction);
Easy Labs : UVM
Easy Labs : OVM   instruction req;
 
Easy Labs : VMM   function new(string name="demo_pre_body_post_body");
AVM Switch TB     super.new(name);
  endfunction
VMM Ethernet sample   
  `ovm_sequence_utils(demo_pre_body_post_body, instruction_sequencer)    

Verilog   virtual task pre_body();
Verification        ovm_report_info(get_full_name()," pre_body() callback ",OVM_LOW);
  endtask
Verilog Switch TB
Basic Constructs   virtual task post_body();
       ovm_report_info(get_full_name()," post_body() callback ",OVM_LOW);
  endtask
OpenVera   virtual task body();
Constructs      ovm_report_info(get_full_name(),
Switch TB           "body() method: Before ovm_do macro ",OVM_LOW);
     `ovm_do(req);
RVM Switch TB      ovm_report_info(get_full_name(),
RVM Ethernet sample           "body() method: After ovm_do macro ",OVM_LOW);
  endtask
  
endclass 
Specman E
Interview Questions
Download the example

ovm_sequence_4.tar
Browse the code in ovm_sequence_4.tar

Command to sun the simulation

Your_tool_simulation_command +incdir+path_to_ovm testcase.sv

http://testbench.in/OT_08_OVM_SEQUENCE_3.html[9/26/2012 2:27:20 PM]


WWW.TESTBENCH.IN - OVM Tutorial

Log file report

OVM_INFO @ 0 [RNTST] Running test ...


OVM_INFO @ 0: reporter [***]  pre_body() callback
OVM_INFO @ 0: reporter [***] body() method: Before ovm_do macro
0: Driving Instruction  SUB
OVM_INFO @ 10: reporter [***] body() method: After ovm_do macro
OVM_INFO @ 10: reporter [***]  post_body() callback

Hierarchical Sequences

One main advantage of sequences is smaller sequences can be used to create


sequences to generate stimulus required for todays complex protocol.  

To create a sequence using another sequence, following steps has to be done

1)Extend the ovm_sequence class and define a new class.


2)Declare instances of child sequences which will be used to create new sequence.
3)Start the child sequence using <instance>.start() method in body() method.

Sequential Sequences

To executes child sequences sequentially, child sequence start() method should be


called sequentially in body method.
In the below example you can see all the 3 steps mentioned above.
In this example, I have defined 2 child sequences. These child sequences can be used
as normal sequences.

Sequence 1 code:

This sequence generates 4 PUSH_A instructions.

  virtual task body();
      repeat(4) begin
         `ovm_do_with(req, { inst == PUSH_A; });
      end
  endtask

Sequence 2 code:

This sequence generates 4 PUSH_B instructions.

  virtual task body();
      repeat(4) begin
         `ovm_do_with(req, { inst == PUSH_B; });
      end
  endtask

Sequential Sequence code:

This sequence first calls sequence 1 and then calls sequence 2.

class sequential_sequence extends ovm_sequence #(instruction);

  seq_a s_a;
  seq_b s_b;
 
  function new(string name="sequential_sequence");
    super.new(name);
  endfunction
  
  `ovm_sequence_utils(sequential_sequence, instruction_sequencer)    

  virtual task body();
         `ovm_do(s_a);

http://testbench.in/OT_08_OVM_SEQUENCE_3.html[9/26/2012 2:27:20 PM]


WWW.TESTBENCH.IN - OVM Tutorial

         `ovm_do(s_b);
  endtask
  
endclass  

From the testcase, "sequential_sequence" is selected as "default_sequence". 

Download the example

ovm_sequence_5.tar
Browse the code in ovm_sequence_5.tar

Command to sun the simulation

Your_tool_simulation_command +incdir+path_to_ovm testcase.sv

Log file report

0: Driving Instruction  PUSH_A
10: Driving Instruction  PUSH_A
20: Driving Instruction  PUSH_A
30: Driving Instruction  PUSH_A
40: Driving Instruction  PUSH_B
50: Driving Instruction  PUSH_B
60: Driving Instruction  PUSH_B
70: Driving Instruction  PUSH_B

If you observe the above log, you can see sequence seq_a is executed first and then
sequene seq_b is executed.

Parallelsequences

To executes child sequences Parallel, child sequence start() method should be called
parallel using fork/join  in body method.

Parallel Sequence code:

class parallel_sequence extends ovm_sequence #(instruction);

  seq_a s_a;
  seq_b s_b;
 
  function new(string name="parallel_sequence");
    super.new(name);
  endfunction
  
  `ovm_sequence_utils(parallel_sequence, instruction_sequencer)    

  virtual task body();
         fork
              `ovm_do(s_a)
              `ovm_do(s_b)
         join
  endtask
  
endclass  

Download the example

ovm_sequence_6.tar
Browse the code in ovm_sequence_6.tar

Command to sun the simulation

Your_tool_simulation_command +incdir+path_to_ovm testcase.sv

Log file report

OVM_INFO @ 0 [RNTST] Running test ...


0: Driving Instruction  PUSH_A

http://testbench.in/OT_08_OVM_SEQUENCE_3.html[9/26/2012 2:27:20 PM]


WWW.TESTBENCH.IN - OVM Tutorial

10: Driving Instruction  PUSH_B


20: Driving Instruction  PUSH_A
30: Driving Instruction  PUSH_B
40: Driving Instruction  PUSH_A
50: Driving Instruction  PUSH_B
60: Driving Instruction  PUSH_A
70: Driving Instruction  PUSH_B

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OT_08_OVM_SEQUENCE_3.html[9/26/2012 2:27:20 PM]


WWW.TESTBENCH.IN - OVM Tutorial

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS OVM SEQUENCE 4 Index


Introduction
SystemVerilog Sequencer Arbitration: Ovm Testbench
Verification Ovm Reporting
When sequencers are executed parallel, sequencer will arbitrate among the parallel Ovm Transaction
Constructs sequence. When all the parallel sequences are waiting for a grant from sequencer Ovm Factory
Interface using wait_for_grant() method, then the sequencer, using the arbitration mechanism, Ovm Sequence 1
sequencer grants to one of the sequencer. Ovm Sequence 2
OOPS Ovm Sequence 3
Randomization There are 6 different arbitration algorithms, they are Ovm Sequence 4
Ovm Sequence 5
Functional Coverage Ovm Sequence 6
Assertion Ovm Configuration
DPI Report a Bug or Comment
UVM Tutorial on This section - Your
input is what keeps
VMM Tutorial
Testbench.in improving
OVM Tutorial with time!
Easy Labs : SV
Easy Labs : UVM
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

Verilog
Verification
To set the arbitaration, use the set_arbitration() method of the sequencer. By default
Verilog Switch TB , the arbitration algorithms is set to SEQ_ARB_FIFO.
Basic Constructs
   function void set_arbitration(SEQ_ARB_TYPE val)

OpenVera Lets look at a example.


Constructs In this example, I have 3 child sequences seq_mul seq_add and seq_sub each of them
generates 3 transactions.
Switch TB
RVM Switch TB Sequence code 1:
virtual task body();
RVM Ethernet sample
      repeat(3) begin
         `ovm_do_with(req, { inst == MUL; });
      end
Specman E   endtask
Interview Questions
Sequence code 2:
  virtual task body();
      repeat(3) begin
         `ovm_do_with(req, { inst == ADD; });
      end
  endtask

Sequence code 3:
  virtual task body();
      repeat(3) begin
         `ovm_do_with(req, { inst == SUB; });

http://testbench.in/OT_09_OVM_SEQUENCE_4.html[9/26/2012 2:27:28 PM]


WWW.TESTBENCH.IN - OVM Tutorial

      end
  endtask

Parallel sequence code:

In the body method, before starting child sequences, set the arbitration using
set_arbitration(). In this code, im setting it to SEQ_ARB_RANDOM.

class parallel_sequence extends ovm_sequence #(instruction);

  seq_add add;
  seq_sub sub;
  seq_mul mul;
 
  function new(string name="parallel_sequence");
    super.new(name);
  endfunction
  
  `ovm_sequence_utils(parallel_sequence, instruction_sequencer)    

  virtual task body();
      m_sequencer.set_arbitration(SEQ_ARB_RANDOM);
      fork
         `ovm_do(add)
         `ovm_do(sub)
         `ovm_do(mul)
      join
  endtask
  
endclass

Download the example

ovm_sequence_7.tar
Browse the code in ovm_sequence_7.tar

Command to sun the simulation

Your_tool_simulation_command +incdir+path_to_ovm testcase.sv

Log file report for when SEQ_ARB_RANDOM is set.

0: Driving Instruction  MUL
10: Driving Instruction  SUB
20: Driving Instruction  MUL
30: Driving Instruction  SUB
40: Driving Instruction  MUL
50: Driving Instruction  ADD
60: Driving Instruction  ADD
70: Driving Instruction  SUB
80: Driving Instruction  ADD

Log file report for when SEQ_ARB_FIFO is set.

0: Driving Instruction  ADD
10: Driving Instruction  SUB
20: Driving Instruction  MUL
30: Driving Instruction  ADD
40: Driving Instruction  SUB
50: Driving Instruction  MUL
60: Driving Instruction  ADD
70: Driving Instruction  SUB
80: Driving Instruction  MUL

http://testbench.in/OT_09_OVM_SEQUENCE_4.html[9/26/2012 2:27:28 PM]


WWW.TESTBENCH.IN - OVM Tutorial

If you observe the first log report, all the transaction of the sequences are generated
in random order. In the second log file, the transactions are given equal priority and
are in fifo order.

Setting The Sequence Priority:

There are two ways to set the priority of a sequence. One is using the start method of
the sequence and other using the set_priority() method of the sequence. By default,
the priority of a sequence is 100.   Higher numbers indicate higher priority.

virtual task start (ovm_sequencer_base sequencer, 
               ovm_sequence_base parent_sequence = null,
               integer this_priority = 100,
               bit call_pre_post = 1)

function void set_priority (int value)

Lets look a example with SEQ_ARB_WEIGHTED.

For sequence seq_mul set the weight to 200.


For sequence seq_add set the weight to 300.
For sequence seq_sub set the weight to 400.

In the below example, start() method is used to override the default priority value.

Code :

class parallel_sequence extends ovm_sequence #(instruction);

  seq_add add;
  seq_sub sub;
  seq_mul mul;
 
  function new(string name="parallel_sequence");
    super.new(name);
  endfunction
  
  `ovm_sequence_utils(parallel_sequence, instruction_sequencer)    

  virtual task body();
      m_sequencer.set_arbitration(SEQ_ARB_WEIGHTED);
      add = new("add");
      sub = new("sub");
      mul = new("mul");
      fork
         sub.start(m_sequencer,this,400);
         add.start(m_sequencer,this,300);
         mul.start(m_sequencer,this,200);
      join
  endtask
  
endclass 

Download the example

ovm_sequence_8.tar
Browse the code in ovm_sequence_8.tar

Command to sun the simulation

Your_tool_simulation_command +incdir+path_to_ovm testcase.sv

Log file report

0: Driving Instruction  MUL
10: Driving Instruction  ADD
20: Driving Instruction  SUB
30: Driving Instruction  SUB

http://testbench.in/OT_09_OVM_SEQUENCE_4.html[9/26/2012 2:27:28 PM]


WWW.TESTBENCH.IN - OVM Tutorial

40: Driving Instruction  ADD


50: Driving Instruction  ADD
60: Driving Instruction  ADD
70: Driving Instruction  MUL
80: Driving Instruction  SUB

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OT_09_OVM_SEQUENCE_4.html[9/26/2012 2:27:28 PM]


WWW.TESTBENCH.IN - OVM Tutorial

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS OVM SEQUENCE 5 Index


Introduction
SystemVerilog Sequencer Registration Macros Ovm Testbench
Verification Ovm Reporting
Ovm Transaction
Constructs Sequence Registration Macros does the following Ovm Factory
Interface 1) Implements get_type_name method. Ovm Sequence 1
2) Implements create() method. Ovm Sequence 2
OOPS Ovm Sequence 3
3) Registers with the factory.
Randomization 4) Implements the static get_type() method. Ovm Sequence 4
5) Implements the virtual get_object_type() method. Ovm Sequence 5
Functional Coverage Ovm Sequence 6
6) Registers the sequence type with the sequencer type.
Assertion 7) Defines p_sequencer variable. p_sequencer is a handle to its sequencer. Ovm Configuration
DPI 8) Implements m_set_p_sequencer() method.
Report a Bug or Comment
UVM Tutorial If there are no local variables, then use following macro on This section - Your
input is what keeps
VMM Tutorial
`ovm_sequence_utils(TYPE_NAME,SQR_TYPE_NAME) Testbench.in improving
OVM Tutorial with time!
Easy Labs : SV
If there are local variables in sequence, then use macro
Easy Labs : UVM
Easy Labs : OVM `ovm_sequence_utils_begin(TYPE_NAME,SQR_TYPE_NAME)
  `ovm_field_* macro invocations here
Easy Labs : VMM `ovm_sequence_utils_end
AVM Switch TB
VMM Ethernet sample Macros `ovm_field_* are used for define utility methods.
These `ovm_field_* macros  are discussed in
OVM_TRANSACTION  
Verilog
Verification
Example to demonstrate the usage of the above macros:
Verilog Switch TB
Basic Constructs
class seq_mul extends ovm_sequence #(instruction);

  rand integer num_inst ;
OpenVera   instruction req;
Constructs
Switch TB   constraint num_c { num_inst inside { 3,5,7 }; };
RVM Switch TB     `ovm_sequence_utils_begin(seq_mul,instruction_sequencer)    
RVM Ethernet sample     `ovm_field_int(num_inst, OVM_ALL_ON)
    `ovm_sequence_utils_end
  
  function new(string name="seq_mul");
Specman E     super.new(name);
Interview Questions   endfunction
  

  virtual task body();
      ovm_report_info(get_full_name(),
        $psprintf("Num of transactions %d",num_inst),OVM_LOW);
      repeat(num_inst) begin
         `ovm_do_with(req, { inst == MUL; });
      end
  endtask
  

http://testbench.in/OT_10_OVM_SEQUENCE_5.html[9/26/2012 2:27:37 PM]


WWW.TESTBENCH.IN - OVM Tutorial

endclass 

Download the example

ovm_sequence_9.tar
Browse the code in ovm_sequence_9.tar

Command to sun the simulation

Your_tool_simulation_command +incdir+path_to_ovm testcase.sv

Log

OVM_INFO @ 0: reporter [RNTST] Running test ...


OVM_INFO @ 0: reporter [sequencer.seq_mul] Num of transactions           5
0: Driving Instruction  MUL
10: Driving Instruction  MUL
20: Driving Instruction  MUL
30: Driving Instruction  MUL
40: Driving Instruction  MUL

Setting Sequence Members:

set_config_*  can be used only for the components not for the sequences.
By using configuration you can change the variables inside components only not in
sequences.

But there is a workaround to this problem.

Sequence has handle name called p_sequencer which is pointing the Sequencer on
which it is running.
Sequencer is a component , so get_config_* methods are implemented for it.
So from the sequence, using the sequencer get_config_* methods, sequence members
can be updated if the variable is configured.

When using set_config_* , path to the variable should be sequencer name, as we are
using the sequencer get_config_* method.

Following method demonstrates how this can be done:

Sequence:

1) num_inst is a integer variables which can be updated.


2) In the body method, call the get_config_int() method to get the integer value if
num_inst is configured from testcase.

class seq_mul extends ovm_sequence #(instruction);

  integer num_inst = 4;
  instruction req;

    `ovm_sequence_utils_begin(seq_mul,instruction_sequencer)    
    `ovm_field_int(num_inst, OVM_ALL_ON)
    `ovm_sequence_utils_end
  
  function new(string name="seq_mul");
    super.new(name);
  endfunction
  

  virtual task body();

       void'(p_sequencer.get_config_int("num_inst",num_inst));

       ovm_report_info(get_full_name(),
           $psprintf("Num of transactions %d",num_inst),OVM_LOW);
      repeat(num_inst) begin

http://testbench.in/OT_10_OVM_SEQUENCE_5.html[9/26/2012 2:27:37 PM]


WWW.TESTBENCH.IN - OVM Tutorial

         `ovm_do_with(req, { inst == MUL; });


      end
  endtask
  
endclass 

Testcase:

From the testcase, using the     set_config_int() method, configure the num_inst to 3.
The instance path argument should be the sequencer path name.

module test;

  instruction_sequencer sequencer;
  instruction_driver driver;

  initial begin
    set_config_string("sequencer", "default_sequence", "seq_mul");
    set_config_int("sequencer", "num_inst",3);
    sequencer = new("sequencer", null); 
    sequencer.build();
    driver = new("driver", null); 
    driver.build();

    driver.seq_item_port.connect(sequencer.seq_item_export);
    sequencer.print();
    fork 
      begin
        run_test();
        sequencer.start_default_sequence();
      end
      #3000 global_stop_request();
    join
  end

endmodule
 

Download the example

ovm_sequence_10.tar
Browse the code in ovm_sequence_10.tar

Command to sun the simulation

Your_tool_simulation_command +incdir+path_to_ovm testcase.sv

Log

OVM_INFO @ 0: reporter [RNTST] Running test ...


OVM_INFO @ 0: reporter [sequencer.seq_mul] Num of transactions           3
0: Driving Instruction  MUL
10: Driving Instruction  MUL
20: Driving Instruction  MUL

From the above log we can see that seq_mul.num_inst value is 3.

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/OT_10_OVM_SEQUENCE_5.html[9/26/2012 2:27:37 PM]


WWW.TESTBENCH.IN - OVM Tutorial

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OT_10_OVM_SEQUENCE_5.html[9/26/2012 2:27:37 PM]


WWW.TESTBENCH.IN - OVM Tutorial

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS OVM SEQUENCE 6 Index


Introduction
SystemVerilog Ovm Testbench
Verification Exclusive Access Ovm Reporting
Ovm Transaction
Constructs A sequence may need exclusive access to the driver which sequencer is arbitrating Ovm Factory
Interface among multiple sequence. Some operations require that a series of transaction needs Ovm Sequence 1
to be driven without any other transaction in between them. Then a exclusive access Ovm Sequence 2
OOPS Ovm Sequence 3
to the driver will allow to a sequence to complete its operation with out any other
Randomization sequence operations in between them. Ovm Sequence 4
Ovm Sequence 5
Functional Coverage Ovm Sequence 6
There are 2 mechanisms to get exclusive access:
Assertion Lock-unlcok Ovm Configuration
DPI Grab-ungrab
Report a Bug or Comment
UVM Tutorial on This section - Your
input is what keeps
VMM Tutorial Lock-Unlock
Testbench.in improving
OVM Tutorial with time!
task lock(ovm_sequencer_base sequencer = Null)
Easy Labs : SV function void unlock(ovm_sequencer_base sequencer = Null)
Easy Labs : UVM
Easy Labs : OVM Using lock() method , a sequence can requests for exclusive access.  A lock request
Easy Labs : VMM will be arbitrated the same as any other request.  A lock is granted after all earlier
requests are completed and no other locks or grabs are blocking this sequence. A
AVM Switch TB lock() is blocking task and when access is granted, it will unblock.
VMM Ethernet sample     
Using unlock(), removes any locks or grabs obtained by this sequence on the specified
sequencer.  
Verilog If sequencer is null, the lock/unlock will be applied on the current default sequencer.
Verification
Lets see an example,
Verilog Switch TB
In this example there are 3 sequences with each sequence generating 4 transactions.
Basic Constructs All these 3 sequences will be called in parallel in another sequence.

Sequence 1 code:
OpenVera
  virtual task body();
Constructs       repeat(4) begin
Switch TB          `ovm_do_with(req, { inst == PUSH_A; });
      end
RVM Switch TB
  endtask
RVM Ethernet sample
Sequence 2 code:
 virtual task body();
      repeat(4) begin
Specman E
         `ovm_do_with(req, { inst == POP_C; });
Interview Questions       end
  endtask
  

Sequence 3 code:

In this sequence , call the lock() method to get the exclusive access to driver.
After completing all the transaction driving, then call the unclock() method.

 virtual task body();

http://testbench.in/OT_11_OVM_SEQUENCE_6.html[9/26/2012 2:27:44 PM]


WWW.TESTBENCH.IN - OVM Tutorial

      lock();
      repeat(4) begin
         `ovm_do_with(req, { inst == PUSH_B; });
      end
      unlock();
  endtask

Parallel sequence code:

  virtual task body();
      fork
         `ovm_do(s_a)
         `ovm_do(s_b)
         `ovm_do(s_c)
      join
  endtask

Download the example

ovm_sequence_11.tar
Browse the code in ovm_sequence_11.tar

Command to sun the simulation

Your_tool_simulation_command +incdir+path_to_ovm testcase.sv

Log file:

0: Driving Instruction  PUSH_A
10: Driving Instruction  POP_C
20: Driving Instruction  PUSH_A
30: Driving Instruction  PUSH_B
40: Driving Instruction  PUSH_B
50: Driving Instruction  PUSH_B
60: Driving Instruction  PUSH_B
70: Driving Instruction  POP_C
80: Driving Instruction  PUSH_A
90: Driving Instruction  POP_C
100: Driving Instruction  PUSH_A
110: Driving Instruction  POP_C

From the above log file, we can observe that , when seq_b sequence got the access,
then transactions from seq_a and seq_c are not generated.

Lock() will be arbitrated before giving the access. To get the exclusive access without
arbitration, grab() method should be used.

Grab-Ungrab

task grab(ovm_sequencer_base sequencer = null)


function void ungrab(ovm_sequencer_base sequencer = null)

grab() method requests a lock on the specified sequencer. A grab() request is put in
front of the arbitration queue.  It will be arbitrated before any other requests.  A
grab() is granted when no other grabs or locks are blocking this sequence.

A grab() is blocking task and when access is granted, it will unblock.

Ungrab() method removes any locks or grabs obtained by this sequence on the
specified sequencer.
If no argument is supplied, then current default sequencer is chosen.

Example:

 virtual task body();

http://testbench.in/OT_11_OVM_SEQUENCE_6.html[9/26/2012 2:27:44 PM]


WWW.TESTBENCH.IN - OVM Tutorial

      #25;
      grab();
      repeat(4) begin
         `ovm_do_with(req, { inst == PUSH_B; });
      end
      ungrab();
  endtask

Download the example

ovm_sequence_12.tar
Browse the code in ovm_sequence_12.tar

Command to sun the simulation

Your_tool_simulation_command +incdir+path_to_ovm testcase.sv

0: Driving Instruction  PUSH_A
10: Driving Instruction  POP_C
20: Driving Instruction  PUSH_A
30: Driving Instruction  PUSH_B
40: Driving Instruction  PUSH_B
50: Driving Instruction  PUSH_B
60: Driving Instruction  PUSH_B
70: Driving Instruction  POP_C
80: Driving Instruction  PUSH_A
90: Driving Instruction  POP_C
100: Driving Instruction  PUSH_A
110: Driving Instruction  POP_C

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OT_11_OVM_SEQUENCE_6.html[9/26/2012 2:27:44 PM]


WWW.TESTBENCH.IN - OVM Tutorial

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS OVM CONFIGURATION Index


Introduction
SystemVerilog Ovm Testbench
Verification Configuration is a  mechanism in OVM that higher level components in a hierarchy can Ovm Reporting
configure the lower level components variables. Using set_config_* methods, user can Ovm Transaction
Constructs configure integer, string and objects of lower level components. Without this Ovm Factory
Interface mechanism, user should access the lower level component using hierarchy paths, Ovm Sequence 1
which restricts reusability. This mechanism can be used only with components. Ovm Sequence 2
OOPS Ovm Sequence 3
Sequences and transactions cannot be configured using this mechanism. When
Randomization set_config_* method is called, the data is stored w.r.t strings in a table. There is also Ovm Sequence 4
a global configuration table. Ovm Sequence 5
Functional Coverage Ovm Sequence 6
Higher level component can set the configuration data in level component table. It is
Assertion the responsibility of the lower level component to get the data from the component Ovm Configuration
DPI table and update the appropriate table.
Report a Bug or Comment
UVM Tutorial on This section - Your
Set_config_* Methods: input is what keeps
VMM Tutorial
Testbench.in improving
OVM Tutorial Following are the method to configure integer , string and object of ovm_object with time!
Easy Labs : SV based class respectively.
Easy Labs : UVM function void set_config_int (string inst_name,
Easy Labs : OVM                               string field_name,
                              ovm_bitstream_t value)
Easy Labs : VMM
AVM Switch TB function void set_config_string (string inst_name,
                                 string field_name,
VMM Ethernet sample                                  string value)

function void set_config_object (string inst_name,  
Verilog                                  string field_name,  
Verification                    ovm_object value,  bit clone = 1)
Verilog Switch TB
Basic Constructs Arguments description:

string inst_name: Hierarchical string path.


OpenVera string field_name: Name of the field in the table.
Constructs
bitstream_t value: In set_config_int, a integral value that can be anything from 1
bit to 4096 bits.
Switch TB bit clone : If this bit is set then object is cloned.
RVM Switch TB
inst_name and field_name are strings of hierarchal path. They can include wile card
RVM Ethernet sample "*" and "?" characters. These methods must be called in build phase of the component.

Specman E
Interview Questions "*"  matches zero or more characters
"?"  matches exactly one character

Some examples:

"*"     -All the lower level components.

"*abc"  -All the lower level components which ends with "abc".


Example: "xabc","xyabc","xyzabc" ....

http://testbench.in/OT_12_OVM_CONFIGURATION.html[9/26/2012 2:27:52 PM]


WWW.TESTBENCH.IN - OVM Tutorial

"abc*"  -All the lower level components which starts  with "abc".


Example: "abcx","abcxy","abcxyz" ....

"ab?"   -All the lower level components which start with "ab" , then followed by one
more character.
Example: "abc","abb","abx" ....

"?bc"   -All the lower level components which start with any one character  ,then
followed by "c".
Example: "abc","xbc","bbc" ....

"a?c"   -All the lower level components which start with "a" , then followed by one
more character and then followed by "c".
Example: "abc","aac","axc" …..

There are two ways to get the configuration data:


1)Automatic : Using Field macros
2)Manual : using gte_config_* methods.

Automatic Configuration:

To use the atomic configuration, all the configurable fields should be defined using
ovm component field macros and ovm component utilities macros.

Ovm component utility macros:


For non parameterized classes
`ovm_component_utils_begin(TYPE)
  `ovm_field_* macro invocations here
`ovm_component_utils_end
For parameterized classes.
`ovm_component_param_utils_begin(TYPE)
  `ovm_field_* macro invocations here
`ovm_component_utils_end

For OVM Field macros, Refer to link


OVM_TRANSACTION  

Example:
Following example is from link
OVM_TESTBENCH  

2 Configurable fields, a integer and a string are defined in env, agent, monitor and
driver classes. Topology of the environment using these classes is

http://testbench.in/OT_12_OVM_CONFIGURATION.html[9/26/2012 2:27:52 PM]


WWW.TESTBENCH.IN - OVM Tutorial

Driver class Source Code:

Similar to driver class, all other components env, agent and monitor are define.

class driver extends ovm_driver;

  integer int_cfg;
  string  str_cfg;

  `ovm_component_utils_begin(driver)
      `ovm_field_int(int_cfg, OVM_DEFAULT)
      `ovm_field_string(str_cfg, OVM_DEFAULT)
  `ovm_component_utils_end

  function new(string name, ovm_component parent);
      super.new(name, parent);
  endfunction

  function void build();
      super.build();
  endfunction

endclass

Testcase:

Using set_config_int() and set_config_string() configure variables at various hierarchal


locations.

    //t_env.ag1.drv.int_cfg
    //t_env.ag1.mon.int_cfg
    set_config_int("*.ag1.*","int_cfg",32);

    //t_env.ag2.drv
    set_config_int("t_env.ag2.drv","int_cfg",32);

    //t_env.ag2.mon
    set_config_int("t_env.ag2.mon","int_cfg",32);

    //t_env.ag1.mon.str_cfg
    //t_env.ag2.mon.str_cfg
    //t_env.ag1.drv.str_cfg
    //t_env.ag2.drv.str_cfg
    set_config_string("*.ag?.*","str_cfg","pars");

    //t_env.str_cfg
    set_config_string("t_env","str_cfg","abcd");

Download the source code

ovm_configuration_1.tar
Browse the code in ovm_configuration_1.tar

http://testbench.in/OT_12_OVM_CONFIGURATION.html[9/26/2012 2:27:52 PM]


WWW.TESTBENCH.IN - OVM Tutorial

Command to run the simulation

your_tool_simulation_command +path_to_ovm_pkg -f filelist +OVM_TESTNAME=test1

From the above log report of th example, we can see the variables int_cfg and str_cfg
of all the components and they are as per the configuration setting from the testcase.

Manual Configurations:

Using get_config_* methods, user can get the required data if the data is available in
the table.
Following are the method to get configure data of type integer , string and object of
ovm_object based class respectively.

function bit get_config_int (string field_name,
                   inout ovm_bitstream_t value)

function bit get_config_string (string field_name,
                              inout string value)

function bit get_config_object (string field_name,
                          inout ovm_object value,
                             input bit clone = 1)

If a entry is found in the table with "field_name" then data will be updated to "value"
argument . If entry is not found, then the function returns "0". So when these
methods are called, check the return value.

Example: 
Driver class code:
class driver extends ovm_driver;

   integer int_cfg;
   string  str_cfg;

   `ovm_component_utils(driver)

   function new(string name, ovm_component parent);
       super.new(name, parent);
   endfunction

   function void build();
       super.build();
       void'(get_config_int("int_cfg",int_cfg));
       void'(get_config_string("str_cfg",str_cfg));
       ovm_report_info(get_full_name(),
       $psprintf("int_cfg %0d : str_cfg %0s ",int_cfg,str_cfg),OVM_LOW);
   endfunction

endclass 
Download the source code

ovm_configuration_2.tar
Browse the code in ovm_configuration_2.tar

Command to run the simulation

your_tool_simulation_command +path_to_ovm_pkg -f filelist +OVM_TESTNAME=test1

Log file

OVM_INFO @ 0: ovm_test_top.t_env
     int_cfg x : str_cfg abcd
OVM_INFO @ 0: ovm_test_top.t_env.ag1  
     int_cfg x : str_cfg  
OVM_INFO @ 0: ovm_test_top.t_env.ag1.drv  
     int_cfg 32 : str_cfg pars
OVM_INFO @ 0: ovm_test_top.t_env.ag1.mon
     int_cfg 32 : str_cfg pars

http://testbench.in/OT_12_OVM_CONFIGURATION.html[9/26/2012 2:27:52 PM]


WWW.TESTBENCH.IN - OVM Tutorial

OVM_INFO @ 0: ovm_test_top.t_env.ag2
     int_cfg x : str_cfg  
OVM_INFO @ 0: ovm_test_top.t_env.ag2.drv
     int_cfg 32 : str_cfg pars
OVM_INFO @ 0: ovm_test_top.t_env.ag2.mon  
     int_cfg 32 : str_cfg pars

Configuration Setting Members:

print_config_settings
function void print_config_settings
             ( string  field  =  "",
              ovm_component  comp  =  null,
              bit  recurse  =  0 )

This method prints all configuration information for this component.


If "field" is specified and non-empty, then only configuration settings matching that
field, if any, are printed.  The field may not contain wildcards. If "recurse" is set, then
information for all children components are printed recursively.

print_config_matches
static bit print_config_matches = 0

Setting this static variable causes get_config_* to print info about matching
configuration settings as they are being applied. These two members will be helpful
to know while debugging.

Download the source code

ovm_configuration_3.tar
Browse the code in ovm_configuration_3.tar

Command to run the simulation

your_tool_simulation_command +path_to_ovm_pkg -f filelist +OVM_TESTNAME=test1

Log file
When print_config_settings method is called

ovm_test_top.t_env.ag1.drv
   ovm_test_top.*.ag1.* int_cfg int     32
ovm_test_top.t_env.ag1.drv.rsp_port
   ovm_test_top.*.ag?.* str_cfg string  pars
ovm_test_top.t_env.ag1.drv.rsp_port
   ovm_test_top.*.ag1.* int_cfg int     32
ovm_test_top.t_env.ag1.drv.sqr_pull_port
   ovm_test_top.*.ag?.* str_cfg string  pars
ovm_test_top.t_env.ag1.drv.sqr_pull_port  
   ovm_test_top.*.ag1.* int_cfg int     32

When print_config_matches is set to 1.

OVM_INFO @ 0: ovm_test_top.t_env [auto-configuration]


Auto-configuration matches for component ovm_test_top.t_env (env).
Last entry for a given field takes precedence.

Config set from  Instance Path     Field name   Type    Value


------------------------------------------------------------------------------
ovm_test_top(test1) ovm_test_top.t_env str_cfg  string  abcd

http://testbench.in/OT_12_OVM_CONFIGURATION.html[9/26/2012 2:27:52 PM]


WWW.TESTBENCH.IN - OVM Tutorial

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OT_12_OVM_CONFIGURATION.html[9/26/2012 2:27:52 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INTRODUCTION Index


Introduction
SystemVerilog Specification
Verification In this tutorial, we will verify the Switch RTL core. Following are the steps we follow Verification Plan
to verify the Switch RTL core. Phase 1 Top
Constructs Phase 2 Environment
Interface Phase 3 Reset
1) Understand the specification Phase 4 Packet
OOPS Phase 5 Driver
Randomization 2) Developing Verification Plan Phase 6 Receiver
Phase 7 Scoreboard
Functional Coverage
3) Building the Verification Environment. We will build the Environment in Multiple Phase 8 Coverage
Assertion phases, so it will be easy for you to lean step by step. Phase 9 Testcase
DPI Report a Bug or Comment
UVM Tutorial Phase 1) We will develop the testcase and interfaces, and integrate them in these on This section - Your
with the DUT in top module. input is what keeps
VMM Tutorial
Testbench.in improving
OVM Tutorial with time!
Phase 2) We will Develop the Environment class.
Easy Labs : SV
Easy Labs : UVM Phase 3) We will develop reset and configuration methods in Environment class.
Then using these methods, we will reset the DUT and configure the port address.
Easy Labs : OVM
Easy Labs : VMM Phase 4) We will develop a packet class based on the stimulus plan. We will also
write a small code to test the packet class implementation.
AVM Switch TB
VMM Ethernet sample Phase 5) We will develop a driver class. Packets are generated and sent to dut
using driver.  

Verilog Phase 6) We will develop receiver class. Receiver collects the packets coming from
the output port of the DUT.
Verification
Verilog Switch TB Phase 7) We will develop scoreboard class which does the comparison of the
Basic Constructs expected packet with the actual packet received from the DUT.

Phase 8) We will develop coverage class based on the coverage plan.


OpenVera
Phase 9) In this phase , we will write testcases and analyze the coverage report.
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/SL_01_INTRODUCTION.html[9/26/2012 2:28:00 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SL_01_INTRODUCTION.html[9/26/2012 2:28:00 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS SPECIFICATION Index


Introduction
SystemVerilog Switch Specification: Specification
Verification Verification Plan
This is a simple switch. Switch is a packet based protocol. Switch drives the incoming Phase 1 Top
Constructs packet which comes from the input port to output ports based on the address Phase 2 Environment
Interface contained in the packet. Phase 3 Reset
Phase 4 Packet
OOPS
The switch has a one input port from which the packet enters. It has four output ports Phase 5 Driver
Randomization where the packet is driven out. Phase 6 Receiver
Phase 7 Scoreboard
Functional Coverage Phase 8 Coverage
Assertion Phase 9 Testcase
DPI Report a Bug or Comment
UVM Tutorial on This section - Your
input is what keeps
VMM Tutorial
Testbench.in improving
OVM Tutorial with time!
Easy Labs : SV
Easy Labs : UVM
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

Verilog
Verification
Verilog Switch TB
Basic Constructs

Packet Format:
OpenVera
Constructs Packet contains 3 parts. They are Header, data and frame check sequence.
Packet width is 8 bits and the length of the packet can be between 4 bytes to 259
Switch TB bytes.
RVM Switch TB
RVM Ethernet sample
Packet Header:

Packet header contains three fields DA, SA and length.


Specman E
Interview Questions DA: Destination address of the packet is of 8 bits. The switch drives the packet to
respective ports based on this destination address of the packets. Each output port
has 8-bit unique port address.  If the destination address of the packet matches the
port address, then switch drives the packet to the output port.

SA: Source address of the packet from where it originate. It is 8 bits.


Length: Length of the data is of 8 bits and  from 0 to 255. Length is measured in terms
of bytes.  
If Length = 0, it means data length is 0 bytes
If Length = 1, it means data length is 1 bytes
If Length = 2, it means data length is 2 bytes

http://testbench.in/SL_02_SPECIFICATION.html[9/26/2012 2:28:08 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

If Length = 255, it means data length is 255 bytes

Data: Data should be in terms of bytes and can take anything.

FCS: Frame check sequence


 This field contains the security check of the packet. It is calculated over the header
and data.

Configuration:

Switch has four output ports. These output ports address have to be configured to a
unique address. Switch matches the DA field of the packet with this configured port
address and sends the packet on to that port. Switch contains a memory. This
memory has 4 locations, each can store 8 bits. To configure the switch port address,
memory write operation has to be done using memory interface. Memory address
(0,1,2,3) contains the address of port(0,1,2,3) respectively.

Interface Specification:

The Switch has one input Interface, from where the packet enters and 4 output
interfaces from where the packet comes out and one memory interface, through the
port address can be configured.  Switch also has a clock and asynchronous reset
signal.  

 
Memory Interface:

Through memory interfaced output port address are configured. It accepts 8 bit data
to be written to memory. It has 8 bit address inputs. Address 0,1,2,3 contains the
address of the port 0,1,2,3 respectively.

There are 4 input signals to memory interface. They are

input mem_en;
input mem_rd_wr;
input [1:0] mem_add;
input [7:0] mem_data;

All the signals are active high and are synchronous to the positive edge of clock
signal.
To configure a port address,
1.      Assert the mem_en signal.

http://testbench.in/SL_02_SPECIFICATION.html[9/26/2012 2:28:08 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

2.      Asser the mem_rd_wr signal.


3.      Drive the port number (0 or 1 or 2 or 3) on the mem_add signal
4.      Drive the 8 bit port address on to mem_data signal.

Input Port

Packets are sent into the switch using input port.


All the signals are active high and are synchronous to the positive edge of clock
signal.

input port has 2 input signals. They are


input [7:0] data;
input data_status;

To send the packet in to switch,

1. Assert the data_status signal.


2. Send the packet on the data signal byte by byte.
3. After sending all the data bytes, deassert the data_status signal.
4. There should be at least 3 clock cycles difference between packets.

Output Port

Switch sends the packets out using the output ports.  There are 4 ports, each having
data, ready and read signals.  All the signals are active high and are synchronous to
the positive edge of clock signal.

Signal list is

output   [7:0] port0;
output   [7:0] port1;
output   [7:0] port2;
output   [7:0] port3;
output         ready_0;
output       ready_1;
output       ready_2;
output       ready_3;
input       read_0;
input       read_1;
input       read_2;
input       read_3;

When the data is ready to be sent out from the port, switch asserts ready_* signal
high indicating that data is ready to be sent.
If the read_* signal is asserted, when ready_* is high, then the data comes out of the
port_* signal after one clock cycle.

http://testbench.in/SL_02_SPECIFICATION.html[9/26/2012 2:28:08 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

RTL  code:

RTL code is attached with the tar files. From the Phase 1, you can download the tar
files.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SL_02_SPECIFICATION.html[9/26/2012 2:28:08 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS VERIFICATION PLAN Index


Introduction
SystemVerilog Overview Specification
Verification Verification Plan
This Document describes the Verification Plan for Switch. The Verification Plan is Phase 1 Top
Constructs based on System Verilog Hardware Verification Language. The methodology used for Phase 2 Environment
Interface Verification is Constraint random coverage driven verification. Phase 3 Reset
Phase 4 Packet
OOPS Phase 5 Driver
Randomization Feature Extraction Phase 6 Receiver
Phase 7 Scoreboard
Functional Coverage Phase 8 Coverage
This section contains list of all the features to be verified.
Assertion 1) Phase 9 Testcase
DPI ID:  Configuration
Description: Configure all the 4 port address with unique values. Report a Bug or Comment
UVM Tutorial on This section - Your
2) input is what keeps
VMM Tutorial
ID: Packet DA Testbench.in improving
OVM Tutorial Description: DA field of packet should be any of the port address. All the 4 port with time!
Easy Labs : SV address should be used.
Easy Labs : UVM 3)
Easy Labs : OVM ID : Packet payload
Description: Length can be from 0 to 255. Send packets with all the lengths.
Easy Labs : VMM
AVM Switch TB 4)
ID: Length
VMM Ethernet sample Description:
Length field contains length of the payload.
Send Packet with correct length field and incorrect length fields.
Verilog
Verification 5)
ID: FCS
Verilog Switch TB Description:
Basic Constructs Good FCS:  Send packet with good FCS.
Bad FCS: Send packet with corrupted FCS.  

OpenVera Stimulus Generation Plan


Constructs
Switch TB 1) Packet DA: Generate packet DA with the configured address.
2) Payload length: generate payload length ranging from 2 to 255.
RVM Switch TB 3) Correct or Incorrect Length field.
RVM Ethernet sample 4) Generate good and bad FCS.

Coverage Plan
Specman E
Interview Questions 1)      Cover all the port address configurations.
2)      Cover all the packet lengths.
3)      Cover all correct and incorrect length fields.
4)      Cover good and bad FCS.
5)      Cover all the above combinations.

Verification Environment

http://testbench.in/SL_03_VERIFICATION_PLAN.html[9/26/2012 2:28:17 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SL_03_VERIFICATION_PLAN.html[9/26/2012 2:28:17 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PHASE 1 TOP Index


Introduction
SystemVerilog Specification
Verification In phase 1, Verification Plan
Phase 1 Top
Constructs 1) We will write SystemVerilog Interfaces for input port, output port and memory Phase 2 Environment
Interface port. Phase 3 Reset
2) We will write Top module where testcase and DUT instances are done. Phase 4 Packet
OOPS Phase 5 Driver
3) DUT and TestBench interfaces are connected in top module.
Randomization 4) Clock is generator in top module. Phase 6 Receiver
Phase 7 Scoreboard
Functional Coverage Phase 8 Coverage
Assertion NOTE: In every file you will see the syntax Phase 9 Testcase
DPI `ifndef GUARD_*
`endif GUARD_*  Report a Bug or Comment
UVM Tutorial on This section - Your
input is what keeps
VMM Tutorial
Testbench.in improving
OVM Tutorial Interfaces with time!
Easy Labs : SV
In the interface.sv file, declare the 3 interfaces in the following way.
Easy Labs : UVM All the interfaces has clock as input.
Easy Labs : OVM All the signals in interface are logic type.
Easy Labs : VMM All the signals are synchronized to clock except reset in clocking block.
Signal directional w.r.t TestBench is specified with modport.
AVM Switch TB
VMM Ethernet sample
`ifndef GUARD_INTERFACE
`define GUARD_INTERFACE
Verilog
//////////////////////////////////////////
Verification // Interface declaration for the memory///
Verilog Switch TB //////////////////////////////////////////
Basic Constructs interface mem_interface(input bit clock);
  logic [7:0] mem_data;
  logic [1:0] mem_add;
OpenVera   logic       mem_en;
Constructs   logic       mem_rd_wr;
  
Switch TB   clocking cb@(posedge clock);
RVM Switch TB      default input #1 output #1;
     output     mem_data;
RVM Ethernet sample      output      mem_add;
     output mem_en;
     output mem_rd_wr;
Specman E   endclocking
  
Interview Questions   modport MEM(clocking cb,input clock);

endinterface

////////////////////////////////////////////
// Interface for the input side of switch.//
// Reset signal is also passed hear.      //
////////////////////////////////////////////
interface input_interface(input bit clock);
  logic           data_status;
  logic     [7:0] data_in;

http://testbench.in/SL_04_PHASE_1_TOP.html[9/26/2012 2:28:27 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

  logic           reset; 

  clocking cb@(posedge clock);
     default input #1 output #1;
     output    data_status;
     output    data_in;
  endclocking
  
  modport IP(clocking cb,output reset,input clock);
  
endinterface

/////////////////////////////////////////////////
// Interface for the output side of the switch.//
// output_interface is for only one output port//
/////////////////////////////////////////////////

interface output_interface(input bit clock);
  logic    [7:0] data_out;
  logic    ready;
  logic    read;
  
  clocking cb@(posedge clock);
    default input #1 output #1;
    input     data_out;
    input     ready;
    output    read;
  endclocking
  
  modport OP(clocking cb,input clock);

endinterface

//////////////////////////////////////////////////

`endif 

Testcase

Testcase is a program block which provides an entry point for the test and creates a
scope that encapsulates program-wide data. Currently this is an empty testcase which
just ends the simulation after 100 time units.  Program block contains all the above
declared interfaces as arguments. This testcase has initial and final blocks.

`ifndef GUARD_TESTCASE
`define GUARD_TESTCASE

program testcase(mem_interface.MEM mem_intf,input_interface.IP input_intf,output_interface.OP output_intf[4
]);

initial
begin
$display(" ******************* Start of testcase ****************");

#1000;
end

final
$display(" ******************** End of testcase *****************");

endprogram 
`endif

Top Module

The modules that are included in the source text but are not instantiated are called

http://testbench.in/SL_04_PHASE_1_TOP.html[9/26/2012 2:28:27 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

top modules. This module is the highest scope of modules. Generally this module is
named as "top" and referenced as "top module".  Module name can be anything.

Do the following in the top module:

1)Generate the clock signal.

bit Clock;

initial
  forever #10 Clock = ~Clock;

2)Do the instances of memory interface.

mem_interface mem_intf(Clock);

3)Do the instances of input interface.

input_interface input_intf(Clock);

4)There are 4 output ports. So do 4 instances of output_interface.

output_interface output_intf[4](Clock);

5)Do the instance of testcase and pass all the above declared interfaces.

testcase TC (mem_intf,input_intf,output_intf);

6)Do the instance of DUT.

switch DUT    (.

7)Connect all the interfaces and DUT.  The design which we have taken is in
verilog.  So Verilog DUT instance is connected signal by signal.

switch DUT    (.clk(Clock),
               .reset(input_intf.reset),
               .data_status(input_intf.data_status),
               .data(input_intf.data_in),
               .port0(output_intf[0].data_out),
               .port1(output_intf[1].data_out),
               .port2(output_intf[2].data_out),
               .port3(output_intf[3].data_out),
               .ready_0(output_intf[0].ready),
               .ready_1(output_intf[1].ready),
               .ready_2(output_intf[2].ready),
               .ready_3(output_intf[3].ready),
               .read_0(output_intf[0].read),
               .read_1(output_intf[1].read),
               .read_2(output_intf[2].read),
               .read_3(output_intf[3].read),
               .mem_en(mem_intf.mem_en),
               .mem_rd_wr(mem_intf.mem_rd_wr),
               .mem_add(mem_intf.mem_add),
               .mem_data(mem_intf.mem_data));

http://testbench.in/SL_04_PHASE_1_TOP.html[9/26/2012 2:28:27 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

Top Module Source Code:

`ifndef GUARD_TOP
`define GUARD_TOP

module top();

/////////////////////////////////////////////////////
// Clock Declaration and Generation                //
/////////////////////////////////////////////////////
bit Clock;

initial
  forever #10 Clock = ~Clock;

/////////////////////////////////////////////////////
//  Memory interface instance                      //
/////////////////////////////////////////////////////

mem_interface mem_intf(Clock);

/////////////////////////////////////////////////////
//  Input interface instance                       //
/////////////////////////////////////////////////////

input_interface input_intf(Clock);

/////////////////////////////////////////////////////
//  output interface instance                      //
/////////////////////////////////////////////////////

output_interface output_intf[4](Clock);

/////////////////////////////////////////////////////
//  Program block Testcase instance                //
/////////////////////////////////////////////////////

testcase TC (mem_intf,input_intf,output_intf);

/////////////////////////////////////////////////////
//  DUT instance and signal connection             //
/////////////////////////////////////////////////////

switch DUT    (.clk(Clock),
               .reset(input_intf.reset),
               .data_status(input_intf.data_status),

http://testbench.in/SL_04_PHASE_1_TOP.html[9/26/2012 2:28:27 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

               .data(input_intf.data_in),
               .port0(output_intf[0].data_out),
               .port1(output_intf[1].data_out),
               .port2(output_intf[2].data_out),
               .port3(output_intf[3].data_out),
               .ready_0(output_intf[0].ready),
               .ready_1(output_intf[1].ready),
               .ready_2(output_intf[2].ready),
               .ready_3(output_intf[3].ready),
               .read_0(output_intf[0].read),
               .read_1(output_intf[1].read),
               .read_2(output_intf[2].read),
               .read_3(output_intf[3].read),
               .mem_en(mem_intf.mem_en),
               .mem_rd_wr(mem_intf.mem_rd_wr),
               .mem_add(mem_intf.mem_add),
               .mem_data(mem_intf.mem_data));

endmodule

`endif

Download the phase 1 files:

switch_1.tar
Browse the code in switch_1.tar

Run the simulation:


vcs -sverilog -f filelist -R -ntb_opts dtm

Log file after simulation:

 ******************* Start of testcase ****************


 ******************** End of testcase *****************

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SL_04_PHASE_1_TOP.html[9/26/2012 2:28:27 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PHASE 2 ENVIRONMENT Index


Introduction
SystemVerilog Specification
Verification In this phase, we will write Verification Plan
Phase 1 Top
Constructs Phase 2 Environment
Environment class.
Interface Phase 3 Reset
Virtual interface declaration. Phase 4 Packet
OOPS Defining Environment class constructor. Phase 5 Driver
Randomization
Defining required methods for execution. Currently these methods will not be Phase 6 Receiver
implemented in this phase. Phase 7 Scoreboard
Functional Coverage Phase 8 Coverage
Assertion All the above are done in Environment.sv file. Phase 9 Testcase
DPI We will write a testcase using the above define environment class in testcase.sv file. Report a Bug or Comment
UVM Tutorial on This section - Your
input is what keeps
VMM Tutorial Environment Class: Testbench.in improving
OVM Tutorial with time!
Easy Labs : SV The class is a base class used to implement verification environments. Testcase
Easy Labs : UVM contains the instance of the environment class and has access to all the public
declaration of environment class.
Easy Labs : OVM
Easy Labs : VMM
All methods are declared as virtual methods. In environment class, we will formalize
AVM Switch TB the simulation steps using virtual methods.  The methods are used to control the
VMM Ethernet sample execution of the simulation.

Following are the methods which are going to be defined in environment class.
Verilog
1) new() : In constructor method, we will connect the virtual interfaces which are
Verification passed as argument to the virtual interfaces to those which are declared in
Verilog Switch TB environment class.
Basic Constructs 2) build(): In this method , all the objects like driver, monitor etc are constructed.
Currently this method is empty as we did not develop any other component.

OpenVera 3) reset(): in this method we will reset the DUT.


Constructs
4) cfg_dut(): In this method, we will configure the DUT output port address.
Switch TB
RVM Switch TB 5) start(): in this method, we will call the methods which are declared in the other
components like driver and monitor.
RVM Ethernet sample
6) wait_for_end(): this method is used to wait for the end of the simulation.  Waits
until all the required operations in other components are done.
Specman E
7) report(): This method is used to print the TestPass and TestFail status of the
Interview Questions simulation, based on the error count..

8) run(): This method calls all the above declared methods in a sequence order. The
testcase calls this method, to start the simulation.

We are not implementing build(), reset(), cfg_dut() , strat() and report() methods  in
this phase.

Connecting the virtual interfaces of Environment class to the physical interfaces of

http://testbench.in/SL_05_PHASE_2_ENVIRONMENT.html[9/26/2012 2:28:38 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

top module.

Verification environment contains the declarations of the virtual interfaces. Virtual


interfaces are just a handles(like pointers). When a virtual interface is declared, it
only creats a handle. It doesnot creat a real interface.

Constructor method should be declared with virtual interface as arguments, so that


when the object is created in testcase, new() method can pass the interfaces in to
environment class where they are assigned to the local virtual interface handle. With
this, the Environment class  virtual interfaces are pointed to the physical interfaces
which are declared in the top module.

Declare virtual interfaces in Environment  class.

  virtual mem_interface.MEM    mem_intf      ;
  virtual input_interface.IP  input_intf     ;
  virtual output_interface.OP output_intf[4] ;

The construction of Environment class is declared with virtual interface as arguments.

function new(virtual mem_interface.MEM    mem_intf_new       ,
             virtual input_interface.IP  input_intf_new     ,
             virtual output_interface.OP output_intf_new[4] );

In constructor methods, the interfaces which are arguments are connected to the
virtual interfaces of environment class.

  this.mem_intf      = mem_intf_new    ;
  this.input_intf    = input_intf_new  ;
  this.output_intf   = output_intf_new ;

Run :

The run() method is called from the testcase to start the simulation. run() method
calls all the methods which are defined in the Environment class.

task run();
 $display(" %0d : Environment  : start of run() method",$time);
 build();
 reset();
 cfg_dut();
 start();
 wait_for_end();
 report();

http://testbench.in/SL_05_PHASE_2_ENVIRONMENT.html[9/26/2012 2:28:38 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

 $display(" %0d : Environment  : end of run() method",$time);


endtask : run

Environment Class Source Code:

`ifndef GUARD_ENV
`define GUARD_ENV

class Environment ;

  virtual mem_interface.MEM    mem_intf      ;
  virtual input_interface.IP  input_intf     ;
  virtual output_interface.OP output_intf[4] ;

function new(virtual mem_interface.MEM    mem_intf_new       ,
             virtual input_interface.IP  input_intf_new     ,
             virtual output_interface.OP output_intf_new[4] );

  this.mem_intf      = mem_intf_new    ;
  this.input_intf    = input_intf_new  ;
  this.output_intf   = output_intf_new ;
  
  $display(" %0d : Environment  : created env object",$time);
endfunction : new

function void build();
 $display(" %0d : Environment  : start of build() method",$time);
 $display(" %0d : Environment  : end of build() method",$time);
endfunction :build

task reset();
 $display(" %0d : Environment  : start of reset() method",$time);
 $display(" %0d : Environment  : end of reset() method",$time);
endtask : reset

task cfg_dut();
 $display(" %0d : Environment  : start of cfg_dut() method",$time);
 $display(" %0d : Environment  : end of cfg_dut() method",$time);
endtask : cfg_dut

task start();
 $display(" %0d : Environment  : start of start() method",$time);
 $display(" %0d : Environment  : end of start() method",$time);
endtask : start

task wait_for_end();

http://testbench.in/SL_05_PHASE_2_ENVIRONMENT.html[9/26/2012 2:28:38 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

 $display(" %0d : Environment  : start of wait_for_end() method",$time);


 $display(" %0d : Environment  : end of wait_for_end() method",$time);
endtask : wait_for_end

task run();
 $display(" %0d : Environment  : start of run() method",$time);
 build();
 reset();
 cfg_dut();
 start();
 wait_for_end();
 report();
 $display(" %0d : Environment  : end of run() method",$time);
endtask : run

task report();
endtask : report

endclass

`endif

We will create a file Global.sv for global requirement. In this file,  define all the port
address as macros in this file. Define a variable error as integer to keep track the
number of errors occurred during the simulation.

`ifndef GUARD_GLOBALS
`define GUARD_GLOBALS

`define P0 8'h00
`define P1 8'h11
`define P2 8'h22
`define P3 8'h33

int error = 0;
int num_of_pkts = 10;

`endif

Now we will update the testcase. Take an instance of the Environment class and call
the run method of the Environment class.

`ifndef GUARD_TESTCASE
`define GUARD_TESTCASE

program testcase(mem_interface.MEM mem_intf,input_interface.IP


input_intf,output_interface.OP output_intf[4]);

Environment env;

initial
begin
$display(" ******************* Start of testcase ****************");

env = new(mem_intf,input_intf,output_intf);
env.run();

#1000;
end

final
$display(" ******************** End of testcase *****************");

endprogram
`endif

Download the phase 2 source code:

switch_2.tar
Browse the code in switch_2.tar

http://testbench.in/SL_05_PHASE_2_ENVIRONMENT.html[9/26/2012 2:28:38 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

Run the simulation:


vcs -sverilog -f filelist -R -ntb_opts dtm

Log report after the simulation:

 ******************* Start of testcase ****************


 0 : Environemnt : created env object
 0 : Environemnt : start of run() method
 0 : Environemnt : start of build() method
 0 : Environemnt : end of build() method
 0 : Environemnt : start of reset() method
 0 : Environemnt : end of reset() method
 0 : Environemnt : start of cfg_dut() method
 0 : Environemnt : end of cfg_dut() method
 0 : Environemnt : start of start() method
 0 : Environemnt : end of start() method
 0 : Environemnt : start of wait_for_end() method
 0 : Environemnt : end of wait_for_end() method
 0 : Environemnt : end of run() method
 ******************** End of testcase *****************

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SL_05_PHASE_2_ENVIRONMENT.html[9/26/2012 2:28:38 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PHASE 3 RESET Index


Introduction
SystemVerilog Specification
Verification In this phase we will reset and configure the DUT. Verification Plan
Phase 1 Top
Constructs The Environment class has reset() method which contains the logic to reset the DUT Phase 2 Environment
Interface and cfg_dut() method which contains the logic to configure the DUT port address. Phase 3 Reset
Phase 4 Packet
OOPS Phase 5 Driver
Randomization Phase 6 Receiver
Phase 7 Scoreboard
Functional Coverage Phase 8 Coverage
Assertion Phase 9 Testcase
DPI Report a Bug or Comment
UVM Tutorial on This section - Your
input is what keeps
VMM Tutorial
Testbench.in improving
OVM Tutorial with time!
Easy Labs : SV
Easy Labs : UVM
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

NOTE: Clocking block signals can be driven only using a non-blocking assignment.


Verilog
Verification
Verilog Switch TB Define the reset() method.
1) Set all the DUT input signals to a known state.
Basic Constructs

  mem_intf.cb.mem_data      <= 0;
OpenVera   mem_intf.cb.mem_add       <= 0;
  mem_intf.cb.mem_en        <= 0;
Constructs
  mem_intf.cb.mem_rd_wr     <= 0;
Switch TB   input_intf.cb.data_in     <= 0;
  input_intf.cb.data_status <= 0;
RVM Switch TB
  output_intf[0].cb.read    <= 0;
RVM Ethernet sample   output_intf[1].cb.read    <= 0;
  output_intf[2].cb.read    <= 0;
  output_intf[3].cb.read    <= 0;
Specman E
Interview Questions 2) Reset the DUT.

  // Reset the DUT


  input_intf.reset       <= 1;
  repeat (4) @ input_intf.clock;
  input_intf.reset       <= 0;

3) Updated the cfg_dut method.

task cfg_dut();

http://testbench.in/SL_06_PHASE_3_RESET.html[9/26/2012 2:28:48 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

  $display(" %0d : Environment  : start of cfg_dut() method",$time);


  
  mem_intf.cb.mem_en <= 1;
  @(posedge mem_intf.clock);
  mem_intf.cb.mem_rd_wr <= 1;
  
  @(posedge mem_intf.clock);
  mem_intf.cb.mem_add  <= 8'h0;
  mem_intf.cb.mem_data <= `P0;
  $display(" %0d : Environment  : Port 0 Address %h ",$time,`P0);
  
  @(posedge mem_intf.clock);
  mem_intf.cb.mem_add  <= 8'h1;
  mem_intf.cb.mem_data <= `P1;
  $display(" %0d : Environment  : Port 1 Address %h ",$time,`P1);
  
  @(posedge mem_intf.clock);
  mem_intf.cb.mem_add  <= 8'h2;
  mem_intf.cb.mem_data <= `P2;
  $display(" %0d : Environment  : Port 2 Address %h ",$time,`P2);
  
  @(posedge mem_intf.clock);
  mem_intf.cb.mem_add  <= 8'h3;
  mem_intf.cb.mem_data <= `P3;
  $display(" %0d : Environment  : Port 3 Address %h ",$time,`P3);
  
  @(posedge mem_intf.clock);
  mem_intf.cb.mem_en    <=0;
  mem_intf.cb.mem_rd_wr <= 0;
  mem_intf.cb.mem_add   <= 0;
  mem_intf.cb.mem_data  <= 0;
  
  
  $display(" %0d : Environment  : end of cfg_dut() method",$time);
endtask : cfg_dut

(4) In wait_for_end method, wait for some clock cycles.

task wait_for_end();
  $display(" %0d : Environment  : start of wait_for_end() method",$time);
  repeat(10000) @(input_intf.clock);
  $display(" %0d : Environment  : end of wait_for_end() method",$time);
endtask : wait_for_end

Download the Phase 3 source code:

switch_3.tar
Browse the code in switch_3.tar

Run the simulation:


vcs -sverilog -f filelist -R -ntb_opts dtm

Log File report

 ******************* Start of testcase ****************


 0 : Environment : created env object
 0 : Environment : start of run() method
 0 : Environment : start of build() method
 0 : Environment : end of build() method
 0 : Environment : start of reset() method
 40 : Environment : end of reset() method
 40 : Environment : start of cfg_dut() method
 70 : Environment : Port 0 Address 00
 90 : Environment : Port 1 Address 11
 110 : Environment : Port 2 Address 22
 130 : Environment : Port 3 Address 33
 150 : Environment : end of cfg_dut() method

http://testbench.in/SL_06_PHASE_3_RESET.html[9/26/2012 2:28:48 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

 150 : Environment : start of start() method


 150 : Environment : end of start() method
 150 : Environment : start of wait_for_end() method
 100150 : Environment : end of wait_for_end() method
 100150 : Environment : end of run() method
 ******************** End of testcase *****************

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SL_06_PHASE_3_RESET.html[9/26/2012 2:28:48 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PHASE 4 PACKET Index


Introduction
SystemVerilog Specification
Verification In this Phase, We will define a packet and then test it whether it is generating as Verification Plan
expected. Phase 1 Top
Constructs Phase 2 Environment
Interface Packet is modeled using class. Packet class should be able to generate all possible Phase 3 Reset
packet types randomly. Packet class should also implement required methods like Phase 4 Packet
OOPS Phase 5 Driver
packing(), unpacking(), compare() and display() methods.
Randomization Phase 6 Receiver
We will write the packet class in packet.sv file. Packet class variables and constraints Phase 7 Scoreboard
Functional Coverage Phase 8 Coverage
have been derived from stimulus generation plan.
Assertion Phase 9 Testcase
DPI Revisit Stimulus Generation Plan
1) Packet DA: Generate packet DA with the configured address. Report a Bug or Comment
UVM Tutorial 2) Payload length: generate payload length ranging from 2 to 255. on This section - Your
3) Correct or Incorrect Length field. input is what keeps
VMM Tutorial
4) Generate good and bad FCS. Testbench.in improving
OVM Tutorial with time!
Easy Labs : SV 1) Declare FCS types as enumerated data types. Name members as GOOD_FCS and
BAD_FCS.
Easy Labs : UVM
Easy Labs : OVM typedef enum { GOOD_FCS, BAD_FCS } fcs_kind_t;
Easy Labs : VMM 2) Declare the length type as enumerated data type. Name members as
AVM Switch TB GOOD_LENGTH and BAD_LENGTH.
VMM Ethernet sample typedef enum { GOOD_LENGTH, BAD_LENGTH } length_kind_t;

3) Declare the length type and fcs type variables as rand.


Verilog
Verification rand fcs_kind_t     fcs_kind;
rand length_kind_t  length_kind;
Verilog Switch TB
Basic Constructs 4) Declare the packet field as rand. All fields are bit data types. All fields are 8 bit
packet array. Declare the payload as dynamic array.

rand bit [7:0] length;
OpenVera rand bit [7:0] da;
Constructs rand bit [7:0] sa;
Switch TB rand byte data[];//Payload using Dynamic array,size is generated on the fly
rand byte fcs;
RVM Switch TB
RVM Ethernet sample 5) Constraint the DA field to be any one of the configured address.
constraint address_c { da inside {`P0,`P1,`P2,`P3} ; }
Specman E 6) Constrain the payload dynamic array size to between 1 to 255.
Interview Questions
constraint payload_size_c { data.size inside { [1 : 255]};}

7) Constrain the payload length to the length field based on the length type.

constraint length_kind_c { 
   (length_kind == GOOD_LENGTH) -> length == data.size; 
   (length_kind == BAD_LENGTH)  -> length == data.size + 2 ; }

Use solve before to direct the randomization to generate first the payload dynamic

http://testbench.in/SL_07_PHASE_4_PACKET.html[9/26/2012 2:28:58 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

array size and then randomize length field.

constraint solve_size_length { solve  data.size before length; }

8) Constrain the FCS field initial value based on the fcs kind field.

constraint fcs_kind_c {
   (fcs_kind == GOOD_FCS) -> fcs == 8'b0;
   (fcs_kind == BAD_FCS)  -> fcs == 8'b1; }

9) Define the FCS method.

function byte cal_fcs;
  integer i;
  byte result ;
  result = 0;
  result = result ^ da;
  result = result ^ sa;
  result = result ^ length;
  for (i = 0;i< data.size;i++)
  result = result ^ data[i];
  result = fcs ^ result;
  return result;
endfunction : cal_fcs

10) Define display methods:


Display method displays the current value of the packet fields to standard output.

virtual function void display();
  $display("\n---------------------- PACKET  KIND ------------------------- ");
  $display("  fcs_kind     : %s ",fcs_kind.name()    );
  $display("  length_kind  : %s ",length_kind.name() );
  $display("-------- PACKET ---------- ");
  $display("  0 : %h ",da); 
  $display("  1 : %h ",sa); 
  $display("  2 : %h ",length);
  foreach(data[i]) 
  $write("%3d : %0h ",i + 3,data[i]); 
  $display("\n %2d : %h ",data.size() + 3 , cal_fcs); 
$display("----------------------------------------------------------- \n");
endfunction : display

11) Define pack method:

Packing is commonly used to convert the high level data to low level data that can be
applied to DUT.  In packet class various fields are generated. Required fields are
concatenated to form a stream of bytes which can be driven conveniently to DUT
interface by the driver.

virtual function int unsigned byte_pack(ref logic [7:0] bytes[]);

http://testbench.in/SL_07_PHASE_4_PACKET.html[9/26/2012 2:28:58 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

  bytes = new[data.size + 4];
  bytes[0] = da;
  bytes[1] = sa;
  bytes[2] = length;
  foreach(data[i]) 
  bytes[3 + i] = data[i];
  bytes[data.size() + 3] = cal_fcs;
  byte_pack = bytes.size;
endfunction : byte_pack

12) Define unpack method:

The unpack() method does exactly the opposite of pack method. Unpacking is
commonly used to convert a data stream coming from DUT to high level data packet
object.

virtual function void byte_unpack(const ref logic [7:0] bytes[]);
  this.da = bytes[0];
  this.sa = bytes[1];
  this.length = bytes[2];
  this.fcs = bytes[bytes.size - 1];
  this.data = new[bytes.size - 4];
  foreach(data[i]) 
  data[i] = bytes[i + 3];
  this.fcs = 0;
  if(bytes[bytes.size - 1] != cal_fcs)
  this.fcs = 1;
endfunction : byte_unpack

14) Define a compare method.


Compares the current value of the object instance with the current value of the
specified object instance.
If the value is different, FALSE is returned.

virtual function bit compare(packet pkt);
compare = 1;
if(pkt == null)
   begin
      $display(" ** ERROR ** : pkt : received a null object ");
      compare = 0;
   end
   else
      begin
         if(pkt.da !== this.da)
         begin
            $display(" ** ERROR **: pkt : Da field did not match");
            compare = 0;
         end
         if(pkt.sa !== this.sa)
         begin
            $display(" ** ERROR **: pkt : Sa field did not match");
            compare = 0;
         end

         if(pkt.length !== this.length)


         begin

http://testbench.in/SL_07_PHASE_4_PACKET.html[9/26/2012 2:28:58 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

            $display(" ** ERROR **: pkt : Length field did not match");


            compare = 0;
         end
         foreach(this.data[i])
         if(pkt.data[i] !== this.data[i])
         begin
            $display(" ** ERROR **: pkt : Data[%0d] field did not match",i);
            compare = 0;
         end
  
         if(pkt.fcs !== this.fcs)
         begin
            $display(" ** ERROR **: pkt : fcs field did not match %h %h",pkt.fcs ,this.fcs);
            compare = 0;
         end
      end
endfunction : compare

Packet Class Source Code

`ifndef GUARD_PACKET
`define GUARD_PACKET

//Define the enumerated types for packet types


typedef enum { GOOD_FCS, BAD_FCS } fcs_kind_t;
typedef enum { GOOD_LENGTH, BAD_LENGTH } length_kind_t;

class packet;
rand fcs_kind_t     fcs_kind;
rand length_kind_t  length_kind;

rand bit [7:0] length;
rand bit [7:0] da;
rand bit [7:0] sa;
rand byte data[];//Payload using Dynamic array,size is generated on the fly
rand byte fcs;

constraint address_c { da inside {`P0,`P1,`P2,`P3} ; }

constraint payload_size_c { data.size inside { [1 : 255]};}

constraint length_kind_c { 
   (length_kind == GOOD_LENGTH) -> length == data.size; 
   (length_kind == BAD_LENGTH)  -> length == data.size + 2 ; }
                
constraint solve_size_length { solve  data.size before length; }

constraint fcs_kind_c {
   (fcs_kind == GOOD_FCS) -> fcs == 8'b0;
   (fcs_kind == BAD_FCS)  -> fcs == 8'b1; }

///// method to calculate the fcs /////


function byte cal_fcs;
  integer i;
  byte result ;
  result = 0;
  result = result ^ da;
  result = result ^ sa;
  result = result ^ length;
  for (i = 0;i< data.size;i++)
  result = result ^ data[i];
  result = fcs ^ result;
  return result;
endfunction : cal_fcs

///// method to print the packet fields ////


virtual function void display();
  $display("\n---------------------- PACKET  KIND ------------------------- ");
  $display("  fcs_kind     : %s ",fcs_kind.name()    );
  $display("  length_kind  : %s ",length_kind.name() );
  $display("-------- PACKET ---------- ");
  $display("  0 : %h ",da); 
  $display("  1 : %h ",sa); 
  $display("  2 : %h ",length);

http://testbench.in/SL_07_PHASE_4_PACKET.html[9/26/2012 2:28:58 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

  foreach(data[i]) 
  $write("%3d : %0h ",i + 3,data[i]); 
  $display("\n %2d : %h ",data.size() + 3 , cal_fcs); 
$display("----------------------------------------------------------- \n");
endfunction : display

///// method to pack the packet into bytes/////


virtual function int unsigned byte_pack(ref logic [7:0] bytes[]);
  bytes = new[data.size + 4];
  bytes[0] = da;
  bytes[1] = sa;
  bytes[2] = length;
  foreach(data[i]) 
  bytes[3 + i] = data[i];
  bytes[data.size() + 3] = cal_fcs;
  byte_pack = bytes.size;
endfunction : byte_pack

////method to unpack the bytes in to packet /////


virtual function void byte_unpack(const ref logic [7:0] bytes[]);
  this.da = bytes[0];
  this.sa = bytes[1];
  this.length = bytes[2];
  this.fcs = bytes[bytes.size - 1];
  this.data = new[bytes.size - 4];
  foreach(data[i]) 
  data[i] = bytes[i + 3];
  this.fcs = 0;
  if(bytes[bytes.size - 1] != cal_fcs)
  this.fcs = 1;
endfunction : byte_unpack

//// method to compare the packets /////


virtual function bit compare(packet pkt);
compare = 1;
if(pkt == null)
   begin
      $display(" ** ERROR ** : pkt : received a null object ");
      compare = 0;
   end
   else
      begin
         if(pkt.da !== this.da)
         begin
            $display(" ** ERROR **: pkt : Da field did not match");
            compare = 0;
         end
         if(pkt.sa !== this.sa)
         begin
            $display(" ** ERROR **: pkt : Sa field did not match");
            compare = 0;
         end

         if(pkt.length !== this.length)


         begin
            $display(" ** ERROR **: pkt : Length field did not match");
            compare = 0;
         end
         foreach(this.data[i])
         if(pkt.data[i] !== this.data[i])
         begin
            $display(" ** ERROR **: pkt : Data[%0d] field did not match",i);
            compare = 0;
         end
  
         if(pkt.fcs !== this.fcs)
         begin
            $display(" ** ERROR **: pkt : fcs field did not match %h %h",pkt.fcs ,this.fcs);
            compare = 0;
         end
      end
endfunction : compare

endclass

http://testbench.in/SL_07_PHASE_4_PACKET.html[9/26/2012 2:28:58 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

Now we will write a small program to test our packet implantation. This program
block is not used to verify the DUT.

Write a simple program block and do the instance of packet class. Randomize the
packet and call the display method to analyze the generation. Then pack the packet
in to bytes and then unpack bytes and then call compare method to check all the
methods.

Program Block Source Code

program test;

packet pkt1 = new();


packet pkt2 = new();
logic [7:0] bytes[];
initial
repeat(10)
if(pkt1.randomize)
begin
$display(" Randomization Successes full.");
pkt1.display();
void'(pkt1.byte_pack(bytes));
pkt2 = new();
pkt2.byte_unpack(bytes);
if(pkt2.compare(pkt1))
$display(" Packing,Unpacking and compare worked");
else
$display(" *** Something went wrong in Packing or Unpacking or compare ***");

end
else
$display(" *** Randomization Failed ***");

endprogram

Download the packet class with program block.

switch_4.tar
Browse the code in switch_4.tar

Run the simulation


vcs -sverilog -f filelist -R -ntb_opts dtm

Log file report:

 Randomization Sucessesfull.

---------------------- PACKET  KIND -------------------------


  fcs_kind     : BAD_FCS
  length_kind  : GOOD_LENGTH
-------- PACKET ----------
  0 : 00
  1 : f7
  2 : be
  3 : a6   4 : 1b   5 : b5   6 : fa   7 : 4e   8 : 15   9 : 7d  10 : 72  11 : 96  12 : 31  13 :
c4  14 : aa  15 : c4  16 : cf  17 : 4f  18 : f4  19 : 17  20 : 88  21 : f1  22 : 2c  23 : ce  24
: 5  25 : cb  26 : 8c  27 : 1a  28 : 37  29 : 60  30 : 5f  31 : 7a  32 : a2  33 : f0  34 :
c9  35 : dc  36 : 41  37 : 3f  38 : 12  39 : f4  40 : df  41 : c5  42 : d7  43 : 94  44 :
88  45 : 1  46 : 31  47 : 29  48 : d6  49 : f4  50 : d9  51 : 4f  52 : 0  53 : dd  54 : d2  55
: a6  56 : 59  57 : 43  58 : 45  59 : f2  60 : a2  61 : a1  62 : fd  63 : ea  64 : c1  65 :
20  66 : c7  67 : 20  68 : e1  69 : 97  70 : c6  71 : cf  72 : cd  73 : 17  74 : 99  75 :
49  76 : b8  77 : 1c  78 : df  79 : e6  80 : 1a  81 : ce  82 : 8c  83 : ec  84 : b6  85 :
bb  86 : a5  87 : 17  88 : cb  89 : 32  90 : e1  91 : 83  92 : 96  93 : e  94 : ee  95 :
57  96 : 33  97 : cd  98 : 62  99 : 88 100 : 7b 101 : e6 102 : 41 103 : ad 104 : 26 105 :
ee 106 : 9c 107 : 95 108 : a7 109 : b8 110 : 83 111 : f 112 : ca 113 : ec 114 : b5 115 :
8d 116 : d8 117 : 2f 118 : 6f 119 : ea 120 : 4c 121 : 35 122 : 41 123 : f2 124 : 4e 125
: 89 126 : d8 127 : 78 128 : f1 129 : d 130 : d6 131 : d5 132 : 8 133 : c 134 : de 135 :
a9 136 : 1d 137 : a0 138 : ae 139 : 99 140 : f5 141 : 53 142 : d8 143 : 7a 144 : 4c 145
: d4 146 : b8 147 : 54 148 : b7 149 : c3 150 : c9 151 : 7b 152 : a3 153 : 71 154 : 2b
155 : b4 156 : 50 157 : 54 158 : 22 159 : 95 160 : df 161 : 17 162 : c9 163 : 41 164 :

http://testbench.in/SL_07_PHASE_4_PACKET.html[9/26/2012 2:28:58 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

80 165 : 2b 166 : f0 167 : ba 168 : 4a 169 : a9 170 : 7f 171 : 13 172 : 1e 173 : 12 174
: a8 175 : 2 176 : 3 177 : 3d 178 : 71 179 : e6 180 : 96 181 : 89 182 : c6 183 : 46 184
: d6 185 : 1b 186 : 5f 187 : 20 188 : a0 189 : a3 190 : 49 191 : 79 192 : 9
 193 : 53
-----------------------------------------------------------

 Packing,Unpacking and compare worked


 Randomization Sucessesfull.

..............
..............
..............

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SL_07_PHASE_4_PACKET.html[9/26/2012 2:28:58 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PHASE 5 DRIVER Index


Introduction
SystemVerilog Specification
Verification In phase 5 we will write a driver and then instantiate  the driver in environment and Verification Plan
send packet in to DUT. Driver class is defined in Driver.sv file. Phase 1 Top
Constructs Phase 2 Environment
Interface Driver is class which generates the packets and then drives it to the DUT input Phase 3 Reset
interface and pushes the packet in to mailbox. Phase 4 Packet
OOPS Phase 5 Driver
Randomization Phase 6 Receiver
Phase 7 Scoreboard
Functional Coverage Phase 8 Coverage
Assertion Phase 9 Testcase
DPI Report a Bug or Comment
UVM Tutorial on This section - Your
input is what keeps
VMM Tutorial
Testbench.in improving
OVM Tutorial with time!
Easy Labs : SV
Easy Labs : UVM
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

Verilog
Verification
Verilog Switch TB 1) Declare a packet.
Basic Constructs   packet gpkt;

2) Declare a virtual input_interface of the switch. We will connect this to the Physical
OpenVera interface of the top module same as what we did in environment class.
Constructs
  virtual input_interface.IP  input_intf;
Switch TB
RVM Switch TB 3) Define a mailbox "drvr2sb" which is used to send the packets to the score board.
RVM Ethernet sample   mailbox drvr2sb;

4) Define new constructor with arguments, virtual input interface and a mail box
Specman E which is used to send packets from the driver to scoreboard.
Interview Questions function new(virtual input_interface.IP  input_intf_new,mailbox drvr2sb);
  this.input_intf    = input_intf_new  ;
  if(drvr2sb == null)
  begin
    $display(" **ERROR**: drvr2sb is null");
    $finish;
  end
  else
  this.drvr2sb = drvr2sb;

5) Construct the packet in the driver constructor.

http://testbench.in/SL_08_PHASE_5_DRIVER.html[9/26/2012 2:29:08 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

   gpkt = new();

6) Define the start method.


In start method, do the following

Repeat the following steps for num_of_pkts times.

  repeat($root.num_of_pkts)

Randomize the packet and check if the randomization is successes full.

if ( pkt.randomize())
     begin
       $display (" %0d : Driver : Randomization Successes full.",$time);
     ...........
     ...........
     else
       begin
         $display (" %0d Driver : ** Randomization failed. **",$time);
     ............
     ...........

Display the packet content.

   pkt.display();

Then pack the packet in to bytes.

   length = pkt.byte_pack(bytes);

Then send the packet byte in to the switch by asserting data_status of the input
interface signal and driving the data bytes on to the data_in signal.

foreach(bytes[i])
 begin
   @(posedge input_intf.clock);
   input_intf.cb.data_status <= 1;
   input_intf.cb.data_in <= bytes[i];  
 end 

After driving all the data bytes, deassert data_status signal of the input interface.

  @(posedge input_intf.clock);
   input_intf.cb.data_status <= 0;
   input_intf.cb.data_in <= 0;  

Send the packet in to mail "drvr2sb" box for scoreboard.

  drvr2sb.put(pkt);

If randomization fails, increment the error counter which is defined in Globals.sv file

  $root.error++;

Driver Class Source Code:

`ifndef GUARD_DRIVER
`define GUARD_DRIVER

class Driver;
virtual input_interface.IP  input_intf;
mailbox drvr2sb;
packet gpkt;

//// constructor method ////


function new(virtual input_interface.IP  input_intf_new,mailbox drvr2sb);

http://testbench.in/SL_08_PHASE_5_DRIVER.html[9/26/2012 2:29:08 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

  this.input_intf    = input_intf_new  ;
  if(drvr2sb == null)
  begin
    $display(" **ERROR**: drvr2sb is null");
    $finish;
  end
  else
  this.drvr2sb = drvr2sb;
  gpkt = new();
endfunction : new  

/// method to send the packet to DUT ////////


task start();
  packet pkt;
  int length;
  logic [7:0] bytes[];
  repeat($root.num_of_pkts)
  begin
       repeat(3) @(posedge input_intf.clock);
     pkt = new gpkt;
    //// Randomize the packet /////
    if ( pkt.randomize())
     begin
       $display (" %0d : Driver : Randomization Successes full. ",$time);
       //// display the packet content ///////
       pkt.display();
          
       //// Pack the packet in tp stream of bytes //////
       length = pkt.byte_pack(bytes);
        
       ///// assert the data_status signal and send the packed bytes //////
       foreach(bytes[i])
       begin
          @(posedge input_intf.clock);
          input_intf.cb.data_status <= 1;
          input_intf.cb.data_in <= bytes[i];  
       end 
  
       //// deassert the data_status singal //////
       @(posedge input_intf.clock);
       input_intf.cb.data_status <= 0;
       input_intf.cb.data_in <= 0;  
  
       //// Push the packet in to mailbox for scoreboard /////
       drvr2sb.put(pkt);
      
       $display(" %0d : Driver : Finished Driving the packet with length
%0d",$time,length); 
     end
     else
      begin
         $display (" %0d Driver : ** Randomization failed. **",$time);
         ////// Increment the error count in randomization fails ////////
         $root.error++;
      end
  end
endtask : start

endclass

`endif

Now we will take the instance of the driver in the environment class.

http://testbench.in/SL_08_PHASE_5_DRIVER.html[9/26/2012 2:29:08 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

1) Declare a mailbox "drvr2sb" which will be used to connect the scoreboard and
driver.

  mailbox drvr2sb;

2) Declare a driver object "drvr".

  Driver drvr;

3) In build method, construct the mail box.

  drvr2sb = new();

4) In build method, construct the driver object. Pass the input_intf and "drvr2sb" mail
box.

  drvr= new(input_intf,drvr2sb);

5) To start sending the packets to the DUT, call the start method of "drvr" in the start
method of Environment class.

  drvr.start();

Environment Class Source Code:

`ifndef GUARD_ENV
`define GUARD_ENV

class Environment ;

  virtual mem_interface.MEM    mem_intf       ;
  virtual input_interface.IP  input_intf     ;
  virtual output_interface.OP output_intf[4] ;

  Driver drvr;
  mailbox drvr2sb;

function new(virtual mem_interface.MEM    mem_intf_new       ,


             virtual input_interface.IP  input_intf_new     ,
             virtual output_interface.OP output_intf_new[4] );

  this.mem_intf      = mem_intf_new    ;
  this.input_intf    = input_intf_new  ;
  this.output_intf   = output_intf_new ;

http://testbench.in/SL_08_PHASE_5_DRIVER.html[9/26/2012 2:29:08 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

  $display(" %0d : Environment  : created env object",$time);


endfunction : new

function void build();


  $display(" %0d : Environment  : start of build() method",$time);

  drvr2sb = new();
  drvr= new(input_intf,drvr2sb);

  $display(" %0d : Environment  : end of build() method",$time);


endfunction : build

task reset();
  $display(" %0d : Environment  : start of reset() method",$time);
  // Drive all DUT inputs to a known state
  mem_intf.cb.mem_data      <= 0;
  mem_intf.cb.mem_add       <= 0;
  mem_intf.cb.mem_en        <= 0;
  mem_intf.cb.mem_rd_wr     <= 0;
  input_intf.cb.data_in     <= 0;
  input_intf.cb.data_status <= 0;
  output_intf[0].cb.read    <= 0;
  output_intf[1].cb.read    <= 0;
  output_intf[2].cb.read    <= 0;
  output_intf[3].cb.read    <= 0;
  
  // Reset the DUT
  input_intf.reset       <= 1;
  repeat (4) @ input_intf.clock;
  input_intf.reset       <= 0;
  
  $display(" %0d : Environment  : end of reset() method",$time);
endtask : reset

task cfg_dut();
  $display(" %0d : Environment  : start of cfg_dut() method",$time);
  
  mem_intf.cb.mem_en <= 1;
  @(posedge mem_intf.clock);
  mem_intf.cb.mem_rd_wr <= 1;
  
  @(posedge mem_intf.clock);
  mem_intf.cb.mem_add  <= 8'h0;
  mem_intf.cb.mem_data <= `P0;
  $display(" %0d : Environment  : Port 0 Address %h ",$time,`P0);
  
  @(posedge mem_intf.clock);
  mem_intf.cb.mem_add  <= 8'h1;
  mem_intf.cb.mem_data <= `P1;
  $display(" %0d : Environment  : Port 1 Address %h ",$time,`P1);
  
  @(posedge mem_intf.clock);
  mem_intf.cb.mem_add  <= 8'h2;
  mem_intf.cb.mem_data <= `P2;
  $display(" %0d : Environment  : Port 2 Address %h ",$time,`P2);
  
  @(posedge mem_intf.clock);
  mem_intf.cb.mem_add  <= 8'h3;
  mem_intf.cb.mem_data <= `P3;
  $display(" %0d : Environment  : Port 3 Address %h ",$time,`P3);
  
  @(posedge mem_intf.clock);
  mem_intf.cb.mem_en    <=0;
  mem_intf.cb.mem_rd_wr <= 0;
  mem_intf.cb.mem_add   <= 0;
  mem_intf.cb.mem_data  <= 0;
  
  
  $display(" %0d : Environment  : end of cfg_dut() method",$time);
endtask :cfg_dut

task start();
  $display(" %0d : Environment  : start of start() method",$time);

http://testbench.in/SL_08_PHASE_5_DRIVER.html[9/26/2012 2:29:08 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

  drvr.start();

  $display(" %0d : Environment  : end of start() method",$time);


endtask : start

task wait_for_end();
  $display(" %0d : Environment  : start of wait_for_end() method",$time);
  repeat(10000) @(input_intf.clock);
  $display(" %0d : Environment  : end of wait_for_end() method",$time);
endtask : wait_for_end

task run();
  $display(" %0d : Environment  : start of run() method",$time);
  build();
  reset();
  cfg_dut();
  start();
  wait_for_end();
  report();
  $display(" %0d : Environment  : end of run() method",$time);
endtask : run

task report();
endtask : report
endclass

`endif

Download the phase 5 source code:

switch_5.tar
Browse the code in switch_5.tar

Run the command:


vcs -sverilog -f filelist -R -ntb_opts dtm

Log file report.

 ******************* Start of testcase ****************


 0 : Environment : created env object
 0 : Environment : start of run() method
 0 : Environment : start of build() method
 0 : Environment : end of build() method
 0 : Environment : start of reset() method
 40 : Environment : end of reset() method
 40 : Environment : start of cfg_dut() method
 70 : Environment : Port 0 Address 00
 90 : Environment : Port 1 Address 11
 110 : Environment : Port 2 Address 22
 130 : Environment : Port 3 Address 33
 150 : Environment : end of cfg_dut() method
 150 : Environment : start of start() method
 210 : Driver : Randomization Successes full.

---------------------- PACKET  KIND -------------------------


  fcs_kind     : BAD_FCS
  length_kind  : GOOD_LENGTH
-------- PACKET ----------
  0 : 22
  1 : 11
  2 : 2d
  3 : 63   4 : 2a   5 : 2e   6 : c   7 : a   8 : 14   9 : c1  10 : 14  11 : 8f  12 : 54  13 :
5d  14 : da  15 : 22  16 : 2c  17 : ac  18 : 1c  19 : 48  20 : 3c  21 : 7e  22 : f3  23 :
ed  24 : 24  25 : d1  26 : 3e  27 : 38  28 : aa  29 : 54  30 : 19  31 : 89  32 : aa  33 :
cf  34 : 67  35 : 19  36 : 9a  37 : 1d  38 : 96  39 : 8  40 : 15  41 : 66  42 : 55  43 : b  44
: 70  45 : 35  46 : fc  47 : 8f
 48 : cd
-----------------------------------------------------------

 1210 : Driver : Finished Driving the packet with length 49


 1270 : Driver : Randomization Successes full.

..................
..................

http://testbench.in/SL_08_PHASE_5_DRIVER.html[9/26/2012 2:29:08 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

..................

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SL_08_PHASE_5_DRIVER.html[9/26/2012 2:29:08 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PHASE 6 RECEIVER Index


Introduction
SystemVerilog Specification
Verification In this phase, we will write a receiver and use the receiver in environment class to Verification Plan
collect the packets coming from the switch output_interface. Phase 1 Top
Constructs Phase 2 Environment
Interface Receiver collects the data bytes from the interface signal. And then unpacks the bytes Phase 3 Reset
in to packet and pushes it into mailbox. Phase 4 Packet
OOPS Phase 5 Driver
Randomization Receiver class is written in reveicer.sv file. Phase 6 Receiver
Phase 7 Scoreboard
Functional Coverage Phase 8 Coverage
Assertion Phase 9 Testcase
DPI Report a Bug or Comment
UVM Tutorial on This section - Your
input is what keeps
VMM Tutorial
Testbench.in improving
OVM Tutorial with time!
Easy Labs : SV
Easy Labs : UVM
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

Verilog
Verification
Verilog Switch TB
1) Declare a virtual output_interface. We will connect this to the Physical interface of
Basic Constructs the top module, same as what we did in environment class.

  virtual output_interface.OP output_intf;
OpenVera
2) Declare a mailbox  "rcvr2sb" which is used to send the packets to the score board
Constructs
Switch TB   mailbox rcvr2sb;
RVM Switch TB
3) Define new constructor with arguments, virtual input interface and a mail box
RVM Ethernet sample which is used to send packets from the receiver to scoreboard.

function new(virtual output_interface.OP  output_intf_new,mailbox rcvr2sb);
Specman E    this.output_intf    = output_intf_new  ;
   if(rcvr2sb == null)
Interview Questions    begin
     $display(" **ERROR**: rcvr2sb is null");
     $finish;
   end
   else
   this.rcvr2sb = rcvr2sb;
endfunction : new  

4) Define the start method.

http://testbench.in/SL_09_PHASE_6_RECEIVER.html[9/26/2012 2:29:17 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

In start method, do the following

Wait for the ready signal to be asserted by the DUT.  

  wait(output_intf.cb.ready)

If the ready signal is asserted, then request the DUT to send the data out from the
data_out signal by asserting the read signal. When the data to be sent is finished by
the DUT, it will deassert the ready signal. Once the ready signal is deasserted, stop
collecting the data bytes and deasseart the read signal.

  output_intf.cb.read <= 1;  
    repeat(2) @(posedge output_intf.clock);
    while (output_intf.cb.ready)
    begin
       bytes = new[bytes.size + 1](bytes);
       bytes[bytes.size - 1] = output_intf.cb.data_out;
       @(posedge output_intf.clock);
    end
    output_intf.cb.read <= 0;  
    @(posedge output_intf.clock);
    $display(" %0d : Receiver : Received a packet of length %0d",$time,bytes.size);

Create a new packet object of packet.

    pkt = new();

Then call the unpack method of the packet to unpacked the bytes and then display
the packet content.

    pkt.byte_unpack(bytes);
    pkt.display();

Then send the packet to scoreboard.

    rcvr2sb.put(pkt); 

Delete the dynamic array bytes.

    bytes.delete();  

Receiver Class Source Code:


`ifndef GUARD_RECEIVER
`define GUARD_RECEIVER

class Receiver;

virtual output_interface.OP output_intf;
mailbox rcvr2sb;

//// constructor method ////


function new(virtual output_interface.OP  output_intf_new,mailbox rcvr2sb);
   this.output_intf    = output_intf_new  ;
   if(rcvr2sb == null)
   begin
     $display(" **ERROR**: rcvr2sb is null");
     $finish;
   end
   else
   this.rcvr2sb = rcvr2sb;
endfunction : new  

task start();
logic [7:0] bytes[];
packet pkt;
  forever
  begin
    repeat(2) @(posedge output_intf.clock);

http://testbench.in/SL_09_PHASE_6_RECEIVER.html[9/26/2012 2:29:17 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

    wait(output_intf.cb.ready)
    output_intf.cb.read <= 1;  
    repeat(2) @(posedge output_intf.clock);
    while (output_intf.cb.ready)
    begin
       bytes = new[bytes.size + 1](bytes);
       bytes[bytes.size - 1] = output_intf.cb.data_out;
       @(posedge output_intf.clock);
    end
    output_intf.cb.read <= 0;  
    @(posedge output_intf.clock);
    $display(" %0d : Receiver : Received a packet of length %0d",$time,bytes.size);
    pkt = new();
    pkt.byte_unpack(bytes);
    pkt.display();
    rcvr2sb.put(pkt); 
    bytes.delete();  
  end
endtask : start

endclass

`endif

Now we will take the instance of the receiver in the environment class.

1) Declare a mailbox "rcvr2sb" which will be used to connect the scoreboard and
receiver.

  mailbox rcvr2sb;

2) Declare 4 receiver object "rcvr".

  Receiver rcvr[4];

3) In build method, construct the mail box.

  rcvr2sb = new();

4) In build method, construct the receiver object. Pass the output_intf and "rcvr2sb"
mail box. There are 4 output interfaces and receiver objects. We will connect one
receiver for one output interface.

http://testbench.in/SL_09_PHASE_6_RECEIVER.html[9/26/2012 2:29:17 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

  foreach(rcvr[i])
    rcvr[i]= new(output_intf[i],rcvr2sb);

5) To start collecting the packets from the DUT, call the "start" method of "rcvr" in the
"start" method of Environment class.

task start();
  $display(" %0d : Environment  : start of start() method",$time);
  fork
    drvr.start();
    rcvr[0].start();
    rcvr[1].start();
    rcvr[2].start();
    rcvr[3].start();
  join_any
  $display(" %0d : Environment  : end of start() method",$time);
endtask : start

Environment Class Source Code:

`ifndef GUARD_ENV
`define GUARD_ENV

class Environment ;

  virtual mem_interface.MEM    mem_intf       ;
  virtual input_interface.IP  input_intf     ;
  virtual output_interface.OP output_intf[4] ;
  
  Driver drvr;

  Receiver rcvr[4];

  mailbox drvr2sb;

  mailbox rcvr2sb;

function new(virtual mem_interface.MEM    mem_intf_new       ,


             virtual input_interface.IP  input_intf_new     ,
             virtual output_interface.OP output_intf_new[4] );

  this.mem_intf      = mem_intf_new    ;
  this.input_intf    = input_intf_new  ;
  this.output_intf   = output_intf_new ;
  
  $display(" %0d : Environment  : created env object",$time);
endfunction : new

function void build();


  $display(" %0d : Environment  : start of build() method",$time);
  drvr2sb = new();

  rcvr2sb = new();

  drvr= new(input_intf,drvr2sb);

  foreach(rcvr[i])
    rcvr[i]= new(output_intf[i],rcvr2sb);

  $display(" %0d : Environment  : end of build() method",$time);


endfunction : build

task reset();
  $display(" %0d : Environment  : start of reset() method",$time);
  // Drive all DUT inputs to a known state
  mem_intf.cb.mem_data      <= 0;
  mem_intf.cb.mem_add       <= 0;
  mem_intf.cb.mem_en        <= 0;
  mem_intf.cb.mem_rd_wr     <= 0;
  input_intf.cb.data_in     <= 0;
  input_intf.cb.data_status <= 0;

http://testbench.in/SL_09_PHASE_6_RECEIVER.html[9/26/2012 2:29:17 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

  output_intf[0].cb.read    <= 0;
  output_intf[1].cb.read    <= 0;
  output_intf[2].cb.read    <= 0;
  output_intf[3].cb.read    <= 0;
  
  // Reset the DUT
  input_intf.reset       <= 1;
  repeat (4) @ input_intf.clock;
  input_intf.reset       <= 0;
  
  $display(" %0d : Environment  : end of reset() method",$time);
endtask : reset

task cfg_dut();
  $display(" %0d : Environment  : start of cfg_dut() method",$time);
  
  mem_intf.cb.mem_en <= 1;
  @(posedge mem_intf.clock);
  mem_intf.cb.mem_rd_wr <= 1;
  
  @(posedge mem_intf.clock);
  mem_intf.cb.mem_add  <= 8'h0;
  mem_intf.cb.mem_data <= `P0;
  $display(" %0d : Environment  : Port 0 Address %h ",$time,`P0);
  
  @(posedge mem_intf.clock);
  mem_intf.cb.mem_add  <= 8'h1;
  mem_intf.cb.mem_data <= `P1;
  $display(" %0d : Environment  : Port 1 Address %h ",$time,`P1);
  
  @(posedge mem_intf.clock);
  mem_intf.cb.mem_add  <= 8'h2;
  mem_intf.cb.mem_data <= `P2;
  $display(" %0d : Environment  : Port 2 Address %h ",$time,`P2);
  
  @(posedge mem_intf.clock);
  mem_intf.cb.mem_add  <= 8'h3;
  mem_intf.cb.mem_data <= `P3;
  $display(" %0d : Environment  : Port 3 Address %h ",$time,`P3);
  
  @(posedge mem_intf.clock);
  mem_intf.cb.mem_en    <=0;
  mem_intf.cb.mem_rd_wr <= 0;
  mem_intf.cb.mem_add   <= 0;
  mem_intf.cb.mem_data  <= 0;
  
  
  $display(" %0d : Environment  : end of cfg_dut() method",$time);
endtask :cfg_dut

task start();
  $display(" %0d : Environment  : start of start() method",$time);
  fork
    drvr.start();

    rcvr[0].start();
    rcvr[1].start();
    rcvr[2].start();
    rcvr[3].start();

  join_any
  $display(" %0d : Environment  : end of start() method",$time);
endtask : start

task wait_for_end();
  $display(" %0d : Environment  : start of wait_for_end() method",$time);
  repeat(10000) @(input_intf.clock);
  $display(" %0d : Environment  : end of wait_for_end() method",$time);
endtask : wait_for_end

task run();
  $display(" %0d : Environment  : start of run() method",$time);
  build();
  reset();

http://testbench.in/SL_09_PHASE_6_RECEIVER.html[9/26/2012 2:29:17 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

  cfg_dut();
  start();
  wait_for_end();
  report();
  $display(" %0d : Environment  : end of run() method",$time);
  
endtask : run

task report();
endtask: report
endclass

`endif

Download the phase 6 source code:

switch_6.tar
Browse the code in switch_6.tar

Run the command:


vcs -sverilog -f filelist -R -ntb_opts dtm

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SL_09_PHASE_6_RECEIVER.html[9/26/2012 2:29:17 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PHASE 7 SCOREBOARD Index


Introduction
SystemVerilog Specification
Verification In this phase we will see the scoreboard implementation. Verification Plan
Phase 1 Top
Constructs Scoreboard has 2 mailboxes. One is used to for getting the packets from the driver Phase 2 Environment
Interface and other from the receiver.  Then the packets are compared and if they don't match, Phase 3 Reset
then error is asserted. Phase 4 Packet
OOPS Phase 5 Driver
Scoreboard in implemented in file Scoreboard.sv.
Randomization Phase 6 Receiver
Phase 7 Scoreboard
Functional Coverage Phase 8 Coverage
Assertion Phase 9 Testcase
DPI Report a Bug or Comment
UVM Tutorial on This section - Your
input is what keeps
VMM Tutorial
Testbench.in improving
OVM Tutorial with time!
Easy Labs : SV
Easy Labs : UVM
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

Verilog
Verification
Verilog Switch TB
Basic Constructs 1) Declare 2 mailboxes drvr2sb and rcvr2sb.

  mailbox drvr2sb;
OpenVera   mailbox rcvr2sb;
Constructs
2) Declare a constructor method with "drvr2sb" and "rcvr2sb" mailboxes as arguments.
Switch TB
RVM Switch TB   function new(mailbox drvr2sb,mailbox rcvr2sb);
RVM Ethernet sample 3) Connect the mailboxes of the constructor to the mail boxes of the scoreboard.

  this.drvr2sb = drvr2sb;
Specman E   this.rcvr2sb = rcvr2sb;
Interview Questions 4) Define a start method.
Do the following steps forever.
Wait until there is a packet is in "rcvr2sb". Then pop the packet from the mail box.

   rcvr2sb.get(pkt_rcv);
   $display(" %0d : Scorebooard : Scoreboard received a packet from receiver ",$time);

Then pop the packet from drvr2sb.

   drvr2sb.get(pkt_exp);

http://testbench.in/SL_10_PHASE_7_SCOREBOARD.html[9/26/2012 2:29:27 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

Compare both packets and increment an error counter if they are not equal.

   if(pkt_rcv.compare(pkt_exp)) 
    $display(" %0d : Scoreboardd :Packet Matched ",$time);
    else
      $root.error++;

Scoreboard Class Source Code:

`ifndef GUARD_SCOREBOARD
`define GUARD_SCOREBOARD

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

`endif

Now we will see how to connect the scoreboard in the Environment class.

http://testbench.in/SL_10_PHASE_7_SCOREBOARD.html[9/26/2012 2:29:27 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

1) Declare a scoreboard.

  Scoreboard sb;

2) Construct the scoreboard in the build method. Pass the drvr2sb and rcvr2sb
mailboxes to the score board constructor.

   sb = new(drvr2sb,rcvr2sb);

3) Start the scoreboard method in the start method.

   sb.start();

4) Now we are to the end of building the verification environment.


In the report() method of environment class, print the TEST PASS or TEST FAIL  status
based on the error count.

task report();
   $display("\n\n*************************************************");
   if( 0 == $root.error)
       $display("********            TEST PASSED         *********");
   else
       $display("********    TEST Failed with %0d errors *********",$root.error);
  
   $display("*************************************************\n\n");
endtask : report

Source Code Of The Environment Class:

`ifndef GUARD_ENV
`define GUARD_ENV

class Environment ;

  virtual mem_interface.MEM    mem_intf       ;
  virtual input_interface.IP  input_intf     ;
  virtual output_interface.OP output_intf[4] ;
  
  Driver drvr;
  Receiver rcvr[4];

http://testbench.in/SL_10_PHASE_7_SCOREBOARD.html[9/26/2012 2:29:27 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

  Scoreboard sb;

  mailbox drvr2sb ;
  mailbox rcvr2sb ;

function new(virtual mem_interface.MEM    mem_intf_new       ,


             virtual input_interface.IP  input_intf_new     ,
             virtual output_interface.OP output_intf_new[4] );

  this.mem_intf      = mem_intf_new    ;
  this.input_intf    = input_intf_new  ;
  this.output_intf   = output_intf_new ;

  $display(" %0d : Environment  : created env object",$time);


endfunction : new

function void build();


   $display(" %0d : Environment  : start of build() method",$time);
   drvr2sb = new();
   rcvr2sb = new();

   sb = new(drvr2sb,rcvr2sb);

   drvr= new(input_intf,drvr2sb);
   foreach(rcvr[i])
     rcvr[i]= new(output_intf[i],rcvr2sb);
   $display(" %0d : Environment  : end of build() method",$time);
endfunction : build

task reset();
  $display(" %0d : Environment  : start of reset() method",$time);
  // Drive all DUT inputs to a known state
  mem_intf.cb.mem_data      <= 0;
  mem_intf.cb.mem_add       <= 0;
  mem_intf.cb.mem_en        <= 0;
  mem_intf.cb.mem_rd_wr     <= 0;
  input_intf.cb.data_in     <= 0;
  input_intf.cb.data_status <= 0;
  output_intf[0].cb.read    <= 0;
  output_intf[1].cb.read    <= 0;
  output_intf[2].cb.read    <= 0;
  output_intf[3].cb.read    <= 0;
  
  // Reset the DUT
  input_intf.reset       <= 1;
  repeat (4) @ input_intf.clock;
  input_intf.reset       <= 0;
  
  $display(" %0d : Environment  : end of reset() method",$time);
endtask : reset
  
task cfg_dut();
  $display(" %0d : Environment  : start of cfg_dut() method",$time);
  
  mem_intf.cb.mem_en <= 1;
  @(posedge mem_intf.clock);
  mem_intf.cb.mem_rd_wr <= 1;
  
  @(posedge mem_intf.clock);
  mem_intf.cb.mem_add  <= 8'h0;
  mem_intf.cb.mem_data <= `P0;
  $display(" %0d : Environment  : Port 0 Address %h ",$time,`P0);
  
  @(posedge mem_intf.clock);
  mem_intf.cb.mem_add  <= 8'h1;
  mem_intf.cb.mem_data <= `P1;
  $display(" %0d : Environment  : Port 1 Address %h ",$time,`P1);
  
  @(posedge mem_intf.clock);
  mem_intf.cb.mem_add  <= 8'h2;
  mem_intf.cb.mem_data <= `P2;
  $display(" %0d : Environment  : Port 2 Address %h ",$time,`P2);
  
  @(posedge mem_intf.clock);

http://testbench.in/SL_10_PHASE_7_SCOREBOARD.html[9/26/2012 2:29:27 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

  mem_intf.cb.mem_add  <= 8'h3;
  mem_intf.cb.mem_data <= `P3;
  $display(" %0d : Environment  : Port 3 Address %h ",$time,`P3);
  
  @(posedge mem_intf.clock);
  mem_intf.cb.mem_en    <=0;
  mem_intf.cb.mem_rd_wr <= 0;
  mem_intf.cb.mem_add   <= 0;
  mem_intf.cb.mem_data  <= 0;
  
  
  $display(" %0d : Environment  : end of cfg_dut() method",$time);
endtask :cfg_dut

task start();
  $display(" %0d : Environment  : start of start() method",$time);
  fork
    drvr.start();
    rcvr[0].start();
    rcvr[1].start();
    rcvr[2].start();
    rcvr[3].start();

    sb.start();

  join_any
  $display(" %0d : Environment  : end of start() method",$time);
endtask : start

task wait_for_end();
   $display(" %0d : Environment  : start of wait_for_end() method",$time);
   repeat(10000) @(input_intf.clock);
   $display(" %0d : Environment  : end of wait_for_end() method",$time);
endtask : wait_for_end

task run();
   $display(" %0d : Environment  : start of run() method",$time);
   build();
   reset();
   cfg_dut();
   start();
   wait_for_end();
   report();
   $display(" %0d : Environment  : end of run() method",$time);
endtask: run  
  
task report();

   $display("\n\n*************************************************");
   if( 0 == $root.error)
       $display("********            TEST PASSED         *********");
   else
       $display("********    TEST Failed with %0d errors *********",$root.error);
  
   $display("*************************************************\n\n");

endtask : report

endclass
`endif

Download the phase 7 score code:

switch_7.tar
Browse the code in switch_7.tar

Run the simulation:


vcs -sverilog -f filelist -R -ntb_opts dtm

http://testbench.in/SL_10_PHASE_7_SCOREBOARD.html[9/26/2012 2:29:27 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SL_10_PHASE_7_SCOREBOARD.html[9/26/2012 2:29:27 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PHASE 8 COVERAGE Index


Introduction
SystemVerilog Specification
Verification In this phase we will write the functional coverage for switch protocol. Functional Verification Plan
coverage is written in Coverage.sv file. After running simulation, you will analyze the Phase 1 Top
Constructs coverage results and find out if some test scenarios have not been exercised and write Phase 2 Environment
Interface tests to exercise them. Phase 3 Reset
Phase 4 Packet
OOPS Phase 5 Driver
The points which we need to cover are  
Randomization 1) Cover all the port address configurations. Phase 6 Receiver
2) Cover all the packet lengths. Phase 7 Scoreboard
Functional Coverage Phase 8 Coverage
3) Cover all correct and incorrect length fields.
Assertion 4) Cover good and bad FCS. Phase 9 Testcase
DPI 5) Cover all the above combinations.
Report a Bug or Comment
UVM Tutorial 1) Define a cover group with following cover points. on This section - Your
input is what keeps
VMM Tutorial
a) All packet lengths: Testbench.in improving
OVM Tutorial with time!
Easy Labs : SV length : coverpoint pkt.length;
Easy Labs : UVM b) All port address:
Easy Labs : OVM
da     : coverpoint pkt.da {
Easy Labs : VMM             bins p0 = { `P0 }; 
AVM Switch TB             bins p1 = { `P1 }; 
            bins p2 = { `P2 }; 
VMM Ethernet sample             bins p3 = { `P3 }; } 

c) Correct and incorrect Length field types:


Verilog
Verification length_kind : coverpoint pkt.length_kind;
Verilog Switch TB d) Good and Bad FCS:
Basic Constructs
fcs_kind : coverpoint pkt.fcs_kind;

5) Cross product of all the above cover points:


OpenVera
Constructs all_cross:  cross length,da,length_kind,fcs_kind;
Switch TB
2) In constructor method, construct the cover group
RVM Switch TB
RVM Ethernet sample function new();
 switch_coverage = new();
endfunction : new
Specman E 3) Write task which calls the sample method to cover the points.
Interview Questions
task sample(packet pkt);
 this.pkt = pkt;
 switch_coverage.sample();
endtask:sample

Source Code Of Coverage Class:

`ifndef GUARD_COVERAGE
`define GUARD_COVERAGE

http://testbench.in/SL_11_PHASE_8_COVERAGE.html[9/26/2012 2:29:37 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

class coverage;
packet pkt;

covergroup switch_coverage;

  length : coverpoint pkt.length;
  da     : coverpoint pkt.da {
              bins p0 = { `P0 }; 
              bins p1 = { `P1 }; 
              bins p2 = { `P2 }; 
              bins p3 = { `P3 }; } 
  length_kind : coverpoint pkt.length_kind;
  fcs_kind : coverpoint pkt.fcs_kind;
  
  all_cross:  cross length,da,length_kind,fcs_kind;
endgroup

function new();
  switch_coverage = new();
endfunction : new

task sample(packet pkt);
 this.pkt = pkt;
 switch_coverage.sample();
endtask:sample

endclass

`endif

Now we will use this coverage class instance in scoreboard.

1) Take an instance of coverage class and construct it in scoreboard class.

  coverage cov = new();

2) Call the sample method and pass the exp_pkt to the sample method.

  cov.sample(pkt_exp);

Source Code Of The Scoreboard Class:

`ifndef GUARD_SCOREBOARD
`define GUARD_SCOREBOARD

class Scoreboard;

mailbox drvr2sb;
mailbox rcvr2sb;

coverage cov = new();

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))
    begin

http://testbench.in/SL_11_PHASE_8_COVERAGE.html[9/26/2012 2:29:37 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

       $display(" %0d : Scoreboardd :Packet Matched ",$time);

    cov.sample(pkt_exp);

    end
    else
      $root.error++;
  end
endtask : start

endclass

`endif

Download the phase 8 score code:

switch_8.tar
Browse the code in switch_8.tar

Run the simulation:


vcs -sverilog -f filelist -R -ntb_opts dtm
urg -dir simv.cm

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SL_11_PHASE_8_COVERAGE.html[9/26/2012 2:29:37 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PHASE 9 TESTCASE Index


Introduction
SystemVerilog Specification
Verification In this phase we will write a constraint random testcase. Verification Plan
Lets verify the DUT by sending large packets of length above 200. Phase 1 Top
Constructs Phase 2 Environment
Interface 1) In testcase file, define a small_packet class. Phase 3 Reset
This calls is inherited from the packet class and data.size() field is constraint to Phase 4 Packet
OOPS Phase 5 Driver
generate the packet with size greater than 200.
Randomization Phase 6 Receiver
Phase 7 Scoreboard
Functional Coverage Phase 8 Coverage
class small_packet extends packet;
Assertion Phase 9 Testcase
DPI constraint small_c { data.size > 200 ; }
  Report a Bug or Comment
UVM Tutorial endclass on This section - Your
input is what keeps
VMM Tutorial
Testbench.in improving
OVM Tutorial 2) In program block, create an object of the small_packet class. with time!
Easy Labs : SV Then call the build method of env.
Easy Labs : UVM   small_packet spkt;
Easy Labs : OVM
3) Pass the object of the small_packet to the packet handle which is in driver.
Easy Labs : VMM
AVM Switch TB   env.drvr.gpkt = spkt;
VMM Ethernet sample Then call the reset(),cfg_dut(),start(),wait_for_end() and report() methods as in the
run method.

Verilog   env.reset();
Verification   env.cfg_dut();
  env.start();
Verilog Switch TB   env.wait_for_end();
Basic Constructs   env.report();

OpenVera Source Code Of Constraint Testcase:


Constructs
Switch TB `ifndef GUARD_TESTCASE
`define GUARD_TESTCASE
RVM Switch TB
RVM Ethernet sample class small_packet extends packet;

constraint small_c { data.size > 200 ; }
 
Specman E endclass
Interview Questions
program testcase(mem_interface.MEM mem_intf,input_interface.IP input_intf,output_interface.OP output_intf[4
]);

Environment env;
small_packet spkt;

initial
begin
   $display(" ******************* Start of testcase ****************");
   spkt = new();

http://testbench.in/SL_12_PHASE_9_TESTCASE.html[9/26/2012 2:29:48 PM]


WWW.TESTBENCH.IN - Easy Labs : SV

   env = new(mem_intf,input_intf,output_intf);
   env.build();
   env.drvr.gpkt = spkt;
   env.reset();
   env.cfg_dut();
   env.start();
   env.wait_for_end();
   env.report();
   #1000;
end

final
$display(" ******************** End of testcase *****************");

endprogram 
`endif

Download the phase 9 source code:

switch_9.tar
Browse the code in switch_9.tar

Run the simulation:


vcs -sverilog -f filelist -R -ntb_opts dtm
urg -dir simv.cm

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SL_12_PHASE_9_TESTCASE.html[9/26/2012 2:29:48 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INTRODUCTION Index


Introduction
SystemVerilog Specification
Verification In this tutorial, we will verify the Switch RTL core using UVM in SystemVerilog. Verification Plan
Following are the steps we follow to verify the Switch RTL core. Phase 1 Top
Constructs Phase 2 Configuration
Interface 1) Understand the specification Phase 3 Environment N
Testcase
OOPS Phase 4 Packet
2) Developing Verification Plan
Randomization Phase 5 Sequencer N
Functional Coverage
3) Building the Verification Environment. We will build the Environment in Multiple Sequence
phases, so it will be easy for you to lean step by step. Phase 6 Driver
Assertion    In this verification environment, I will not use agents and monitors to make this Phase 7 Receiver
tutorial simple and easy. Phase 8 Scoreboard
DPI
UVM Tutorial  Phase 1) We will develop the interfaces, and connect it to DUT in top module. Report a Bug or Comment
on This section - Your
VMM Tutorial
 Phase 2) We will develop the Configuration class. input is what keeps
OVM Tutorial Testbench.in improving
Easy Labs : SV  Phase 3) We will develop the Environment class and Simple testcase and simulate with time!
them.
Easy Labs : UVM
Easy Labs : OVM  Phase 4) We will develop packet class based on the stimulus plan. We will also write
a small code to test the packet class implementation.
Easy Labs : VMM
AVM Switch TB  Phase 5) We will develop sequencer and a sample sequences.
VMM Ethernet sample  Phase 6) We will develop driver and connect it to the Sequencer in to environment.  

 Phase 7) We will develop receiver and instantiate in environment.


Verilog
Verification  Phase 8) We will develop scoreboard which does the comparison of the expected
packet with the actual packet received from the DUT and connect it to driver and
Verilog Switch TB receiver in Environment class.
Basic Constructs

OpenVera
Constructs Installing Uvm Library
Switch TB
RVM Switch TB
RVM Ethernet sample 1)Go to  http://www.accellera.org/activities/vip/
2)Download the uvm*.tar.gz file.
3)Untar the file.
4)Go to the extracted directory  : cd uvm*\uvm\src
Specman E 5)Set the UVM_HOME path  :  setenv UVM_HOME `pwd`
Interview Questions (This is required to run the examples which are downloaded from this site)
6)Go to examples :  cd  ../examples/hello_world/uvm/
7)Compile the example using  :
your_tool_compilation_command -f compile_<toolname>.f
(example for questasim use :  qverilog -f compile_questa.f)
8)Run the example.

  

http://testbench.in/UL_01_INTRODUCTION.html[9/26/2012 2:29:56 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/UL_01_INTRODUCTION.html[9/26/2012 2:29:56 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS SPECIFICATION Index


Introduction
SystemVerilog Switch Specification: Specification
Verification Verification Plan
This is a simple switch. Switch is a packet based protocol. Switch drives the incoming Phase 1 Top
Constructs packet which comes from the input port to output ports based on the address Phase 2 Configuration
Interface contained in the packet. Phase 3 Environment N
Testcase
OOPS
The switch has a one input port from which the packet enters. It has four output ports Phase 4 Packet
Randomization where the packet is driven out. Phase 5 Sequencer N
Sequence
Functional Coverage Phase 6 Driver
Assertion Phase 7 Receiver
Phase 8 Scoreboard
DPI
UVM Tutorial Report a Bug or Comment
on This section - Your
VMM Tutorial
input is what keeps
OVM Tutorial Testbench.in improving
with time!
Easy Labs : SV
Easy Labs : UVM
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

Verilog
Verification
Verilog Switch TB
Basic Constructs

Packet Format:
OpenVera
Constructs Packet contains 3 parts. They are Header, data and frame check sequence.
Packet width is 8 bits and the length of the packet can be between 4 bytes to 259
Switch TB bytes.
RVM Switch TB
RVM Ethernet sample
Packet header:

Packet header contains three fields DA, SA and length.


Specman E
Interview Questions DA: Destination address of the packet is of 8 bits. The switch drives the packet to
respective ports based on this destination address of the packets. Each output port
has 8-bit unique port address.  If the destination address of the packet matches the
port address, then switch drives the packet to the output port.

SA: Source address of the packet from where it originate. It is 8 bits.

Length: Length of the data is of 8 bits and from 0 to 255. Length is measured in
terms of bytes.  
If Length = 0, it means data length is 0 bytes
If Length = 1, it means data length is 1 bytes

http://testbench.in/UL_02_SPECIFICATION.html[9/26/2012 2:30:04 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

If Length = 2, it means data length is 2 bytes


If Length = 255, it means data length is 255 bytes

Data: Data should be in terms of bytes and can take anything.

FCS: Frame check sequence


 This field contains the security check of the packet. It is calculated over the header
and data.

Configuration:

Switch has four output ports. These output ports address have to be configured to a
unique address. Switch matches the DA field of the packet with this configured port
address and sends the packet on to that port. Switch contains a memory. This
memory has 4 locations, each can store 8 bits. To configure the switch port address,
memory write operation has to be done using memory interface. Memory address
(0,1,2,3) contains the address of port(0,1,2,3) respectively.

Interface Specification:

The Switch has one input Interface, from where the packet enters and 4 output
interfaces from where the packet comes out and one memory interface, through the
port address can be configured.  Switch also has a clock and asynchronous reset
signal.  

 
MEMORY INTERFACE:

Through memory interfaced output port address are configured. It accepts 8 bit data
to be written to memory. It has 8 bit address inputs. Address 0,1,2,3 contains the
address of the port 0,1,2,3 respectively.

There are 4 input signals to memory interface. They are

input mem_en;
input mem_rd_wr;
input [1:0] mem_add;
input [7:0] mem_data;

All the signals are active high and are synchronous to the positive edge of clock
signal.
To configure a port address,

http://testbench.in/UL_02_SPECIFICATION.html[9/26/2012 2:30:04 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

1.      Assert the mem_en signal.


2.      Asser the mem_rd_wr signal.
3.      Drive the port number (0 or 1 or 2 or 3) on the mem_add signal
4.      Drive the 8 bit port address on to mem_data signal.

INPUT PORT

Packets are sent into the switch using input port.


All the signals are active high and are synchronous to the positive edge of clock
signal.

input port has 2 input signals. They are


input [7:0] data;
input data_status;

To send the packet in to switch,

1. Assert the data_status signal.


2. Send the packet on the data signal byte by byte.
3. After sending all the data bytes, deassert the data_status signal.
4. There should be at least 3 clock cycles difference between packets.

OUTPUT PORT

Switch sends the packets out using the output ports.  There are 4 ports, each having
data, ready and read signals.  All the signals are active high and are synchronous to
the positive edge of clock signal.

Signal list is

output   [7:0] port0;
output   [7:0] port1;
output   [7:0] port2;
output   [7:0] port3;
output      ready_0;
output      ready_1;
output      ready_2;
output      ready_3;
input       read_0;
input       read_1;
input       read_2;
input       read_3;

When the data is ready to be sent out from the port, switch asserts ready_* signal
high indicating that data is ready to be sent.
If the read_* signal is asserted, when ready_* is high, then the data comes out of the
port_* signal after one clock cycle.

http://testbench.in/UL_02_SPECIFICATION.html[9/26/2012 2:30:04 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

RTL  code:

RTL code is attached with the tar files. From the Phase 1, you can download the tar
files.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/UL_02_SPECIFICATION.html[9/26/2012 2:30:04 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS VERIFICATION PLAN Index


Introduction
SystemVerilog Overview Specification
Verification Verification Plan
This Document describes the Verification Plan for Switch. The Verification Plan is Phase 1 Top
Constructs based on System Verilog Hardware Verification Language. The methodology used for Phase 2 Configuration
Interface Verification is Constraint random coverage driven verification. Phase 3 Environment N
Testcase
OOPS Phase 4 Packet
Randomization Feature Extraction Phase 5 Sequencer N
Sequence
Functional Coverage Phase 6 Driver
This section contains list of all the features to be verified.
Assertion 1) Phase 7 Receiver
ID:  Configuration Phase 8 Scoreboard
DPI
Description: Configure all the 4 port address with unique values.
UVM Tutorial Report a Bug or Comment
2) on This section - Your
VMM Tutorial
ID: Packet DA input is what keeps
OVM Tutorial Description: DA field of packet should be any of the port address. All the 4 port Testbench.in improving
address should be used. with time!
Easy Labs : SV
Easy Labs : UVM 3)
Easy Labs : OVM ID : Packet payload
Description: Length can be from 1 to 255. Send packets with all the lengths.
Easy Labs : VMM
AVM Switch TB 4)
ID: Length
VMM Ethernet sample Description:
Length field contains length of the payload.

Verilog 5)
Verification ID: FCS
Description:
Verilog Switch TB Good FCS:  Send packet with good FCS.
Basic Constructs Bad FCS: Send packet with corrupted FCS.  

Stimulus Generation Plan


OpenVera
Constructs 1) Packet DA: Generate packet DA with the configured address.
Switch TB 2) Payload length: generate payload length ranging from 2 to 255.
3) Generate good and bad FCS.
RVM Switch TB
RVM Ethernet sample

Verification Environment
Specman E
Interview Questions

http://testbench.in/UL_03_VERIFICATION_PLAN.html[9/26/2012 2:30:16 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

  

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/UL_03_VERIFICATION_PLAN.html[9/26/2012 2:30:16 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PHASE 1 TOP Index


Introduction
SystemVerilog In phase 1, Specification
Verification Verification Plan
1) We will write SystemVerilog Interfaces for input port, output port and memory Phase 1 Top
Constructs port. Phase 2 Configuration
Interface 2) We will write Top module where testcase and DUT instances are done. Phase 3 Environment N
3) DUT and interfaces are connected in top module. Testcase
OOPS Phase 4 Packet
4) We will implement Clock generator in top module.
Randomization Phase 5 Sequencer N
Sequence
Functional Coverage Phase 6 Driver
  
Assertion Interface Phase 7 Receiver
Phase 8 Scoreboard
DPI
In the interface.sv file, declare the 3 interfaces in the following way.
UVM Tutorial    All the interfaces has clock as input. Report a Bug or Comment
   All the signals in interface are wire type. on This section - Your
VMM Tutorial
   All the signals are synchronized to clock except reset in clocking block. input is what keeps
OVM Tutorial Testbench.in improving
Easy Labs : SV This approach will avoid race conditions between the design and the verification with time!
environment.
Easy Labs : UVM Define the set-up and hold time using parameters.
Easy Labs : OVM Signal directional w.r.t TestBench is specified with modport.
Easy Labs : VMM
AVM Switch TB Interface Source Code
VMM Ethernet sample
`ifndef GUARD_INTERFACE
`define GUARD_INTERFACE
Verilog
Verification
//////////////////////////////////////////
Verilog Switch TB // Interface declaration for the memory///
Basic Constructs //////////////////////////////////////////

interface mem_interface(input bit clock);
OpenVera     parameter setup_time = 5ns;
Constructs     parameter hold_time = 3ns;
Switch TB
    wire [7:0] mem_data;
RVM Switch TB     wire [1:0] mem_add;
RVM Ethernet sample     wire       mem_en;
    wire       mem_rd_wr;
    
    clocking cb@(posedge clock);
Specman E        default input #setup_time output #hold_time;
Interview Questions        output     mem_data;
       output      mem_add;
       output mem_en;
       output mem_rd_wr;
    endclocking:cb
    
    modport MEM(clocking cb,input clock);

endinterface :mem_interface

////////////////////////////////////////////

http://testbench.in/UL_04_PHASE_1_TOP.html[9/26/2012 2:30:26 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

// Interface for the input side of switch.//


// Reset signal is also passed hear.      //
////////////////////////////////////////////
interface input_interface(input bit clock);

    parameter setup_time = 5ns;
    parameter hold_time = 3ns;

    wire           data_status;
    wire     [7:0] data_in;
    reg           reset; 

    clocking cb@(posedge clock);
       default input #setup_time output #hold_time;
       output    data_status;
       output    data_in;
    endclocking:cb
    
    modport IP(clocking cb,output reset,input clock);
  
endinterface:input_interface

/////////////////////////////////////////////////
// Interface for the output side of the switch.//
// output_interface is for only one output port//
/////////////////////////////////////////////////

interface output_interface(input bit clock);

    parameter setup_time = 5ns;
    parameter hold_time = 3ns;

    wire    [7:0] data_out;
    wire    ready;
    wire    read;
    
    clocking cb@(posedge clock);
      default input #setup_time output #hold_time;
      input     data_out;
      input     ready;
      output    read;
    endclocking:cb
    
    modport OP(clocking cb,input clock);

endinterface:output_interface

//////////////////////////////////////////////////

`endif 

Top Module

The modules that are included in the source text but are not instantiated are called
top modules. This module is the highest scope of modules. Generally this module is
named as "top" and referenced as "top module".  Module name can be anything.
This top-level module will contain the design portion of the simulation.

Do the following in the top module:

1) The first step is to import the uvm packages

 `include "uvm.svh"
 import uvm_pkg::*;

2)Generate the clock signal.

bit Clock;

http://testbench.in/UL_04_PHASE_1_TOP.html[9/26/2012 2:30:26 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

initial
  begin
      #20;
      forever #10 Clock = ~Clock;
  end

2)Do the instances of memory interface.

mem_interface mem_intf(Clock);

3)Do the instances of input interface.

input_interface input_intf(Clock);

4)There are 4 output ports. So do 4 instances of output_interface.

output_interface output_intf[4](Clock);

5) Connect all the interfaces and DUT.  The design which we have taken is in
verilog.  So Verilog DUT instance is connected signal by signal.

switch DUT    (.clk(Clock),
               .reset(input_intf.reset),
               .data_status(input_intf.data_status),
               .data(input_intf.data_in),
               .port0(output_intf[0].data_out),
               .port1(output_intf[1].data_out),
               .port2(output_intf[2].data_out),
               .port3(output_intf[3].data_out),
               .ready_0(output_intf[0].ready),
               .ready_1(output_intf[1].ready),
               .ready_2(output_intf[2].ready),
               .ready_3(output_intf[3].ready),
               .read_0(output_intf[0].read),
               .read_1(output_intf[1].read),
               .read_2(output_intf[2].read),
               .read_3(output_intf[3].read),
               .mem_en(mem_intf.mem_en),
               .mem_rd_wr(mem_intf.mem_rd_wr),
               .mem_add(mem_intf.mem_add),
               .mem_data(mem_intf.mem_data));

Top module Scource Code

`ifndef GUARD_TOP
`define GUARD_TOP
/////////////////////////////////////////////////////
// Importing UVM Packages                          //
/////////////////////////////////////////////////////

 `include "uvm.svh"
 import uvm_pkg::*;

module top();

/////////////////////////////////////////////////////
// Clock Declaration and Generation                //
/////////////////////////////////////////////////////
    bit Clock;
    
    initial
      begin
          #20;
          forever #10 Clock = ~Clock;
      end
/////////////////////////////////////////////////////
//  Memory interface instance                      //
/////////////////////////////////////////////////////

    mem_interface mem_intf(Clock);

/////////////////////////////////////////////////////

http://testbench.in/UL_04_PHASE_1_TOP.html[9/26/2012 2:30:26 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

//  Input interface instance                       //


/////////////////////////////////////////////////////

    input_interface input_intf(Clock);

/////////////////////////////////////////////////////
//  output interface instance                      //
/////////////////////////////////////////////////////

    output_interface output_intf[4](Clock);

/////////////////////////////////////////////////////
//  DUT instance and signal connection             //
/////////////////////////////////////////////////////

switch DUT    (.clk(Clock),
               .reset(input_intf.reset),
               .data_status(input_intf.data_status),
               .data(input_intf.data_in),
               .port0(output_intf[0].data_out),
               .port1(output_intf[1].data_out),
               .port2(output_intf[2].data_out),
               .port3(output_intf[3].data_out),
               .ready_0(output_intf[0].ready),
               .ready_1(output_intf[1].ready),
               .ready_2(output_intf[2].ready),
               .ready_3(output_intf[3].ready),
               .read_0(output_intf[0].read),
               .read_1(output_intf[1].read),
               .read_2(output_intf[2].read),
               .read_3(output_intf[3].read),
               .mem_en(mem_intf.mem_en),
               .mem_rd_wr(mem_intf.mem_rd_wr),
               .mem_add(mem_intf.mem_add),
               .mem_data(mem_intf.mem_data));

endmodule : top

`endif

Download the files:

uvm_switch_1.tar
Browse the code in uvm_switch_1.tar

Command to compile

VCS Users : make vcs


Questa Users: make questa

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/UL_04_PHASE_1_TOP.html[9/26/2012 2:30:26 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PHASE 2 CONFIGURATION Index


Introduction
SystemVerilog Specification
Verification In this phase we will implement the configuration class. All the requirements of the Verification Plan
testbench configurations will be declared inside this class. Virtual interfaces required Phase 1 Top
Constructs by verification components driver and receiver for connecting to DUT are declared in Phase 2 Configuration
Interface this class. We will also declare 4 variables which will hold the port address of the Phase 3 Environment N
DUT. Testcase
OOPS Phase 4 Packet
Randomization uvm_object does not have the simulation phases and can be used in get_config_object Phase 5 Sequencer N
and set_config_object method. So we will implement the configuration class by Sequence
Functional Coverage Phase 6 Driver
extending uvm_object.
Assertion Phase 7 Receiver
Phase 8 Scoreboard
DPI
Configuration
UVM Tutorial Report a Bug or Comment
1) Define configuration class by extending uvm_object on This section - Your
VMM Tutorial
input is what keeps
OVM Tutorial `ifndef GUARD_CONFIGURATION Testbench.in improving
`define GUARD_CONFIGURATION with time!
Easy Labs : SV
Easy Labs : UVM class Configuration extends uvm_object;
Easy Labs : OVM
endclass : Configuration
Easy Labs : VMM
AVM Switch TB `endif
VMM Ethernet sample 2) Declare All the interfaces which are required in this verification environment.

    virtual input_interface.IP   input_intf;
Verilog     virtual mem_interface.MEM  mem_intf;
Verification     virtual output_interface.OP output_intf[4];
Verilog Switch TB 3) Declare 4 variables which holds the device port address.
Basic Constructs
    bit [7:0] device_add[4] ;

4) uvm_object required to define the uvm_object::creat() method.


OpenVera    uvm_object::create method allocates a new object of the same type as this object
Constructs and returns it via a base uvm_object handle.
Switch TB
   In create method, we have to construct a new object of configuration class and
RVM Switch TB update all the important fields and return it.
RVM Ethernet sample
    virtual function uvm_object create(string name="");
        Configuration t = new();
Specman E         t.device_add  =   this.device_add;
Interview Questions         t.input_intf  =   this.input_intf;
        t.mem_intf    =   this.mem_intf;
        t.output_intf =   this.output_intf;

        return t;
    endfunction : create

Configuration class source code


`ifndef GUARD_CONFIGURATION
`define GUARD_CONFIGURATION

http://testbench.in/UL_05_PHASE_2_CONFIGURATION.html[9/26/2012 2:30:34 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

class Configuration extends uvm_object;

    virtual input_interface.IP   input_intf;
    virtual mem_interface.MEM  mem_intf;
    virtual output_interface.OP output_intf[4];

    bit [7:0] device_add[4] ;

    virtual function uvm_object create(string name="");
        Configuration t = new();

        t.device_add  =   this.device_add;
        t.input_intf  =   this.input_intf;
        t.mem_intf    =   this.mem_intf;
        t.output_intf =   this.output_intf;

        return t;
    endfunction : create

endclass : Configuration
`endif

Updates To Top Module

In top module we will create an object of the above defined configuration class and
update the interfaces so that all the verification components can access to physical
interfaces in top module using configuration class object.

1) Declare a Configuration class object

    Configuration cfg;

2) Construct the configuration object and update the interfaces.

initial begin
    cfg = new();
    cfg.input_intf = input_intf;
    cfg.mem_intf = mem_intf;
    cfg.output_intf = output_intf;

3) In top module , we have to call the run_test() method.  

    run_test();

Top module updates

 typedef class Configuration;

module top();
/////////////////////////////////////////////////////
// Clock Declaration and Generation                //
/////////////////////////////////////////////////////
    bit Clock;
    
    initial
      begin
          #20;
          forever #10 Clock = ~Clock;
      end
/////////////////////////////////////////////////////
//  Memory interface instance                      //
/////////////////////////////////////////////////////
    mem_interface mem_intf(Clock);
/////////////////////////////////////////////////////
//  Input interface instance                       //
/////////////////////////////////////////////////////
    input_interface input_intf(Clock);
/////////////////////////////////////////////////////

http://testbench.in/UL_05_PHASE_2_CONFIGURATION.html[9/26/2012 2:30:34 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

//  output interface instance                      //


/////////////////////////////////////////////////////
    output_interface output_intf[4](Clock);

/////////////////////////////////////////////////////
// Creat Configuration and Strart the run_test//
/////////////////////////////////////////////////////

    Configuration cfg;

initial begin
    cfg = new();
    cfg.input_intf = input_intf;
    cfg.mem_intf = mem_intf;
    cfg.output_intf = output_intf;
  
    run_test();
end

/////////////////////////////////////////////////////
//  DUT instance and signal connection             //
/////////////////////////////////////////////////////
switch DUT    (.clk(Clock),
               .reset(input_intf.reset),
               .data_status(input_intf.data_status),
               .data(input_intf.data_in),
               .port0(output_intf[0].data_out),
               .port1(output_intf[1].data_out),
               .port2(output_intf[2].data_out),
               .port3(output_intf[3].data_out),
               .ready_0(output_intf[0].ready),
               .ready_1(output_intf[1].ready),
               .ready_2(output_intf[2].ready),
               .ready_3(output_intf[3].ready),
               .read_0(output_intf[0].read),
               .read_1(output_intf[1].read),
               .read_2(output_intf[2].read),
               .read_3(output_intf[3].read),
               .mem_en(mem_intf.mem_en),
               .mem_rd_wr(mem_intf.mem_rd_wr),
               .mem_add(mem_intf.mem_add),
               .mem_data(mem_intf.mem_data));
endmodule : top
`endif

Download the source code

uvm_switch_2.tar
Browse the code in uvm_switch_2.tar

Command to compile

VCS Users : make vcs


Questa Users: make questa

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/UL_05_PHASE_2_CONFIGURATION.html[9/26/2012 2:30:34 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PHASE 3 ENVIRONMENT N TESTCASE Index


Introduction
SystemVerilog Specification
Verification In the phase we will implement the skeleton for environment class. Verification Plan
We will declare virtual interfaces and Extend Required Environment class virtual Phase 1 Top
Constructs methods. Phase 2 Configuration
Interface We will also implement a simple testcase and run the simulation. Phase 3 Environment N
Testcase
OOPS Phase 4 Packet
Randomization Environment class is used to implement verification environments in UVM. It is Phase 5 Sequencer N
extension on uvm_env class.  The testbench simulation needs some systematic flow Sequence
Functional Coverage Phase 6 Driver
like building the components, connection the components, starting the components
Assertion etc. uvm_env base class has methods formalize the simulation steps. All methods are Phase 7 Receiver
declared as virtual methods. Phase 8 Scoreboard
DPI
UVM Tutorial Report a Bug or Comment
on This section - Your
VMM Tutorial
input is what keeps
OVM Tutorial Testbench.in improving
with time!
Easy Labs : SV
Easy Labs : UVM
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

Verilog
Verification
Verilog Switch TB
Basic Constructs We will not implement all the uvm_env virtual methods in this phase but will we print
messages from these methods which are required for this example to understand the
simulation execution.
OpenVera
Testcase contains the instance of the environment class. This testcase Creates a
Constructs Environment object and defines the required test specific functionality.
Switch TB
Verification environment contains the declarations of the virtual interfaces. These
RVM Switch TB
virtual interfaces are pointed to the physical interfaces which are declared in the top
RVM Ethernet sample module. These virtual interfaces are made to point to physical interface in the
testcase.

Specman E
Environment
Interview Questions
1) Extend uvm_env class to define Environment class.

    `ifndef GUARD_ENV
    `define GUARD_ENV
    
    class Environment extends uvm_env;
    
    endclass : Environment
    
    `endif 

http://testbench.in/UL_06_PHASE_3_ENVIRONMENT_N_TESTCASE.html[9/26/2012 2:30:42 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

2)  Declare the utility macro. This utility macro provides the implementation of
create() and get_type_name() methods.

    `uvm_component_utils(Environment)

3) Define the constructor. In the constructor, call the super methods and pass the
parent object. Parent is the object in which environment is instantiated.

    function new(string name , uvm_component parent = null);


        super.new(name, parent);
    endfunction: new

4) Define build method. In build method, just print messages and super.build() must
be called. This method is automatically called.
Build is the first phase in simulation. This phase is used to construct the child
components of the current class.

    virtual function void build();
        super.build();
      
        uvm_report_info(get_full_name(),"START of build ",UVM_LOW);
      
        uvm_report_info(get_full_name(),"END of build ",UVM_LOW);
      
    endfunction

5) Define connect method. In connect method, just print messages and


super.connect() must be called.
This method is called automatically after the build() method is called. This method is
used for connecting port and exports.

    virtual function void connect();
        super.connect();
        uvm_report_info(get_full_name(),"START of connect ",UVM_LOW);
    
        uvm_report_info(get_full_name(),"END of connect ",UVM_LOW);
    endfunction

Environment class Source Code


`ifndef GUARD_ENV
`define GUARD_ENV

class Environment extends uvm_env;

    `uvm_component_utils(Environment)

    function new(string name , uvm_component parent = null);


        super.new(name, parent);
    endfunction: new

    virtual function void build();
        super.build();
      
        uvm_report_info(get_full_name(),"START of build ",UVM_LOW);
      
        uvm_report_info(get_full_name(),"END of build ",UVM_LOW);
      
    endfunction
    
    virtual function void connect();
        super.connect();
        uvm_report_info(get_full_name(),"START of connect ",UVM_LOW);
    
        uvm_report_info(get_full_name(),"END of connect ",UVM_LOW);
    endfunction

endclass : Environment

http://testbench.in/UL_06_PHASE_3_ENVIRONMENT_N_TESTCASE.html[9/26/2012 2:30:42 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

`endif 

Testcase

Now we will implement testcase. In UVM, testcases are implemented by extending


uvm_test. Using uvm_test , provides the ability to select which test to execute using
the UVM_TESTNAME command line option or argument to the uvm_root::run_test task.
We will use UVM_TESTNAME command line argument.

1) Define a testcase by extending uvm_test class.

   class test1 extends uvm_test;

   endclass

2)  Declare the utility macro.

    `uvm_component_utils(test1)

3) Take the instance of Environemtn.

     Environment t_env ;

4) Define the constructor method.


   In this method, construct the environment class object and dont forget to pass the
parent argument.

    function new (string name="test1", uvm_component parent=null);
        super.new (name, parent);
        t_env = new("t_env",this);
    endfunction : new 

5) Define run() method.


   run() method is the only task which is time consuming. After completing the
start_of_simulation() phase , this method is called.
   To terminate this task, we will use global_stop_request().

   As we dont have anything now to write in this testcase, just call the
global_stop_request() after some delay.

    virtual task run ();
        #3000ns;
        global_stop_request();
    endtask : run

With this, for the first time, we can do the simulation.

Testcase Source code


class test1 extends uvm_test;

    `uvm_component_utils(test1)

     Environment t_env ;

    function new (string name="test1", uvm_component parent=null);
        super.new (name, parent);
        t_env = new("t_env",this);
    endfunction : new 

    virtual task run ();
        #3000ns;
        global_stop_request();
    endtask : run

endclass : test1

Download the Source Code

uvm_switch_3.tar
Browse the code in uvm_switch_3.tar

http://testbench.in/UL_06_PHASE_3_ENVIRONMENT_N_TESTCASE.html[9/26/2012 2:30:42 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

Command to run the simulation

VCS Users : make vcs


Questa Users: make questa

Log report after simulation

UVM_INFO @ 0 [RNTST] Running test test1...


UVM_INFO @ 0: uvm_test_top.t_env [uvm_test_top.t_env] START of build
UVM_INFO @ 0: uvm_test_top.t_env [uvm_test_top.t_env] END of build
UVM_INFO @ 0: uvm_test_top.t_env [uvm_test_top.t_env] START of connect
UVM_INFO @ 0: uvm_test_top.t_env [uvm_test_top.t_env] END of connect

--- UVM Report Summary ---

** Report counts by severity


UVM_INFO :    5
UVM_WARNING :    0
UVM_ERROR :    0
UVM_FATAL :    0
** Report counts by id
[RNTST               ]     1
[uvm_test_top.t_env  ]     4

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/UL_06_PHASE_3_ENVIRONMENT_N_TESTCASE.html[9/26/2012 2:30:42 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PHASE 4 PACKET Index


Introduction
SystemVerilog Specification
Verification In this Phase, we will develop Transaction as per the verification plan. We will define Verification Plan
required methods and constraints. We will also develop a small logic to test our Phase 1 Top
Constructs implementation of this class. Phase 2 Configuration
Interface Phase 3 Environment N
Testcase
OOPS Phase 4 Packet
Packet
Randomization Phase 5 Sequencer N
We will write the packet class in Packet.sv file. Packet class variables and constraints Sequence
Functional Coverage Phase 6 Driver
have been derived from stimulus generation plan.
Assertion Phase 7 Receiver
One way to model Packet is by extending uvm_sequence_item. uvm_sequence_item Phase 8 Scoreboard
DPI
provides basic functionality for sequence items and sequences to operate in a
UVM Tutorial sequence mechanism. Packet class should be able to generate all possible packet Report a Bug or Comment
types randomly. To define copy, compare, record, print and sprint methods, we will on This section - Your
VMM Tutorial
use UVM field macros. For packing and Unpacking, we will define the logic and not use input is what keeps
OVM Tutorial the field  macros. Testbench.in improving
with time!
Easy Labs : SV
Easy Labs : UVM Revisit Stimulus Generation Plan
Easy Labs : OVM 1) Packet DA: Generate packet DA with the configured address.
2) Payload length: generate payload length ranging from 2 to 255.
Easy Labs : VMM 3) Generate good and bad FCS.
AVM Switch TB
VMM Ethernet sample
1) Define enumerated type data for fcs.

Verilog    typedef enum { GOOD_FCS, BAD_FCS } fcs_kind_t;
Verification
2) Define transaction by extending uvm_sequence_item.
Verilog Switch TB
Basic Constructs    class Packet extends uvm_sequence_item;

   endclass : Packet
OpenVera 3) Define all the fields as rand variables.
Constructs
Switch TB     rand fcs_kind_t     fcs_kind;
    
RVM Switch TB     rand bit [7:0] length;
RVM Ethernet sample     rand bit [7:0] da;
    rand bit [7:0] sa;
    rand bit [7:0] data[];
    rand byte fcs;
Specman E     
Interview Questions
4) Define constraints to constraint payload size of data.

    constraint payload_size_c { data.size inside { [2 : 255]};}
    
    constraint length_c {  length == data.size; } 
                    

5) Define the constructor method.

    function new(string name = "");

http://testbench.in/UL_07_PHASE_4_PACKET.html[9/26/2012 2:30:50 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

         super.new(name);
    endfunction : new

6) In post_randomize() , define the fcs value based on fcs_kind.

    function void post_randomize();
         if(fcs_kind == GOOD_FCS)
             fcs = 8'b0;
         else
            fcs = 8'b1;
         fcs = cal_fcs();
    endfunction : post_randomize

7) Define cal_fcs() method which computes the fcs value.

   ///// method to calculate the fcs /////


    virtual function byte cal_fcs;
       return da ^ sa ^ length ^ data.xor() ^ fcs;
    endfunction : cal_fcs

8) Using uvm_field_* macros, define transaction required method.


   We will define packing and unpacking methods manually, so use UVM_NOPACK for
excluding atomic creation of packing and un packing method.

    `uvm_object_utils_begin(Packet)
       `uvm_field_int(da, UVM_ALL_ON|UVM_NOPACK)
       `uvm_field_int(sa, UVM_ALL_ON|UVM_NOPACK)
       `uvm_field_int(length, UVM_ALL_ON|UVM_NOPACK)
       `uvm_field_array_int(data, UVM_ALL_ON|UVM_NOPACK)
       `uvm_field_int(fcs, UVM_ALL_ON|UVM_NOPACK)
    `uvm_object_utils_end

9) Define do_pack() method which does the packing operation.

    function void do_pack(uvm_packer packer);
        super.do_pack(packer);
        packer.pack_field_int(da,$bits(da));
        packer.pack_field_int(sa,$bits(sa));
        packer.pack_field_int(length,$bits(length));
        foreach(data[i])
          packer.pack_field_int(data[i],8);
        packer.pack_field_int(fcs,$bits(fcs));
    endfunction : do_pack

10) Define do_unpack() method which does the unpacking operation.

    function void do_unpack(uvm_packer packer);
        int sz;
        super.do_pack(packer);
    
        da = packer.unpack_field_int($bits(da));
        sa = packer.unpack_field_int($bits(sa));
        length = packer.unpack_field_int($bits(length));
        
        data.delete();
        data = new[length];
        foreach(data[i])
          data[i] = packer.unpack_field_int(8);
        fcs = packer.unpack_field_int($bits(fcs));
    endfunction : do_unpack

Packet class source code

`ifndef GUARD_PACKET
`define GUARD_PACKET

 `include "uvm.svh"

http://testbench.in/UL_07_PHASE_4_PACKET.html[9/26/2012 2:30:50 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

 import uvm_pkg::*;

//Define the enumerated types for packet types


typedef enum { GOOD_FCS, BAD_FCS } fcs_kind_t;

class Packet extends uvm_sequence_item;

    rand fcs_kind_t     fcs_kind;
    
    rand bit [7:0] length;
    rand bit [7:0] da;
    rand bit [7:0] sa;
    rand bit [7:0] data[];
    rand byte fcs;
    
    constraint payload_size_c { data.size inside { [1 : 6]};}
    
    constraint length_c {  length == data.size; } 
                    
    function new(string name = "");
         super.new(name);
    endfunction : new
    
    function void post_randomize();
         if(fcs_kind == GOOD_FCS)
             fcs = 8'b0;
         else
            fcs = 8'b1;
         fcs = cal_fcs();
    endfunction : post_randomize
    
   ///// method to calculate the fcs /////
    virtual function byte cal_fcs;
       return da ^ sa ^ length ^ data.xor() ^ fcs;
    endfunction : cal_fcs
    
    `uvm_object_utils_begin(Packet)
       `uvm_field_int(da, UVM_ALL_ON|UVM_NOPACK)
       `uvm_field_int(sa, UVM_ALL_ON|UVM_NOPACK)
       `uvm_field_int(length, UVM_ALL_ON|UVM_NOPACK)
       `uvm_field_array_int(data, UVM_ALL_ON|UVM_NOPACK)
       `uvm_field_int(fcs, UVM_ALL_ON|UVM_NOPACK)
    `uvm_object_utils_end
    
    function void do_pack(uvm_packer packer);
        super.do_pack(packer);
        packer.pack_field_int(da,$bits(da));
        packer.pack_field_int(sa,$bits(sa));
        packer.pack_field_int(length,$bits(length));
        foreach(data[i])
          packer.pack_field_int(data[i],8);
        packer.pack_field_int(fcs,$bits(fcs));
    endfunction : do_pack
    
    function void do_unpack(uvm_packer packer);
        int sz;
        super.do_pack(packer);
    
        da = packer.unpack_field_int($bits(da));
        sa = packer.unpack_field_int($bits(sa));
        length = packer.unpack_field_int($bits(length));
        
        data.delete();
        data = new[length];
        foreach(data[i])
          data[i] = packer.unpack_field_int(8);
        fcs = packer.unpack_field_int($bits(fcs));
    endfunction : do_unpack

endclass : Packet

Test The Transaction Implementation

http://testbench.in/UL_07_PHASE_4_PACKET.html[9/26/2012 2:30:50 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

Now we will write a small logic to test our packet implantation. This module is not
used in normal verification.

Define a module and take the instance of packet class. Randomize the packet and call
the print method to analyze the generation. Then pack the packet in to bytes and
then unpack bytes and then call compare method to check all the method
implementation.

1) Declare Packet objects and dynamic arrays.

    Packet pkt1 = new("pkt1");


    Packet pkt2 = new("pkt2");
    byte unsigned pkdbytes[];

2) In a initial block, randomize the packet, pack the packet in to pkdbytes and then
unpack it and compare the packets.

       if(pkt1.randomize)
       begin
          $display(" Randomization Sucessesfull.");
          pkt1.print();
          uvm_default_packer.use_metadata = 1;    
          void'(pkt1.pack_bytes(pkdbytes));
          $display("Size of pkd bits %d",pkdbytes.size());
          pkt2.unpack_bytes(pkdbytes);
          pkt2.print();
          if(pkt2.compare(pkt1))
              $display(" Packing,Unpacking and compare worked");
          else
              $display(" *** Something went wrong in Packing or Unpacking or compare ***
\n \n");

Logic to test the transaction implementation


module test;

    Packet pkt1 = new("pkt1");


    Packet pkt2 = new("pkt2");
    byte unsigned pkdbytes[];

    initial
    repeat(10)
       if(pkt1.randomize)
       begin
          $display(" Randomization Successesfull.");
          pkt1.print();
          uvm_default_packer.use_metadata = 1;    
          void'(pkt1.pack_bytes(pkdbytes));
          $display("Size of pkd bits %d",pkdbytes.size());
          pkt2.unpack_bytes(pkdbytes);
          pkt2.print();
          if(pkt2.compare(pkt1))
              $display(" Packing,Unpacking and compare worked");
          else
              $display(" *** Something went wrong in Packing or Unpacking or compare ***
\n \n");
       end
       else
       $display(" *** Randomization Failed ***");
    
endmodule

Download the Source Code

uvm_switch_4.tar
Browse the code in uvm_switch_4.tar

Command to run the simulation

VCS Users : make vcs


Questa Users: make questa

http://testbench.in/UL_07_PHASE_4_PACKET.html[9/26/2012 2:30:50 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

Log report after simulation

 Randomization Sucessesfull.
----------------------------------------------------------------------
Name                     Type                Size                Value
----------------------------------------------------------------------
pkt1                     Packet              -                  pkt1@3
--da                     integral            8                    'ha5
--sa                     integral            8                    'ha1
--length                 integral            8                     'h6
--data                   da(integral)        6                       -
----[0]                  integral            8                    'h58
----[1]                  integral            8                    'h60
----[2]                  integral            8                    'h34
----[3]                  integral            8                    'hdd
----[4]                  integral            8                     'h9
----[5]                  integral            8                    'haf
--fcs                    integral            8                    'h75
----------------------------------------------------------------------
Size of pkd bits          10
----------------------------------------------------------------------
Name                     Type                Size                Value
----------------------------------------------------------------------
pkt2                     Packet              -                  pkt2@5
--da                     integral            8                    'ha5
--sa                     integral            8                    'ha1
--length                 integral            8                     'h6
--data                   da(integral)        6                       -
----[0]                  integral            8                    'h58
----[1]                  integral            8                    'h60
----[2]                  integral            8                    'h34
----[3]                  integral            8                    'hdd
----[4]                  integral            8                     'h9
----[5]                  integral            8                    'haf
--fcs                    integral            8                    'h75
----------------------------------------------------------------------
 Packing,Unpacking and compare worked

....
....
....
....

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/UL_07_PHASE_4_PACKET.html[9/26/2012 2:30:50 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PHASE 5 SEQUENCER N SEQUENCE Index


Introduction
SystemVerilog In this phase we will develop Sequence and Sequencer. Specification
Verification Verification Plan
A sequence is series of transaction and sequencer is used to for controlling the flow of Phase 1 Top
Constructs transaction generation. Phase 2 Configuration
Interface A sequence of transaction (which we already developed in previous phase) is defined Phase 3 Environment N
by extending uvm_sequence class. uvm_sequencer does the generation of this Testcase
OOPS Phase 4 Packet
sequence of transaction, uvm_driver takes the transaction from Sequencer and
Randomization processes the packet/ drives to other component or to DUT. Phase 5 Sequencer N
Sequence
Functional Coverage Phase 6 Driver
Assertion Phase 7 Receiver
Phase 8 Scoreboard
DPI
UVM Tutorial Report a Bug or Comment
on This section - Your
VMM Tutorial
input is what keeps
OVM Tutorial Testbench.in improving
with time!
Easy Labs : SV
Easy Labs : UVM
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample Sequencer

A Sequencer is defined by extending uvm_sequencer. uvm_sequencer has a port


Verilog seq_item_export which is used to connect to uvm_driver for transaction transfer.
Verification
Verilog Switch TB 1) Define a sequencer by extending uvm_sequence.
Basic Constructs `ifndef GUARD_SEQUENCER
`define GUARD_SEQUENCER

OpenVera class Sequencer extends uvm_sequencer #(Packet);


Constructs
endclass : Sequencer
Switch TB
RVM Switch TB `endif
RVM Ethernet sample 2) We need Device port address, which are in configuration class. So declare a
configuration class object.

Specman E      Configuration cfg;


Interview Questions 3) Declare Sequencer utility macros.    

    `uvm_sequencer_utils(Sequencer)

4) Define the constructor.  

    function new (string name, uvm_component parent);
        super.new(name, parent);
        `uvm_update_sequence_lib_and_item(Packet)
    endfunction : new

http://testbench.in/UL_08_PHASE_5_SEQUENCER_N_SEQUENCE.html[9/26/2012 2:30:58 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

5) In   end_of_elaboration() method, using get_config_object(), get the configuration


object which will be passed from testcase.
   get_config_object() returns object of type uvm_object, so using a temporary
uvm_object and cast it to configuration object.

    virtual function void end_of_elaboration();
        uvm_object tmp;
        assert(get_config_object("Configuration",tmp));
        $cast(cfg,tmp);
    endfunction

Sequencer source code

`ifndef GUARD_SEQUENCER
`define GUARD_SEQUENCER

class Sequencer extends uvm_sequencer #(Packet);

     Configuration cfg;


  
    `uvm_sequencer_utils(Sequencer)
  
    function new (string name, uvm_component parent);
        super.new(name, parent);
        `uvm_update_sequence_lib_and_item(Packet)
    endfunction : new
  
  
    virtual function void end_of_elaboration();
        uvm_object tmp;
        assert(get_config_object("Configuration",tmp));
        $cast(cfg,tmp);
    endfunction

endclass : Sequencer

`endif
Sequence

A sequence is defined by extending uvm_sequence class. This sequence of transactions


should be defined in budy() method of uvm_sequence class. UVM has macros and
methods to define the transaction types. We will use macros in this example.

You can define as many sequences as you want. We will define 2 sequences.

1) Define sequence by extending

class Seq_device0_and_device1 extends uvm_sequence #(Packet);

endclass: Seq_device0_and_device1

2) Define constructor method.

     function new(string name = "Seq_do");
         super.new(name);
     endfunction : new

3) Declare utilities macro.  With this macro, this sequence is tied to Sequencer.

     `uvm_sequence_utils(Seq_device0_and_device1, Sequencer)    

4) The algorithm for the transaction should be defined in body() method of the
sequence. In this sequence we will define the algorithm such that alternate
transactions for device port 0 and 1 are generated.
  
   The device addresses are available in configuration object which is in sequencer.

http://testbench.in/UL_08_PHASE_5_SEQUENCER_N_SEQUENCE.html[9/26/2012 2:30:58 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

Every sequence has a handle to its sequence through p_sequencer. Using p_sequencer
handle, access the device address.

     virtual task body();
        forever begin
         `uvm_do_with(item, {da == p_sequencer.cfg.device_add[0];} ); 
         `uvm_do_with(item, {da == p_sequencer.cfg.device_add[1];} ); 
        end
     endtask : body
  

Sequence Source Code

class Seq_device0_and_device1 extends uvm_sequence #(Packet);

     function new(string name = "Seq_device0_and_device1");
         super.new(name);
     endfunction : new
 
     Packet item;
 
     `uvm_sequence_utils(Seq_device0_and_device1, Sequencer)    

     virtual task body();
        forever begin
         `uvm_do_with(item, {da == p_sequencer.cfg.device_add[0];} ); 
         `uvm_do_with(item, {da == p_sequencer.cfg.device_add[1];} ); 
        end
     endtask : body
  
endclass :Seq_device0_and_device1

One more Sequence

class Seq_constant_length extends uvm_sequence #(Packet);

     function new(string name = "Seq_constant_length");
         super.new(name);
     endfunction : new
 
     Packet item;
 
     `uvm_sequence_utils(Seq_constant_length, Sequencer)    

     virtual task body();
        forever begin
         `uvm_do_with(item, {length == 10;da == p_sequencer.cfg.device_add[0];} ); 
        end
     endtask : body
  
endclass : Seq_constant_length

Download the Source Code

uvm_switch_5.tar
Browse the code in uvm_switch_5.tar

Command to run the simulation

VCS Users : make vcs


Questa Users: make questa

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/UL_08_PHASE_5_SEQUENCER_N_SEQUENCE.html[9/26/2012 2:30:58 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/UL_08_PHASE_5_SEQUENCER_N_SEQUENCE.html[9/26/2012 2:30:58 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PHASE 6 DRIVER Index


Introduction
SystemVerilog Driver Specification
Verification Verification Plan
In this phase we will develop the driver. Driver is defined by extending uvm_driver. Phase 1 Top
Constructs Driver takes the transaction from the sequencer using seq_item_port. This transaction Phase 2 Configuration
Interface will be driven to DUT as per the interface specification. After driving the transaction Phase 3 Environment N
to DUT, it sends the transaction to scoreboard using uvm_analysis_port. Testcase
OOPS Phase 4 Packet
Randomization In driver class, we will also define task for resetting DUT and configuring the DUT. Phase 5 Sequencer N
After completing the driver class implementation, we will instantiate it in Sequence
Functional Coverage Phase 6 Driver
environment class and connect the sequencer to it. We will also update the test case
Assertion and run the simulation to check the implementation which we did till now. Phase 7 Receiver
Phase 8 Scoreboard
DPI
UVM Tutorial Report a Bug or Comment
on This section - Your
VMM Tutorial
input is what keeps
OVM Tutorial Testbench.in improving
with time!
Easy Labs : SV
Easy Labs : UVM
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

Verilog
Verification
Verilog Switch TB
Basic Constructs

1) Define the driver class by extending uvm_driver;


OpenVera
`ifndef GUARD_DRIVER
Constructs `define GUARD_DRIVER
Switch TB
class Driver extends uvm_driver #(Packet);
RVM Switch TB
RVM Ethernet sample endclass : Driver

2) Create a handle to configuration object. Using this object we can get DUT
interfaces and DUT port addresses.
Specman E
Interview Questions     Configuration cfg;

3) Declare input and memory interfaces

     virtual input_interface.IP   input_intf;


     virtual mem_interface.MEM  mem_intf;

4) Declare uvm_analysis_port which is used to send packets to scoreboard.

     uvm_analysis_port #(Packet) Drvr2Sb_port;

http://testbench.in/UL_09_PHASE_6_DRIVER.html[9/26/2012 2:31:07 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

5) Declare component utilities macro.

    `uvm_component_utils(Driver)  

6) Define the constructor method. Pass the parent object to super class.

   function new( string name = "" , uvm_component parent = null) ;


       super.new( name , parent );
   endfunction : new

7) In the build method and construct Drvr2Sb_port object.

   virtual function void build();
       super.build();
       Drvr2Sb_port = new("Drvr2Sb_port", this);
   endfunction :  build

8) In the end_of_elaboration() method, get the configuration object using


get_config_object and update the virtual interfaces.

  virtual function void end_of_elaboration();
      uvm_object tmp;
      super.end_of_elaboration();
      assert(get_config_object("Configuration",tmp));
      $cast(cfg,tmp);
      this.input_intf = cfg.input_intf;
      this.mem_intf = cfg.mem_intf;
  endfunction : end_of_elaboration

 
9) Define the reset_dut() method which will be used for resetting the DUT.

 virtual task reset_dut();
      uvm_report_info(get_full_name(),"Start of reset_dut() method ",UVM_LOW);
      mem_intf.mem_data      <= 0;
      mem_intf.mem_add       <= 0;
      mem_intf.mem_en        <= 0;
      mem_intf.mem_rd_wr     <= 0;
      input_intf.data_in     <= 0;
      input_intf.data_status <= 0;
      
      input_intf.reset       <= 1;
      repeat (4) @ input_intf.clock;
      input_intf.reset       <= 0;

      uvm_report_info(get_full_name(),"End of reset_dut() method ",UVM_LOW);


 endtask : reset_dut

10) Define the cfg_dut() method which does the configuration due port address.

 virtual task cfg_dut();
        uvm_report_info(get_full_name(),"Start of cfg_dut() method ",UVM_LOW);
        mem_intf.cb.mem_en <= 1;
        @(mem_intf.cb);
        mem_intf.cb.mem_rd_wr <= 1;

        foreach (cfg.device_add[i])  begin

            @(mem_intf.cb);
            mem_intf.cb.mem_add  <= i;
            mem_intf.cb.mem_data <= cfg.device_add[i];
            uvm_report_info(get_full_name(),$psprintf(" Port %0d Address %h
",i,cfg.device_add[i]),UVM_LOW);
        
        end
        
        @(mem_intf.cb);
        mem_intf.cb.mem_en    <=0;

http://testbench.in/UL_09_PHASE_6_DRIVER.html[9/26/2012 2:31:07 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

        mem_intf.cb.mem_rd_wr <= 0;
        mem_intf.cb.mem_add   <= 0;
        mem_intf.cb.mem_data  <= 0;
  
        uvm_report_info(get_full_name(),"End of cfg_dut() method ",UVM_LOW);
 endtask : cfg_dut

11) Define drive() method which will be used to drive the packet to DUT. In this
method pack the packet fields using the pack_bytes() method of the transaction and
drive the packed data to DUT interface.  

virtual task drive(Packet pkt);
      byte unsigned  bytes[];
      int pkt_len;
      pkt_len = pkt.pack_bytes(bytes);
      uvm_report_info(get_full_name(),"Driving packet ...",UVM_LOW);

      foreach(bytes[i])
      begin
          @(input_intf.cb);
          input_intf.data_status <= 1 ;
          input_intf.data_in <= bytes[i];
      end

      @(input_intf.cb);
      input_intf.data_status <= 0 ;
      input_intf.data_in <= 0;
      repeat(2) @(input_intf.cb);
endtask : drive

12) Now we will use the above 3 defined methods and update the run() method of
uvm_driver.
First call the reset_dut() method and then cfg_dut(). After completing the
configuration, in a forever loop get the transaction from seq_item_port and send it
DUT using drive() method and also to scoreboard using Drvr2SB_port .

 virtual task run();
     Packet pkt;
     @(input_intf.cb);
     reset_dut();
     cfg_dut();
     forever begin
         seq_item_port.get_next_item(pkt);
         Drvr2Sb_port.write(pkt);
         @(input_intf.cb);
         drive(pkt);
         @(input_intf.cb);
         seq_item_port.item_done();
    end
 endtask : run

Driver class source code

`ifndef GUARD_DRIVER
`define GUARD_DRIVER

class Driver extends uvm_driver #(Packet);

    Configuration cfg;
  
    virtual input_interface.IP   input_intf;
    virtual mem_interface.MEM  mem_intf;
    
    uvm_analysis_port #(Packet) Drvr2Sb_port;

    `uvm_component_utils(Driver) 
  
    function new( string name = "" , uvm_component parent = null) ;
        super.new( name , parent );
    endfunction : new
  
    virtual function void build();
        super.build();

http://testbench.in/UL_09_PHASE_6_DRIVER.html[9/26/2012 2:31:07 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

        Drvr2Sb_port = new("Drvr2Sb", this);
    endfunction :  build
  
    virtual function void end_of_elaboration();
        uvm_object tmp;
        super.end_of_elaboration();
        assert(get_config_object("Configuration",tmp));
        $cast(cfg,tmp);
        this.input_intf = cfg.input_intf;
        this.mem_intf = cfg.mem_intf;
    endfunction : end_of_elaboration

    virtual task run();
        Packet pkt;
        @(input_intf.cb);
        reset_dut();
        cfg_dut();
        forever begin
            seq_item_port.get_next_item(pkt);
            Drvr2Sb_port.write(pkt);
            @(input_intf.cb);
            drive(pkt);
            @(input_intf.cb);
            seq_item_port.item_done();
        end
    endtask : run
  
    virtual task reset_dut();
        uvm_report_info(get_full_name(),"Start of reset_dut() method ",UVM_LOW);
        mem_intf.mem_data      <= 0;
        mem_intf.mem_add       <= 0;
        mem_intf.mem_en        <= 0;
        mem_intf.mem_rd_wr     <= 0;
        input_intf.data_in     <= 0;
        input_intf.data_status <= 0;
        
        input_intf.reset       <= 1;
        repeat (4) @ input_intf.clock;
            input_intf.reset       <= 0;
  
        uvm_report_info(get_full_name(),"End of reset_dut() method ",UVM_LOW);
    endtask : reset_dut
  
    virtual task cfg_dut();
        uvm_report_info(get_full_name(),"Start of cfg_dut() method ",UVM_LOW);
        mem_intf.cb.mem_en <= 1;
        @(mem_intf.cb);
        mem_intf.cb.mem_rd_wr <= 1;

        foreach (cfg.device_add[i])  begin

            @(mem_intf.cb);
            mem_intf.cb.mem_add  <= i;
            mem_intf.cb.mem_data <= cfg.device_add[i];
            uvm_report_info(get_full_name(),$psprintf(" Port %0d Address %h
",i,cfg.device_add[i]),UVM_LOW);
        
        end
        
        @(mem_intf.cb);
        mem_intf.cb.mem_en    <=0;
        mem_intf.cb.mem_rd_wr <= 0;
        mem_intf.cb.mem_add   <= 0;
        mem_intf.cb.mem_data  <= 0;
  
        uvm_report_info(get_full_name(),"End of cfg_dut() method ",UVM_LOW);
   endtask : cfg_dut
  
   virtual task drive(Packet pkt);
        byte unsigned  bytes[];
        int pkt_len;
        pkt_len = pkt.pack_bytes(bytes);
        uvm_report_info(get_full_name(),"Driving packet ...",UVM_LOW);

http://testbench.in/UL_09_PHASE_6_DRIVER.html[9/26/2012 2:31:07 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

        foreach(bytes[i])
        begin
            @(input_intf.cb);
            input_intf.data_status <= 1 ;
            input_intf.data_in <= bytes[i];
        end
  
        @(input_intf.cb);
        input_intf.data_status <= 0 ;
        input_intf.data_in <= 0;
        repeat(2) @(input_intf.cb);
   endtask : drive

endclass : Driver

`endif

Environment Updates

We will take the instance of Sequencer and Driver and connect them in Environment
class.

1) Declare handles to Driver and Sequencer.

     Sequencer Seqncr;


     Driver Drvr;

2) In build method, construct Seqncr and Drvr object using create() method.

        Drvr   = Driver::type_id::create("Drvr",this);
        Seqncr = Sequencer::type_id::create("Seqncr",this);

2) In connect() method connect the sequencer seq_item_port to drivers


seq_item_export.

     Drvr.seq_item_port.connect(Seqncr.seq_item_export);

Environment class code

`ifndef GUARD_ENV
`define GUARD_ENV

class Environment extends uvm_env;

    `uvm_component_utils(Environment)

     Sequencer Seqncr;


     Driver Drvr;

    function new(string name , uvm_component parent = null);


        super.new(name, parent);
    endfunction: new

http://testbench.in/UL_09_PHASE_6_DRIVER.html[9/26/2012 2:31:07 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

    virtual function void build();


        super.build();
        uvm_report_info(get_full_name(),"START of build ",UVM_LOW);

        Drvr   = Driver::type_id::create("Drvr",this);
        Seqncr = Sequencer::type_id::create("Seqncr",this);

        uvm_report_info(get_full_name(),"END of build ",UVM_LOW);


    endfunction
    
    virtual function void connect();
        super.connect();
        uvm_report_info(get_full_name(),"START of connect ",UVM_LOW);

        Drvr.seq_item_port.connect(Seqncr.seq_item_export);

        uvm_report_info(get_full_name(),"END of connect ",UVM_LOW);


    endfunction

endclass : Environment

`endif

Testcase Updates

We will update the testcase and run the simulation.

1)In the build() method, update the configuration address in the configuration object
which in top module.

    virtual function void build();
        super.build();

        cfg.device_add[0] = 0;
        cfg.device_add[1] = 1;
        cfg.device_add[2] = 2;
        cfg.device_add[3] = 3;

2) In the build() method itself, using set_config_object , configure the configuration


object with the one which is in top module.
   with this, the configuration object in Sequencer and Driver will be pointing to the
one which in top module.

        set_config_object("t_env.*","Configuration",cfg);

3) In the build method, using set_config_string, configure the default_sequence of the


sequencer to use the sequence which we defined.

        set_config_string("*.Seqncr", "default_sequence", "Seq_device0_and_device1");

4) Set the sequencer count value to 2 .

        set_config_int("*.Seqncr", "count",2);

5) Update the run() method to print the Sequencer details.    

     t_env.Seqncr.print();

Testcase code

class test1 extends uvm_test;

    `uvm_component_utils(test1)

     Environment t_env ;

    function new (string name="test1", uvm_component parent=null);


        super.new (name, parent);
        t_env = new("t_env",this);
    endfunction : new

    virtual function void build();

http://testbench.in/UL_09_PHASE_6_DRIVER.html[9/26/2012 2:31:07 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

        super.build();

        cfg.device_add[0] = 0;
        cfg.device_add[1] = 1;
        cfg.device_add[2] = 2;
        cfg.device_add[3] = 3;
 
        set_config_object("t_env.*","Configuration",cfg);
        set_config_string("*.Seqncr", "default_sequence", "Seq_device0_and_device1");
        set_config_int("*.Seqncr", "count",2);

    endfunction

    virtual task run ();

       t_env.Seqncr.print();

        #3000ns;
        global_stop_request();
    endtask : run

endclass : test1

Download the source code

uvm_switch_6.tar
Browse the code in uvm_switch_6.tar

Command to run the simulation

VCS Users : make vcs


Questa Users: make questa

Log report after simulation

UVM_INFO @ 0 [RNTST] Running test test1...


UVM_INFO @ 0: uvm_test_top.t_env [uvm_test_top.t_env] START of build
UVM_INFO @ 0: uvm_test_top.t_env [uvm_test_top.t_env] END of build
UVM_INFO @ 0: uvm_test_top.t_env [uvm_test_top.t_env] START of connect
UVM_INFO @ 0: uvm_test_top.t_env [uvm_test_top.t_env] END of connect
----------------------------------------------------------------------
Name                     Type                Size                Value
----------------------------------------------------------------------
Seqncr                   Sequencer           -               Seqncr@14
--rsp_export             uvm_analysis_export -           rsp_export@16
--seq_item_export        uvm_seq_item_pull_+ -      seq_item_export@40
--default_sequence       string              19    uvm_random_sequence
--count                  integral            32                     -1
--max_random_count       integral            32                   'd10
--sequences              array               5                       -
----[0]                  string              19    uvm_random_sequence
----[1]                  string              23   uvm_exhaustive_sequ+
----[2]                  string              19    uvm_simple_sequence
----[3]                  string              23   Seq_device0_and_dev+
----[4]                  string              19    Seq_constant_length
--max_random_depth       integral            32                    'd4
--num_last_reqs          integral            32                    'd1
--num_last_rsps          integral            32                    'd1
----------------------------------------------------------------------
UVM_INFO @ 30: uvm_test_top.t_env.Drvr [uvm_test_top.t_env.Drvr]
                Start of reset_dut() method
UVM_INFO @ 70: uvm_test_top.t_env.Drvr [uvm_test_top.t_env.Drvr]
                End of reset_dut() method
UVM_INFO @ 70: uvm_test_top.t_env.Drvr [uvm_test_top.t_env.Drvr]
                Start of cfg_dut() method
UVM_INFO @ 110: uvm_test_top.t_env.Drvr [uvm_test_top.t_env.Drvr]  
                Port 0 Address 00
UVM_INFO @ 130: uvm_test_top.t_env.Drvr [uvm_test_top.t_env.Drvr]  
                Port 1 Address 01
UVM_INFO @ 150: uvm_test_top.t_env.Drvr [uvm_test_top.t_env.Drvr]  
                Port 2 Address 02
UVM_INFO @ 170: uvm_test_top.t_env.Drvr [uvm_test_top.t_env.Drvr]  

http://testbench.in/UL_09_PHASE_6_DRIVER.html[9/26/2012 2:31:07 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

                Port 3 Address 03
UVM_INFO @ 190: uvm_test_top.t_env.Drvr [uvm_test_top.t_env.Drvr]
                End of cfg_dut() method
UVM_INFO @ 210: uvm_test_top.t_env.Drvr [uvm_test_top.t_env.Drvr]
                Driving packet ...
UVM_INFO @ 590: uvm_test_top.t_env.Drvr [uvm_test_top.t_env.Drvr]
                Driving packet ...
UVM_INFO @ 970: uvm_test_top.t_env.Drvr [uvm_test_top.t_env.Drvr]
                Driving packet ...

--- UVM Report Summary ---

** Report counts by severity


UVM_INFO :   16
UVM_WARNING :    0
UVM_ERROR :    0
UVM_FATAL :    0

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/UL_09_PHASE_6_DRIVER.html[9/26/2012 2:31:07 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PHASE 7 RECEIVER Index


Introduction
SystemVerilog Specification
Verification In this phase, we will write a receiver and use the receiver in environment class to Verification Plan
collect the packets coming from the switch output_interface. Phase 1 Top
Constructs Phase 2 Configuration
Interface Receiver Phase 3 Environment N
Testcase
OOPS
Receiver collects the data bytes from the interface signal. And then unpacks the bytes Phase 4 Packet
Randomization in to packet using unpack_bytes method and pushes it into Rcvr2Sb_port for score Phase 5 Sequencer N
boarding. Sequence
Functional Coverage Phase 6 Driver
Assertion Receiver class is written in Reveicer.sv file. Phase 7 Receiver
Phase 8 Scoreboard
DPI
Receiver class is defined by extending uvm_component class. It will drive the received
UVM Tutorial transaction to scoreboard using uvm_analysis_port. Report a Bug or Comment
on This section - Your
VMM Tutorial
input is what keeps
OVM Tutorial Testbench.in improving
with time!
Easy Labs : SV
Easy Labs : UVM
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

Verilog
Verification
Verilog Switch TB
Basic Constructs

1) Define Receiver class by extending uvm_component.


OpenVera
Constructs `ifndef GUARD_RECEIVER
Switch TB `define GUARD_RECEIVER
RVM Switch TB class Receiver extends uvm_component;
RVM Ethernet sample
endclass : Receiver

`endif
Specman E
Interview Questions 2) Declare configuration class object.

    Configuration cfg;

3) Declare an integer to hold the receiver number.

    integer id;

4) Declare a virtual interface of dut out put side.

  virtual output_interface.OP output_intf;

http://testbench.in/UL_10_PHASE_7_RECEIVER.html[9/26/2012 2:31:16 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

5) Declare analysis port which is used by receiver to send the received transaction to
scoreboard.

  uvm_analysis_port #(Packet) Rcvr2Sb_port;

6) Declare the utility macro. This utility macro provides the implementation of creat()
and get_type_name() methods.

  `uvm_component_utils(Receiver) 

7) Define the constructor.

   function new (string name, uvm_component parent);
      super.new(name, parent);
   endfunction : new

8) Define the build method and construct the Rcvr2Sb_port.

   virtual function void build();
      super.build();
      Rcvr2Sb_port = new("Rcvr2Sb", this); 
   endfunction : build

9) In the end_of_elaboration() method, get the configuration object using


get_config_object and update the virtual interfaces.

   virtual function void end_of_elaboration();
      uvm_object tmp;
      super.end_of_elaboration();
      assert(get_config_object("Configuration",tmp));
      $cast(cfg,tmp);
      output_intf = cfg.output_intf[id]; 
   endfunction : end_of_elaboration

10) Define the run() method. This method collects the packets from the DUT output
interface and unpacks it into high level transaction using transactions unpack_bytes()
method.

     virtual task run();
     Packet pkt;
         fork
         forever
         begin
            // declare the queue and dynamic array here
            // so they are automatically allocated for every packet
             bit [7:0] bq[$],bytes[];

             repeat(2) @(posedge output_intf.clock);
             wait(output_intf.cb.ready)
             output_intf.cb.read <= 1;  
    
             repeat(2) @(posedge output_intf.clock);
             while (output_intf.cb.ready)
             begin
                  bq.push_back(output_intf.cb.data_out);
                  @(posedge output_intf.clock);
             end
             bytes = new[bq.size()] (bq); // Copy queue into dyn array

             output_intf.cb.read <= 0;  


             @(posedge output_intf.clock);
             uvm_report_info(get_full_name(),"Received packet ...",UVM_LOW);
             pkt = new();
             void'(pkt.unpack_bytes(bytes));
             Rcvr2Sb_port.write(pkt);
         end
         join

http://testbench.in/UL_10_PHASE_7_RECEIVER.html[9/26/2012 2:31:16 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

     endtask : run

Receiver class source code


`ifndef GUARD_RECEIVER
`define GUARD_RECEIVER

class Receiver extends uvm_component;

    virtual output_interface.OP output_intf;

    Configuration cfg;

    integer id;

    uvm_analysis_port #(Packet) Rcvr2Sb_port;

   `uvm_component_utils(Receiver) 

    function new (string name, uvm_component parent);
        super.new(name, parent);
    endfunction : new

    virtual function void build();
        super.build();
        Rcvr2Sb_port = new("Rcvr2Sb", this);
    endfunction : build

    virtual function void end_of_elaboration();
        uvm_object tmp;
        super.end_of_elaboration();
        assert(get_config_object("Configuration",tmp));
        $cast(cfg,tmp);
        output_intf = cfg.output_intf[id]; 
    endfunction : end_of_elaboration

    virtual task run();
    Packet pkt;
         fork
         forever
         begin
            // declare the queue and dynamic array here
            // so they are automatically allocated for every packet
             bit [7:0] bq[$],bytes[];

             repeat(2) @(posedge output_intf.clock);
             wait(output_intf.cb.ready)
             output_intf.cb.read <= 1;  
    
             repeat(2) @(posedge output_intf.clock);
             while (output_intf.cb.ready)
             begin
                  bq.push_back(output_intf.cb.data_out);
                  @(posedge output_intf.clock);
             end
             bytes = new[bq.size()] (bq); // Copy queue into dyn array

             output_intf.cb.read <= 0;  


             @(posedge output_intf.clock);
             uvm_report_info(get_full_name(),"Received packet ...",UVM_LOW);
             pkt = new();
             void'(pkt.unpack_bytes(bytes));
             Rcvr2Sb_port.write(pkt);
         end
         join

     endtask : run

endclass :  Receiver

Environment Class Updates

http://testbench.in/UL_10_PHASE_7_RECEIVER.html[9/26/2012 2:31:16 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

We will update the Environment class and take instance of receiver and run the
testcase.

1) Declare 4 receivers.

    Receiver Rcvr[4];

2) In the build() method construct the Receivers using create() methods. Also update
the id variable of the receiver object.  

    foreach(Rcvr[i]) begin
        Rcvr[i]   = Receiver::type_id::create($psprintf("Rcvr%0d",i),this);
        Rcvr[i].id = i;
    end

Environment class source code

`ifndef GUARD_ENV
`define GUARD_ENV

class Environment extends uvm_env;

    `uvm_component_utils(Environment)

     Sequencer Seqncr;


     Driver Drvr;

     Receiver Rcvr[4];

    function new(string name , uvm_component parent = null);


        super.new(name, parent);
    endfunction: new

    virtual function void build();


        super.build();
        uvm_report_info(get_full_name(),"START of build ",UVM_LOW);
        Drvr   = Driver::type_id::create("Drvr",this);
        Seqncr = Sequencer::type_id::create("Seqncr",this);

        foreach(Rcvr[i]) begin
            Rcvr[i]   = Receiver::type_id::create($psprintf("Rcvr%0d",i),this);
            Rcvr[i].id = i;
        end

        uvm_report_info(get_full_name(),"END of build ",UVM_LOW);


    endfunction
    
    virtual function void connect();
        super.connect();
        uvm_report_info(get_full_name(),"START of connect ",UVM_LOW);
        Drvr.seq_item_port.connect(Seqncr.seq_item_export);
        uvm_report_info(get_full_name(),"END of connect ",UVM_LOW);
    endfunction

endclass : Environment
`endif

Download the Source Code

http://testbench.in/UL_10_PHASE_7_RECEIVER.html[9/26/2012 2:31:16 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

uvm_switch_7.tar
Browse the code in uvm_switch_7.tar

Command to run the simulation

VCS Users : make vcs


Questa Users: make questa

Log report after simulation

UVM_INFO @ 0 [RNTST] Running test test1...


UVM_INFO @ 0: uvm_test_top.t_env [uvm_test_top.t_env] START of build
UVM_INFO @ 0: uvm_test_top.t_env [uvm_test_top.t_env] END of build
UVM_INFO @ 0: uvm_test_top.t_env [uvm_test_top.t_env] START of connect
UVM_INFO @ 0: uvm_test_top.t_env [uvm_test_top.t_env] END of connect
----------------------------------------------------------------------
Name                     Type                Size                Value
----------------------------------------------------------------------
Seqncr                   Sequencer           -               Seqncr@14
--rsp_export             uvm_analysis_export -           rsp_export@16
--seq_item_export        uvm_seq_item_pull_+ -      seq_item_export@40
--default_sequence       string              19    uvm_random_sequence
--count                  integral            32                     -1
--max_random_count       integral            32                   'd10
--sequences              array               5                       -
----[0]                  string              19    uvm_random_sequence
----[1]                  string              23   uvm_exhaustive_sequ+
----[2]                  string              19    uvm_simple_sequence
----[3]                  string              23   Seq_device0_and_dev+
----[4]                  string              19    Seq_constant_length
--max_random_depth       integral            32                    'd4
--num_last_reqs          integral            32                    'd1
--num_last_rsps          integral            32                    'd1
----------------------------------------------------------------------
UVM_INFO @ 30: uvm_test_top.t_env.Drvr [uvm_test_top.t_env.Drvr]
               Start of reset_dut() method
UVM_INFO @ 70: uvm_test_top.t_env.Drvr [uvm_test_top.t_env.Drvr]
               End of reset_dut() method
UVM_INFO @ 70: uvm_test_top.t_env.Drvr [uvm_test_top.t_env.Drvr]
               Start of cfg_dut() method
UVM_INFO @ 110: uvm_test_top.t_env.Drvr [uvm_test_top.t_env.Drvr]
               Port 0 Address 00
UVM_INFO @ 130: uvm_test_top.t_env.Drvr [uvm_test_top.t_env.Drvr]  
               Port 1 Address 01
UVM_INFO @ 150: uvm_test_top.t_env.Drvr [uvm_test_top.t_env.Drvr]
               Port 2 Address 02
UVM_INFO @ 170: uvm_test_top.t_env.Drvr [uvm_test_top.t_env.Drvr]
               Port 3 Address 03
UVM_INFO @ 190: uvm_test_top.t_env.Drvr [uvm_test_top.t_env.Drvr]
               End of cfg_dut() method
UVM_INFO @ 210: uvm_test_top.t_env.Drvr [uvm_test_top.t_env.Drvr]
               Driving packet ...
UVM_INFO @ 590: uvm_test_top.t_env.Drvr [uvm_test_top.t_env.Drvr]
               Driving packet ...
UVM_INFO @ 610: uvm_test_top.t_env.Rcvr0 [uvm_test_top.t_env.Rcvr0]
               Received packet ...
UVM_INFO @ 970: uvm_test_top.t_env.Drvr [uvm_test_top.t_env.Drvr]
               Driving packet ...
UVM_INFO @ 990: uvm_test_top.t_env.Rcvr0 [uvm_test_top.t_env.Rcvr0]
               Received packet ...

--- UVM Report Summary ---

** Report counts by severity


UVM_INFO :   18
UVM_WARNING :    0
UVM_ERROR :    0
UVM_FATAL :    0

http://testbench.in/UL_10_PHASE_7_RECEIVER.html[9/26/2012 2:31:16 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/UL_10_PHASE_7_RECEIVER.html[9/26/2012 2:31:16 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PHASE 8 SCOREBOARD Index


Introduction
SystemVerilog Specification
Verification In this phase we will see the scoreboard implementation. Verification Plan
Phase 1 Top
Constructs Scoreboard Phase 2 Configuration
Interface Phase 3 Environment N
Scoreboard is implemented by extending uvm_scorboard. For our requirement, we can Testcase
OOPS Phase 4 Packet
use uvm_in_order_comparator, but we will see develop our own scoreboard by
Randomization extending uvm_scorboard. Scoreboard has 2 analysis imports. One is used to for Phase 5 Sequencer N
getting the packets from the driver and other from the receiver.  Then the packets Sequence
Functional Coverage Phase 6 Driver
are compared and if they don't match, then error is asserted. For comparison,
Assertion compare () method of the Packet class is used. Phase 7 Receiver
Phase 8 Scoreboard
DPI
Implement the scoreboard in file Scoreboard.sv.
UVM Tutorial Report a Bug or Comment
Steps to create a scoreboard: on This section - Your
VMM Tutorial
1) Useing macro `uvm_analysis_imp_decl(<_portname>), to declare input is what keeps
OVM Tutorial uvm_analysis_imp_<_portname>  class. Testbench.in improving
2) The above macro, creates write_<_portname>(). This method has to be define as with time!
Easy Labs : SV
per our requirements.
Easy Labs : UVM
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

Verilog
Verification
Verilog Switch TB
Basic Constructs
1) We need 2 import, one for expected packet which is sent by driver and received
packet which is coming from receiver.
OpenVera    Declare 2 imports using `uvm_analysis_imp_decl macros should not be defined
inside the class.
Constructs
Switch TB     `uvm_analysis_imp_decl(_rcvd_pkt)
    `uvm_analysis_imp_decl(_sent_pkt)
RVM Switch TB
RVM Ethernet sample 2) Declare a scoreboard by extending uvm_scoreboard class.

class Scoreboard extends uvm_scoreboard;
Specman E
endclass : Scoreboard
Interview Questions
3)  Declare the utility macro.

   `uvm_component_utils(Scoreboard)

4) Declare a queue which stores the expected packets.

   Packet exp_que[$];

5) Declare imports for getting expected packets and received packets.

http://testbench.in/UL_11_PHASE_8_SCOREBOARD.html[9/26/2012 2:31:24 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

   uvm_analysis_imp_rcvd_pkt #(Packet,Scoreboard) Rcvr2Sb_port;
   uvm_analysis_imp_sent_pkt #(Packet,Scoreboard) Drvr2Sb_port;

6) In the constructor, create objects for the above two declared imports.

    function new(string name, uvm_component parent);
       super.new(name, parent);
       Rcvr2Sb_port = new("Rcvr2Sb", this);
       Drvr2Sb_port = new("Drvr2Sb", this);
    endfunction : new

7) Define write_sent_pkt() method which was created by macro


`uvm_analysis_imp_decl(_sent_pkt).
   In this method, store the received packet in the expected queue.

   virtual function void write_sent_pkt(input Packet pkt);
       exp_que.push_back(pkt);
   endfunction : write_sent_pkt

8) Define write_rcvd_pkt() method which was created by macro


`uvm_analysis_imp_decl(_rcvd_pkt)
  In this method, get the transaction from the expected queue and compare.

   virtual function void write_rcvd_pkt(input Packet pkt);
       Packet exp_pkt;
       pkt.print();
       if(exp_que.size())
       begin
           exp_pkt = exp_que.pop_front();
           exp_pkt.print();
           if( pkt.compare(exp_pkt))
               uvm_report_info(get_type_name(),
               $psprintf("Sent packet and received packet matched"), UVM_LOW);
           else
               uvm_report_error(get_type_name(),
               $psprintf("Sent packet and received packet mismatched"), UVM_LOW);
       end
       else
           uvm_report_error(get_type_name(),
           $psprintf("No more packets in the expected queue to compare"), UVM_LOW);
   endfunction : write_rcvd_pkt

9) Define the report() method to print the Scoreboard information.

  virtual function void report();
      uvm_report_info(get_type_name(),
      $psprintf("Scoreboard Report %s", this.sprint()), UVM_LOW);
  endfunction : report

Complete Scoreboard Code


`ifndef GUARD_SCOREBOARD
`define GUARD_SCOREBOARD

`uvm_analysis_imp_decl(_rcvd_pkt)
`uvm_analysis_imp_decl(_sent_pkt)

class Scoreboard extends uvm_scoreboard;
    `uvm_component_utils(Scoreboard)
  
    Packet exp_que[$];
  
    uvm_analysis_imp_rcvd_pkt #(Packet,Scoreboard) Rcvr2Sb_port;
    uvm_analysis_imp_sent_pkt #(Packet,Scoreboard) Drvr2Sb_port;
  
    function new(string name, uvm_component parent);
        super.new(name, parent);
        Rcvr2Sb_port = new("Rcvr2Sb", this);
        Drvr2Sb_port = new("Drvr2Sb", this);
    endfunction : new

http://testbench.in/UL_11_PHASE_8_SCOREBOARD.html[9/26/2012 2:31:24 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

  
    virtual function void write_rcvd_pkt(input Packet pkt);
        Packet exp_pkt;
        pkt.print();

        if(exp_que.size())
        begin
           exp_pkt = exp_que.pop_front();
           exp_pkt.print();
           if( pkt.compare(exp_pkt))
             uvm_report_info(get_type_name(),
             $psprintf("Sent packet and received packet matched"), UVM_LOW);
           else
             uvm_report_error(get_type_name(),  
             $psprintf("Sent packet and received packet mismatched"), UVM_LOW);
        end
        else
             uvm_report_error(get_type_name(),
             $psprintf("No more packets to in the expected queue to
compare"), UVM_LOW);
   endfunction : write_rcvd_pkt
  
   virtual function void write_sent_pkt(input Packet pkt);
        exp_que.push_back(pkt);
   endfunction : write_sent_pkt
  
  
   virtual function void report();
        uvm_report_info(get_type_name(),
        $psprintf("Scoreboard Report %s", this.sprint()), UVM_LOW);
   endfunction : report
  
endclass : Scoreboard
`endif

Environment Class Updates

We will take the instance of scoreboard in the environment and connect its ports to
driver and receiver ports.

1) Declare scoreboard object.

     Scoreboard Sbd;

2) Construct the scoreboard object using create() method in build() method.

        Sbd   = Scoreboard::type_id::create("Sbd",this);

3) In connect() method, connect the driver and receiver ports to scoreboard.

        Drvr.Drvr2Sb_port.connect(Sbd.Drvr2Sb_port);

        foreach(Rcvr[i])
            Rcvr[i].Rcvr2Sb_port.connect(Sbd.Rcvr2Sb_port);

Environemnt class code

`ifndef GUARD_ENV

http://testbench.in/UL_11_PHASE_8_SCOREBOARD.html[9/26/2012 2:31:24 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

`define GUARD_ENV

class Environment extends uvm_env;

    `uvm_component_utils(Environment)

     Sequencer Seqncr;


     Driver Drvr;
     Receiver Rcvr[4];

     Scoreboard Sbd;

    function new(string name , uvm_component parent = null);


        super.new(name, parent);
    endfunction: new

    virtual function void build();


        super.build();
        uvm_report_info(get_full_name(),"START of build ",UVM_LOW);

        Drvr   = Driver::type_id::create("Drvr",this);
        Seqncr = Sequencer::type_id::create("Seqncr",this);
        
        foreach(Rcvr[i]) begin
            Rcvr[i]   = Receiver::type_id::create($psprintf("Rcvr%0d",i),this);
            Rcvr[i].id = i;
        end

        Sbd   = Scoreboard::type_id::create("Sbd",this);

        uvm_report_info(get_full_name(),"END of build ",UVM_LOW);


    endfunction
    
    virtual function void connect();
        super.connect();
        uvm_report_info(get_full_name(),"START of connect ",UVM_LOW);

        Drvr.seq_item_port.connect(Seqncr.seq_item_export);

        Drvr.Drvr2Sb_port.connect(Sbd.Drvr2Sb_port);

        foreach(Rcvr[i])
            Rcvr[i].Rcvr2Sb_port.connect(Sbd.Rcvr2Sb_port);

        uvm_report_info(get_full_name(),"END of connect ",UVM_LOW);


    endfunction

endclass : Environment
`endif

Download the Source Code

uvm_switch_8.tar
Browse the code in uvm_switch_8.tar

Command to run the simulation

VCS Users : make vcs


Questa Users: make questa

Log report after simulation

UVM_INFO @ 0 [RNTST] Running test test1...


UVM_INFO @ 0: uvm_test_top.t_env [uvm_test_top.t_env] START of build
UVM_INFO @ 0: uvm_test_top.t_env [uvm_test_top.t_env] END of build
UVM_INFO @ 0: uvm_test_top.t_env [uvm_test_top.t_env] START of connect
UVM_INFO @ 0: uvm_test_top.t_env [uvm_test_top.t_env] END of connect
----------------------------------------------------------------------
Name                     Type                Size                Value
----------------------------------------------------------------------
Seqncr                   Sequencer           -               Seqncr@14
  rsp_export             uvm_analysis_export -           rsp_export@16

http://testbench.in/UL_11_PHASE_8_SCOREBOARD.html[9/26/2012 2:31:24 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

  seq_item_export        uvm_seq_item_pull_+ -      seq_item_export@40
  default_sequence       string              19    uvm_random_sequence
  count                  integral            32                     -1
  max_random_count       integral            32                   'd10
  sequences              array               5                       -
    [0]                  string              19    uvm_random_sequence
    [1]                  string              23   uvm_exhaustive_sequ+
    [2]                  string              19    uvm_simple_sequence
    [3]                  string              23   Seq_device0_and_dev+
    [4]                  string              19    Seq_constant_length
  max_random_depth       integral            32                    'd4
  num_last_reqs          integral            32                    'd1
  num_last_rsps          integral            32                    'd1
----------------------------------------------------------------------
UVM_INFO @ 30: uvm_test_top.t_env.Drvr [uvm_test_top.t_env.Drvr]
            Start of reset_dut() method
UVM_INFO @ 70: uvm_test_top.t_env.Drvr [uvm_test_top.t_env.Drvr]
            End of reset_dut() method
UVM_INFO @ 70: uvm_test_top.t_env.Drvr [uvm_test_top.t_env.Drvr]
            Start of cfg_dut() method
UVM_INFO @ 110: uvm_test_top.t_env.Drvr [uvm_test_top.t_env.Drvr]  
            Port 0 Address 00
UVM_INFO @ 130: uvm_test_top.t_env.Drvr [uvm_test_top.t_env.Drvr]
            Port 1 Address 01
UVM_INFO @ 150: uvm_test_top.t_env.Drvr [uvm_test_top.t_env.Drvr]
            Port 2 Address 02
UVM_INFO @ 170: uvm_test_top.t_env.Drvr [uvm_test_top.t_env.Drvr]
            Port 3 Address 03
UVM_INFO @ 190: uvm_test_top.t_env.Drvr [uvm_test_top.t_env.Drvr]
            End of cfg_dut() method
UVM_INFO @ 210: uvm_test_top.t_env.Drvr [uvm_test_top.t_env.Drvr]
            Driving packet ...
UVM_INFO @ 590: uvm_test_top.t_env.Drvr [uvm_test_top.t_env.Drvr]
            Driving packet ...
UVM_INFO @ 610: uvm_test_top.t_env.Rcvr0 [uvm_test_top.t_env.Rcvr0]
            Received packet ...
UVM_INFO @ 610: uvm_test_top.t_env.Sbd [Scoreboard]
            Sent packet and received packet matched
UVM_INFO @ 970: uvm_test_top.t_env.Drvr [uvm_test_top.t_env.Drvr]
           Driving packet ...
UVM_INFO @ 990: uvm_test_top.t_env.Rcvr0 [uvm_test_top.t_env.Rcvr0]
           Received packet ...
UVM_INFO @ 990: uvm_test_top.t_env.Sbd [Scoreboard]
            Sent packet and received packet matched
UVM_INFO @ 1000: uvm_test_top.t_env.Sbd [Scoreboard]
           Scoreboard Report
----------------------------------------------------------------------
Name                     Type                Size                Value
----------------------------------------------------------------------
Sbd                      Scoreboard          -                  Sbd@52
  Drvr2Sb                uvm_analysis_imp_s+ -              Drvr2Sb@56
  Rcvr2Sb                uvm_analysis_imp_r+ -              Rcvr2Sb@54
----------------------------------------------------------------------

--- UVM Report Summary ---

** Report counts by severity


UVM_INFO :   21
UVM_WARNING :    0
UVM_ERROR :    0
UVM_FATAL :    0

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/UL_11_PHASE_8_SCOREBOARD.html[9/26/2012 2:31:24 PM]


WWW.TESTBENCH.IN - Easy Labs : UVM

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/UL_11_PHASE_8_SCOREBOARD.html[9/26/2012 2:31:24 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INTRODUCTION Index


Introduction
SystemVerilog Specification
Verification In this tutorial, we will verify the Switch RTL core using OVM in SystemVerilog. Verification Plan
Following are the steps we follow to verify the Switch RTL core. Phase 1 Top
Constructs Phase 2 Configuration
Interface 1) Understand the specification Phase 3 Environment N
Testcase
OOPS Phase 4 Packet
2) Developing Verification Plan
Randomization Phase 5 Sequencer N
Functional Coverage
3) Building the Verification Environment. We will build the Environment in Multiple Sequence
phases, so it will be easy for you to lean step by step. Phase 6 Driver
Assertion    In this verification environment, I will not use agents and monitors to make this Phase 7 Receiver
tutorial simple and easy. Phase 8 Scoreboard
DPI
UVM Tutorial  Phase 1) We will develop the interfaces, and connect it to DUT in top module. Report a Bug or Comment
on This section - Your
VMM Tutorial
 Phase 2) We will develop the Configuration class. input is what keeps
OVM Tutorial Testbench.in improving
Easy Labs : SV  Phase 3) We will develop the Environment class and Simple testcase and simulate with time!
them.
Easy Labs : UVM
Easy Labs : OVM  Phase 4) We will develop packet class based on the stimulus plan. We will also write
a small code to test the packet class implementation.
Easy Labs : VMM
AVM Switch TB  Phase 5) We will develop sequencer and a sample sequences.
VMM Ethernet sample  Phase 6) We will develop driver and connect it to the Sequencer in to environment.  

 Phase 7) We will develop receiver and instantiate in environment.


Verilog
Verification  Phase 8) We will develop scoreboard which does the comparison of the expected
packet with the actual packet received from the DUT and connect it to driver and
Verilog Switch TB receiver in Environment class.
Basic Constructs

  
OpenVera   I would like to thank to Vishnu Prashant(Vitesse) for teaching me OVM.
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/CM_01_INTRODUCTION.html[9/26/2012 2:31:33 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CM_01_INTRODUCTION.html[9/26/2012 2:31:33 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS SPECIFICATION Index


Introduction
SystemVerilog Switch Specification: Specification
Verification Verification Plan
This is a simple switch. Switch is a packet based protocol. Switch drives the incoming Phase 1 Top
Constructs packet which comes from the input port to output ports based on the address Phase 2 Configuration
Interface contained in the packet. Phase 3 Environment N
Testcase
OOPS
The switch has a one input port from which the packet enters. It has four output ports Phase 4 Packet
Randomization where the packet is driven out. Phase 5 Sequencer N
Sequence
Functional Coverage Phase 6 Driver
Assertion Phase 7 Receiver
Phase 8 Scoreboard
DPI
UVM Tutorial Report a Bug or Comment
on This section - Your
VMM Tutorial
input is what keeps
OVM Tutorial Testbench.in improving
with time!
Easy Labs : SV
Easy Labs : UVM
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

Verilog
Verification
Verilog Switch TB
Basic Constructs

Packet Format:
OpenVera
Constructs Packet contains 3 parts. They are Header, data and frame check sequence.
Packet width is 8 bits and the length of the packet can be between 4 bytes to 259
Switch TB bytes.
RVM Switch TB
RVM Ethernet sample
Packet header:

Packet header contains three fields DA, SA and length.


Specman E
Interview Questions DA: Destination address of the packet is of 8 bits. The switch drives the packet to
respective ports based on this destination address of the packets. Each output port
has 8-bit unique port address.  If the destination address of the packet matches the
port address, then switch drives the packet to the output port.

SA: Source address of the packet from where it originate. It is 8 bits.

Length: Length of the data is of 8 bits and from 0 to 255. Length is measured in
terms of bytes.  
If Length = 0, it means data length is 0 bytes
If Length = 1, it means data length is 1 bytes

http://testbench.in/CM_02_SPECIFICATION.html[9/26/2012 2:31:40 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

If Length = 2, it means data length is 2 bytes


If Length = 255, it means data length is 255 bytes

Data: Data should be in terms of bytes and can take anything.

FCS: Frame check sequence


 This field contains the security check of the packet. It is calculated over the header
and data.

Configuration:

Switch has four output ports. These output ports address have to be configured to a
unique address. Switch matches the DA field of the packet with this configured port
address and sends the packet on to that port. Switch contains a memory. This
memory has 4 locations, each can store 8 bits. To configure the switch port address,
memory write operation has to be done using memory interface. Memory address
(0,1,2,3) contains the address of port(0,1,2,3) respectively.

Interface Specification:

The Switch has one input Interface, from where the packet enters and 4 output
interfaces from where the packet comes out and one memory interface, through the
port address can be configured.  Switch also has a clock and asynchronous reset
signal.  

 
MEMORY INTERFACE:

Through memory interfaced output port address are configured. It accepts 8 bit data
to be written to memory. It has 8 bit address inputs. Address 0,1,2,3 contains the
address of the port 0,1,2,3 respectively.

There are 4 input signals to memory interface. They are

input mem_en;
input mem_rd_wr;
input [1:0] mem_add;
input [7:0] mem_data;

All the signals are active high and are synchronous to the positive edge of clock
signal.
To configure a port address,

http://testbench.in/CM_02_SPECIFICATION.html[9/26/2012 2:31:40 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

1.      Assert the mem_en signal.


2.      Asser the mem_rd_wr signal.
3.      Drive the port number (0 or 1 or 2 or 3) on the mem_add signal
4.      Drive the 8 bit port address on to mem_data signal.

INPUT PORT

Packets are sent into the switch using input port.


All the signals are active high and are synchronous to the positive edge of clock
signal.

input port has 2 input signals. They are


input [7:0] data;
input data_status;

To send the packet in to switch,

1. Assert the data_status signal.


2. Send the packet on the data signal byte by byte.
3. After sending all the data bytes, deassert the data_status signal.
4. There should be at least 3 clock cycles difference between packets.

OUTPUT PORT

Switch sends the packets out using the output ports.  There are 4 ports, each having
data, ready and read signals.  All the signals are active high and are synchronous to
the positive edge of clock signal.

Signal list is

output   [7:0] port0;
output   [7:0] port1;
output   [7:0] port2;
output   [7:0] port3;
output         ready_0;
output       ready_1;
output       ready_2;
output       ready_3;
input       read_0;
input       read_1;
input       read_2;
input       read_3;

When the data is ready to be sent out from the port, switch asserts ready_* signal
high indicating that data is ready to be sent.
If the read_* signal is asserted, when ready_* is high, then the data comes out of the
port_* signal after one clock cycle.

http://testbench.in/CM_02_SPECIFICATION.html[9/26/2012 2:31:40 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

RTL  code:

RTL code is attached with the tar files. From the Phase 1, you can download the tar
files.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CM_02_SPECIFICATION.html[9/26/2012 2:31:40 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS VERIFICATION PLAN Index


Introduction
SystemVerilog Overview Specification
Verification Verification Plan
This Document describes the Verification Plan for Switch. The Verification Plan is Phase 1 Top
Constructs based on System Verilog Hardware Verification Language. The methodology used for Phase 2 Configuration
Interface Verification is Constraint random coverage driven verification. Phase 3 Environment N
Testcase
OOPS Phase 4 Packet
Randomization Feature Extraction Phase 5 Sequencer N
Sequence
Functional Coverage Phase 6 Driver
This section contains list of all the features to be verified.
Assertion 1) Phase 7 Receiver
ID:  Configuration Phase 8 Scoreboard
DPI
Description: Configure all the 4 port address with unique values.
UVM Tutorial Report a Bug or Comment
2) on This section - Your
VMM Tutorial
ID: Packet DA input is what keeps
OVM Tutorial Description: DA field of packet should be any of the port address. All the 4 port Testbench.in improving
address should be used. with time!
Easy Labs : SV
Easy Labs : UVM 3)
Easy Labs : OVM ID : Packet payload
Description: Length can be from 1 to 255. Send packets with all the lengths.
Easy Labs : VMM
AVM Switch TB 4)
ID: Length
VMM Ethernet sample Description:
Length field contains length of the payload.

Verilog 5)
Verification ID: FCS
Description:
Verilog Switch TB Good FCS:  Send packet with good FCS.
Basic Constructs Bad FCS: Send packet with corrupted FCS.  

Stimulus Generation Plan


OpenVera
Constructs 1) Packet DA: Generate packet DA with the configured address.
Switch TB 2) Payload length: generate payload length ranging from 2 to 255.
3) Generate good and bad FCS.
RVM Switch TB
RVM Ethernet sample

Verification Environment
Specman E
Interview Questions

http://testbench.in/CM_03_VERIFICATION_PLAN.html[9/26/2012 2:31:48 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

  

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CM_03_VERIFICATION_PLAN.html[9/26/2012 2:31:48 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PHASE 1 TOP Index


Introduction
SystemVerilog In phase 1, Specification
Verification Verification Plan
1) We will write SystemVerilog Interfaces for input port, output port and memory Phase 1 Top
Constructs port. Phase 2 Configuration
Interface 2) We will write Top module where testcase and DUT instances are done. Phase 3 Environment N
3) DUT and interfaces are connected in top module. Testcase
OOPS Phase 4 Packet
4) We will implement Clock generator in top module.
Randomization Phase 5 Sequencer N
Sequence
Functional Coverage Phase 6 Driver
  
Assertion Interface Phase 7 Receiver
Phase 8 Scoreboard
DPI
In the interface.sv file, declare the 3 interfaces in the following way.
UVM Tutorial    All the interfaces has clock as input. Report a Bug or Comment
   All the signals in interface are wire type. on This section - Your
VMM Tutorial
   All the signals are synchronized to clock except reset in clocking block. input is what keeps
OVM Tutorial Testbench.in improving
Easy Labs : SV This approach will avoid race conditions between the design and the verification with time!
environment.
Easy Labs : UVM Define the set-up and hold time using parameters.
Easy Labs : OVM Signal directional w.r.t TestBench is specified with modport.
Easy Labs : VMM
AVM Switch TB Interface Source Code
VMM Ethernet sample
`ifndef GUARD_INTERFACE
`define GUARD_INTERFACE
Verilog
Verification
//////////////////////////////////////////
Verilog Switch TB // Interface declaration for the memory///
Basic Constructs //////////////////////////////////////////

interface mem_interface(input bit clock);
OpenVera     parameter setup_time = 5ns;
Constructs     parameter hold_time = 3ns;
Switch TB
    wire [7:0] mem_data;
RVM Switch TB     wire [1:0] mem_add;
RVM Ethernet sample     wire       mem_en;
    wire       mem_rd_wr;
    
    clocking cb@(posedge clock);
Specman E        default input #setup_time output #hold_time;
Interview Questions        output     mem_data;
       output      mem_add;
       output mem_en;
       output mem_rd_wr;
    endclocking:cb
    
    modport MEM(clocking cb,input clock);

endinterface :mem_interface

////////////////////////////////////////////

http://testbench.in/CM_04_PHASE_1_TOP.html[9/26/2012 2:31:56 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

// Interface for the input side of switch.//


// Reset signal is also passed hear.      //
////////////////////////////////////////////
interface input_interface(input bit clock);

    parameter setup_time = 5ns;
    parameter hold_time = 3ns;

    wire           data_status;
    wire     [7:0] data_in;
    reg           reset; 

    clocking cb@(posedge clock);
       default input #setup_time output #hold_time;
       output    data_status;
       output    data_in;
    endclocking:cb
    
    modport IP(clocking cb,output reset,input clock);
  
endinterface:input_interface

/////////////////////////////////////////////////
// Interface for the output side of the switch.//
// output_interface is for only one output port//
/////////////////////////////////////////////////

interface output_interface(input bit clock);

    parameter setup_time = 5ns;
    parameter hold_time = 3ns;

    wire    [7:0] data_out;
    wire    ready;
    wire    read;
    
    clocking cb@(posedge clock);
      default input #setup_time output #hold_time;
      input     data_out;
      input     ready;
      output    read;
    endclocking:cb
    
    modport OP(clocking cb,input clock);

endinterface:output_interface

//////////////////////////////////////////////////

`endif 

Top Module

The modules that are included in the source text but are not instantiated are called
top modules. This module is the highest scope of modules. Generally this module is
named as "top" and referenced as "top module".  Module name can be anything.
This top-level module will contain the design portion of the simulation.

Do the following in the top module:

1) The first step is to import the ovm packages

 `include "ovm.svh"
 import ovm_pkg::*;

2)Generate the clock signal.

bit Clock;

http://testbench.in/CM_04_PHASE_1_TOP.html[9/26/2012 2:31:56 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

initial
  begin
      #20;
      forever #10 Clock = ~Clock;
  end

2)Do the instances of memory interface.

mem_interface mem_intf(Clock);

3)Do the instances of input interface.

input_interface input_intf(Clock);

4)There are 4 output ports. So do 4 instances of output_interface.

output_interface output_intf[4](Clock);

5) Connect all the interfaces and DUT.  The design which we have taken is in
verilog.  So Verilog DUT instance is connected signal by signal.

switch DUT    (.clk(Clock),
               .reset(input_intf.reset),
               .data_status(input_intf.data_status),
               .data(input_intf.data_in),
               .port0(output_intf[0].data_out),
               .port1(output_intf[1].data_out),
               .port2(output_intf[2].data_out),
               .port3(output_intf[3].data_out),
               .ready_0(output_intf[0].ready),
               .ready_1(output_intf[1].ready),
               .ready_2(output_intf[2].ready),
               .ready_3(output_intf[3].ready),
               .read_0(output_intf[0].read),
               .read_1(output_intf[1].read),
               .read_2(output_intf[2].read),
               .read_3(output_intf[3].read),
               .mem_en(mem_intf.mem_en),
               .mem_rd_wr(mem_intf.mem_rd_wr),
               .mem_add(mem_intf.mem_add),
               .mem_data(mem_intf.mem_data));

Top module Scource Code

`ifndef GUARD_TOP
`define GUARD_TOP
/////////////////////////////////////////////////////
// Importing OVM Packages                          //
/////////////////////////////////////////////////////

 `include "ovm.svh"
 import ovm_pkg::*;

 typedef class Configuration;

module top();

/////////////////////////////////////////////////////
// Clock Declaration and Generation                //
/////////////////////////////////////////////////////
    bit Clock;
    
    initial
      begin
          #20;
          forever #10 Clock = ~Clock;
      end
/////////////////////////////////////////////////////
//  Memory interface instance                      //
/////////////////////////////////////////////////////

    mem_interface mem_intf(Clock);

http://testbench.in/CM_04_PHASE_1_TOP.html[9/26/2012 2:31:56 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

/////////////////////////////////////////////////////
//  Input interface instance                       //
/////////////////////////////////////////////////////

    input_interface input_intf(Clock);

/////////////////////////////////////////////////////
//  output interface instance                      //
/////////////////////////////////////////////////////

    output_interface output_intf[4](Clock);

/////////////////////////////////////////////////////
//  DUT instance and signal connection             //
/////////////////////////////////////////////////////

switch DUT    (.clk(Clock),
               .reset(input_intf.reset),
               .data_status(input_intf.data_status),
               .data(input_intf.data_in),
               .port0(output_intf[0].data_out),
               .port1(output_intf[1].data_out),
               .port2(output_intf[2].data_out),
               .port3(output_intf[3].data_out),
               .ready_0(output_intf[0].ready),
               .ready_1(output_intf[1].ready),
               .ready_2(output_intf[2].ready),
               .ready_3(output_intf[3].ready),
               .read_0(output_intf[0].read),
               .read_1(output_intf[1].read),
               .read_2(output_intf[2].read),
               .read_3(output_intf[3].read),
               .mem_en(mem_intf.mem_en),
               .mem_rd_wr(mem_intf.mem_rd_wr),
               .mem_add(mem_intf.mem_add),
               .mem_data(mem_intf.mem_data));

endmodule : top

`endif

Download the files:

ovm_switch_1.tar
Browse the code in ovm_switch_1.tar

Command to compile

vcs -sverilog +incdir+$OVM_HOME/src $OVM_HOME/src/ovm_pkg.sv  +incdir+. rtl.sv


interface.sv top.sv
qverilog +incdir+$OVM_HOME/src $OVM_HOME/src/ovm_pkg.sv  +incdir+. rtl.sv
interface.sv top.sv  

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CM_04_PHASE_1_TOP.html[9/26/2012 2:31:56 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PHASE 2 CONFIGURATION Index


Introduction
SystemVerilog Specification
Verification In this phase we will implement the configuration class. All the requirements of the Verification Plan
testbench configurations will be declared inside this class. Virtual interfaces required Phase 1 Top
Constructs by verification components driver and receiver for connecting to DUT are declared in Phase 2 Configuration
Interface this class. We will also declare 4 variables which will hold the port address of the Phase 3 Environment N
DUT. Testcase
OOPS Phase 4 Packet
Randomization ovm_object does not have the simulation phases and can be used in get_config_object Phase 5 Sequencer N
and set_config_object method. So we will implement the configuration class by Sequence
Functional Coverage Phase 6 Driver
extending ovm_object.
Assertion Phase 7 Receiver
Phase 8 Scoreboard
DPI
Configuration
UVM Tutorial Report a Bug or Comment
1) Define configuration class by extending ovm_object on This section - Your
VMM Tutorial
input is what keeps
OVM Tutorial `ifndef GUARD_CONFIGURATION Testbench.in improving
`define GUARD_CONFIGURATION with time!
Easy Labs : SV
Easy Labs : UVM class Configuration extends ovm_object;
Easy Labs : OVM
endclass : Configuration
Easy Labs : VMM
AVM Switch TB `endif
VMM Ethernet sample 2) Declare All the interfaces which are required in this verification environment.

    virtual input_interface.IP   input_intf;
Verilog     virtual mem_interface.MEM  mem_intf;
Verification     virtual output_interface.OP output_intf[4];
Verilog Switch TB 3) Declare 4 variables which holds the device port address.
Basic Constructs
    bit [7:0] device0_add ;
    bit [7:0] device1_add ;
    bit [7:0] device2_add ;
OpenVera     bit [7:0] device3_add ;
Constructs
Switch TB 4) ovm_object required to define the ovm_object::creat() method.
   ovm_object::create method allocates a new object of the same type as this object
RVM Switch TB and returns it via a base ovm_object handle.
RVM Ethernet sample
   In create method, we have to construct a new object of configuration class and
update all the important fields and return it.
Specman E        virtual function ovm_object create(string name="");
Interview Questions         Configuration t = new();

        t.device0_add = this.device0_add;
        t.device1_add = this.device1_add;
        t.device2_add = this.device2_add;
        t.device3_add = this.device3_add;
        t.input_intf  =   this.input_intf;
        t.mem_intf    =   this.mem_intf;
        t.output_intf =   this.output_intf;

        return t;

http://testbench.in/CM_05_PHASE_2_CONFIGURATION.html[9/26/2012 2:32:03 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

    endfunction : create

Configuration class source code


`ifndef GUARD_CONFIGURATION
`define GUARD_CONFIGURATION

class Configuration extends ovm_object;

    virtual input_interface.IP   input_intf;
    virtual mem_interface.MEM  mem_intf;
    virtual output_interface.OP output_intf[4];

    bit [7:0] device0_add ;
    bit [7:0] device1_add ;
    bit [7:0] device2_add ;
    bit [7:0] device3_add ;

    virtual function ovm_object create(string name="");
        Configuration t = new();

        t.device0_add = this.device0_add;
        t.device1_add = this.device1_add;
        t.device2_add = this.device2_add;
        t.device3_add = this.device3_add;
        t.input_intf  =   this.input_intf;
        t.mem_intf    =   this.mem_intf;
        t.output_intf =   this.output_intf;

        return t;
    endfunction : create

endclass : Configuration
`endif

Updates To Top Module

In top module we will create an object of the above defined configuration class and
update the interfaces so that all the verification components can access to physical
interfaces in top module using configuration class object.

1) Declare a Configuration class object

    Configuration cfg;

2) Construct the configuration object and update the interfaces.

initial begin
    cfg = new();
    cfg.input_intf = input_intf;
    cfg.mem_intf = mem_intf;
    cfg.output_intf = output_intf;

3) In top module , we have to call the run_test() method.  

    run_test();

Top module updates

 typedef class Configuration;

module top();
/////////////////////////////////////////////////////
// Clock Declaration and Generation                //
/////////////////////////////////////////////////////
    bit Clock;
    
    initial
      begin

http://testbench.in/CM_05_PHASE_2_CONFIGURATION.html[9/26/2012 2:32:03 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

          #20;
          forever #10 Clock = ~Clock;
      end
/////////////////////////////////////////////////////
//  Memory interface instance                      //
/////////////////////////////////////////////////////
    mem_interface mem_intf(Clock);
/////////////////////////////////////////////////////
//  Input interface instance                       //
/////////////////////////////////////////////////////
    input_interface input_intf(Clock);
/////////////////////////////////////////////////////
//  output interface instance                      //
/////////////////////////////////////////////////////
    output_interface output_intf[4](Clock);

/////////////////////////////////////////////////////
// Creat Configuration and Strart the run_test//
/////////////////////////////////////////////////////

    Configuration cfg;

initial begin
    cfg = new();
    cfg.input_intf = input_intf;
    cfg.mem_intf = mem_intf;
    cfg.output_intf = output_intf;
  
    run_test();
end

/////////////////////////////////////////////////////
//  DUT instance and signal connection             //
/////////////////////////////////////////////////////
switch DUT    (.clk(Clock),
               .reset(input_intf.reset),
               .data_status(input_intf.data_status),
               .data(input_intf.data_in),
               .port0(output_intf[0].data_out),
               .port1(output_intf[1].data_out),
               .port2(output_intf[2].data_out),
               .port3(output_intf[3].data_out),
               .ready_0(output_intf[0].ready),
               .ready_1(output_intf[1].ready),
               .ready_2(output_intf[2].ready),
               .ready_3(output_intf[3].ready),
               .read_0(output_intf[0].read),
               .read_1(output_intf[1].read),
               .read_2(output_intf[2].read),
               .read_3(output_intf[3].read),
               .mem_en(mem_intf.mem_en),
               .mem_rd_wr(mem_intf.mem_rd_wr),
               .mem_add(mem_intf.mem_add),
               .mem_data(mem_intf.mem_data));
endmodule : top
`endif

Download the source code

ovm_switch_2.tar
Browse the code in ovm_switch_2.tar

Command to compile

vcs -sverilog +incdir+$OVM_HOME/src $OVM_HOME/src/ovm_pkg.sv  +incdir+. rtl.sv


interface.sv top.sv
qverilog +incdir+$OVM_HOME/src $OVM_HOME/src/ovm_pkg.sv  +incdir+. rtl.sv
interface.sv top.sv  

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/CM_05_PHASE_2_CONFIGURATION.html[9/26/2012 2:32:03 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CM_05_PHASE_2_CONFIGURATION.html[9/26/2012 2:32:03 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PHASE 3 ENVIRONMENT N TESTCASE Index


Introduction
SystemVerilog Specification
Verification In the phase we will implement the skeleton for environment class. Verification Plan
We will declare virtual interfaces and Extend Required Environment class virtual Phase 1 Top
Constructs methods. Phase 2 Configuration
Interface We will also implement a simple testcase and run the simulation. Phase 3 Environment N
Testcase
OOPS Phase 4 Packet
Randomization Environment class is used to implement verification environments in OVM. It is Phase 5 Sequencer N
extension on ovm_env class.  The testbench simulation needs some systematic flow Sequence
Functional Coverage Phase 6 Driver
like building the components, connection the components, starting the components
Assertion etc. ovm_env base class has methods formalize the simulation steps. All methods are Phase 7 Receiver
declared as virtual methods. Phase 8 Scoreboard
DPI
UVM Tutorial Report a Bug or Comment
on This section - Your
VMM Tutorial
input is what keeps
OVM Tutorial Testbench.in improving
with time!
Easy Labs : SV
Easy Labs : UVM
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

Verilog
Verification
Verilog Switch TB
Basic Constructs We will not implement all the ovm_env virtual methods in this phase but will we print
messages from these methods which are required for this example to understand the
simulation execution.
OpenVera
Testcase contains the instance of the environment class. This testcase Creates a
Constructs Environment object and defines the required test specific functionality.
Switch TB
Verification environment contains the declarations of the virtual interfaces. These
RVM Switch TB
virtual interfaces are pointed to the physical interfaces which are declared in the top
RVM Ethernet sample module. These virtual interfaces are made to point to physical interface in the
testcase.

Specman E
Environment
Interview Questions
1) Extend ovm_env class to define Environment class.

    `ifndef GUARD_ENV
    `define GUARD_ENV
    
    class Environment extends ovm_env;
    
    endclass : Environment
    
    `endif 

http://testbench.in/CM_06_PHASE_3_ENVIRONMENT_N_TESTCASE.html[9/26/2012 2:32:13 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

2)  Declare the utility macro. This utility macro provides the implementation of
create() and get_type_name() methods.

    `ovm_component_utils(Environment)

3) Define the constructor. In the constructor, call the super methods and pass the
parent object. Parent is the object in which environment is instantiated.

    function new(string name , ovm_component parent = null);


        super.new(name, parent);
    endfunction: new

4) Define build method. In build method, just print messages and super.build() must
be called. This method is automatically called.
Build is the first phase in simulation. This phase is used to construct the child
components of the current class.

    function void build();
        super.build();
      
        ovm_report_info(get_full_name(),"START of build ",OVM_LOW);
      
        ovm_report_info(get_full_name(),"END of build ",OVM_LOW);
      
    endfunction

5) Define connect method. In connect method, just print messages and


super.connect() must be called.
This method is called automatically after the build() method is called. This method is
used for connecting port and exports.

    function void connect();
        super.connect();
        ovm_report_info(get_full_name(),"START of connect ",OVM_LOW);
    
        ovm_report_info(get_full_name(),"END of connect ",OVM_LOW);
    endfunction

Environment class Source Code


`ifndef GUARD_ENV
`define GUARD_ENV

class Environment extends ovm_env;

    `ovm_component_utils(Environment)

    function new(string name , ovm_component parent = null);


        super.new(name, parent);
    endfunction: new

    function void build();
        super.build();
      
        ovm_report_info(get_full_name(),"START of build ",OVM_LOW);
      
        ovm_report_info(get_full_name(),"END of build ",OVM_LOW);
      
    endfunction
    
    function void connect();
        super.connect();
        ovm_report_info(get_full_name(),"START of connect ",OVM_LOW);
    
        ovm_report_info(get_full_name(),"END of connect ",OVM_LOW);
    endfunction

endclass : Environment

http://testbench.in/CM_06_PHASE_3_ENVIRONMENT_N_TESTCASE.html[9/26/2012 2:32:13 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

`endif 

Testcase

Now we will implement testcase. In OVM, testcases are implemented by extending


ovm_test. Using ovm_test , provides the ability to select which test to execute using
the OVM_TESTNAME command line option or argument to the ovm_root::run_test task.
We will use OVM_TESTNAME command line argument.

1) Define a testcase by extending ovm_test class.

   class test1 extends ovm_test;

   endclass

2)  Declare the utility macro.

    `ovm_component_utils(test1)

3) Take the instance of Environemtn.

     Environment t_env ;

4) Define the constructor method.


   In this method, construct the environment class object and dont forget to pass the
parent argument.

    function new (string name="test1", ovm_component parent=null);
        super.new (name, parent);
        t_env = new("t_env",this);
    endfunction : new 

5) Define run() method.


   run() method is the only task which is time consuming. After completing the
start_of_simulation() phase , this method is called.
   To terminate this task, we will use global_stop_request().

   As we dont have anything now to write in this testcase, just call the
global_stop_request() after some delay.

    task run ();
     #1000;
     global_stop_request();
    endtask : run

With this, for the first time, we can do the simulation.

Testcase Source code


class test1 extends ovm_test;

    `ovm_component_utils(test1)

     Environment t_env ;

    function new (string name="test1", ovm_component parent=null);
        super.new (name, parent);
        t_env = new("t_env",this);
    endfunction : new 

    task run ();
     #1000;
     global_stop_request();
    endtask : run

endclass : test1

Download the Source Code

ovm_switch_3.tar
Browse the code in ovm_switch_3.tar

http://testbench.in/CM_06_PHASE_3_ENVIRONMENT_N_TESTCASE.html[9/26/2012 2:32:13 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

Command to run the simulation

 vcs -sverilog +incdir+$OVM_HOME/src $OVM_HOME/src/ovm_pkg.sv  +incdir+. rtl.sv


interface.sv top.sv -R +OVM_TESTNAME=test1
qverilog +incdir+$OVM_HOME/src $OVM_HOME/src/ovm_pkg.sv  +incdir+. rtl.sv
interface.sv top.sv -R +OVM_TESTNAME=test1

Log report after simulation

OVM_INFO @ 0 [RNTST] Running test test1...


OVM_INFO @ 0: ovm_test_top.t_env [ovm_test_top.t_env] START of build
OVM_INFO @ 0: ovm_test_top.t_env [ovm_test_top.t_env] END of build
OVM_INFO @ 0: ovm_test_top.t_env [ovm_test_top.t_env] START of connect
OVM_INFO @ 0: ovm_test_top.t_env [ovm_test_top.t_env] END of connect

--- OVM Report Summary ---

** Report counts by severity


OVM_INFO :    5
OVM_WARNING :    0
OVM_ERROR :    0
OVM_FATAL :    0
** Report counts by id
[RNTST               ]     1
[ovm_test_top.t_env  ]     4

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CM_06_PHASE_3_ENVIRONMENT_N_TESTCASE.html[9/26/2012 2:32:13 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PHASE 4 PACKET Index


Introduction
SystemVerilog Specification
Verification In this Phase, we will develop Transaction as per the verification plan. We will define Verification Plan
required methods and constraints. We will also develop a small logic to test our Phase 1 Top
Constructs implementation of this class. Phase 2 Configuration
Interface Phase 3 Environment N
Testcase
OOPS Phase 4 Packet
Packet
Randomization Phase 5 Sequencer N
We will write the packet class in Packet.sv file. Packet class variables and constraints Sequence
Functional Coverage Phase 6 Driver
have been derived from stimulus generation plan.
Assertion Phase 7 Receiver
One way to model Packet is by extending ovm_sequence_item. ovm_sequence_item Phase 8 Scoreboard
DPI
provides basic functionality for sequence items and sequences to operate in a
UVM Tutorial sequence mechanism. Packet class should be able to generate all possible packet Report a Bug or Comment
types randomly. To define copy, compare, record, print and sprint methods, we will on This section - Your
VMM Tutorial
use OVM field macros. For packing and Unpacking, we will define the logic and not use input is what keeps
OVM Tutorial the field  macros. Testbench.in improving
with time!
Easy Labs : SV
Easy Labs : UVM Revisit Stimulus Generation Plan
Easy Labs : OVM 1) Packet DA: Generate packet DA with the configured address.
2) Payload length: generate payload length ranging from 2 to 255.
Easy Labs : VMM 3) Generate good and bad FCS.
AVM Switch TB
VMM Ethernet sample
1) Define enumerated type data for fcs.

Verilog    typedef enum { GOOD_FCS, BAD_FCS } fcs_kind_t;
Verification
2) Define transaction by extending ovm_sequence_item.
Verilog Switch TB
Basic Constructs    class Packet extends ovm_sequence_item;

   endclass : Packet
OpenVera 3) Define all the fields as rand variables.
Constructs
Switch TB     rand fcs_kind_t     fcs_kind;
    
RVM Switch TB     rand bit [7:0] length;
RVM Ethernet sample     rand bit [7:0] da;
    rand bit [7:0] sa;
    rand bit [7:0] data[];
    rand byte fcs;
Specman E     
Interview Questions
4) Define constraints to constraint payload size of data.

    constraint payload_size_c { data.size inside { [2 : 255]};}
    
    constraint length_c {  length == data.size; } 
                    

5) Define the constructor method.

    function new(string name = "");

http://testbench.in/CM_07_PHASE_4_PACKET.html[9/26/2012 2:32:21 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

         super.new(name);
    endfunction : new

6) In post_randomize() , define the fcs value based on fcs_kind.

    function void post_randomize();
         if(fcs_kind == GOOD_FCS)
             fcs = 8'b0;
         else
            fcs = 8'b1;
         fcs = cal_fcs();
    endfunction : post_randomize

7) Define cal_fcs() method which computes the fcs value.

    virtual function byte cal_fcs;
         integer i;
         byte result ;
         result = 0;
         result = result ^ da;
         result = result ^ sa;
         result = result ^ length;
         for (i = 0;i< data.size;i++)
         result = result ^ data[i];
         result = fcs ^ result;
         return result;
    endfunction : cal_fcs

8) Using ovm_field_* macros, define transaction required method.


   We will define packing and unpacking methods manually, so use OVM_NOPACK for
excluding atomic creation of packing and un packing method.

    `ovm_object_utils_begin(Packet)
       `ovm_field_int(da, OVM_ALL_ON|OVM_NOPACK)
       `ovm_field_int(sa, OVM_ALL_ON|OVM_NOPACK)
       `ovm_field_int(length, OVM_ALL_ON|OVM_NOPACK)
       `ovm_field_array_int(data, OVM_ALL_ON|OVM_NOPACK)
       `ovm_field_int(fcs, OVM_ALL_ON|OVM_NOPACK)
    `ovm_object_utils_end

9) Define do_pack() method which does the packing operation.

    function void do_pack(ovm_packer packer);
        super.do_pack(packer);
        packer.pack_field_int(da,$bits(da));
        packer.pack_field_int(sa,$bits(sa));
        packer.pack_field_int(length,$bits(length));
        foreach(data[i])
          packer.pack_field_int(data[i],8);
        packer.pack_field_int(fcs,$bits(fcs));
    endfunction : do_pack

10) Define do_unpack() method which does the unpacking operation.

    function void do_unpack(ovm_packer packer);
        int sz;
        super.do_pack(packer);
    
        da = packer.unpack_field_int($bits(da));
        sa = packer.unpack_field_int($bits(sa));
        length = packer.unpack_field_int($bits(length));
        
        data.delete();
        data = new[length];
        foreach(data[i])
          data[i] = packer.unpack_field_int(8);
        fcs = packer.unpack_field_int($bits(fcs));

http://testbench.in/CM_07_PHASE_4_PACKET.html[9/26/2012 2:32:21 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

    endfunction : do_unpack

Packet class source code

`ifndef GUARD_PACKET
`define GUARD_PACKET

 `include "ovm.svh"
 import ovm_pkg::*;

//Define the enumerated types for packet types


typedef enum { GOOD_FCS, BAD_FCS } fcs_kind_t;

class Packet extends ovm_sequence_item;

    rand fcs_kind_t     fcs_kind;
    
    rand bit [7:0] length;
    rand bit [7:0] da;
    rand bit [7:0] sa;
    rand bit [7:0] data[];
    rand byte fcs;
    
    constraint payload_size_c { data.size inside { [1 : 6]};}
    
    constraint length_c {  length == data.size; } 
                    
    function new(string name = "");
         super.new(name);
    endfunction : new
    
    function void post_randomize();
         if(fcs_kind == GOOD_FCS)
             fcs = 8'b0;
         else
            fcs = 8'b1;
         fcs = cal_fcs();
    endfunction : post_randomize
    
    ///// method to calculate the fcs /////
    virtual function byte cal_fcs;
         integer i;
         byte result ;
         result = 0;
         result = result ^ da;
         result = result ^ sa;
         result = result ^ length;
         for (i = 0;i< data.size;i++)
         result = result ^ data[i];
         result = fcs ^ result;
         return result;
    endfunction : cal_fcs
    
    `ovm_object_utils_begin(Packet)
       `ovm_field_int(da, OVM_ALL_ON|OVM_NOPACK)
       `ovm_field_int(sa, OVM_ALL_ON|OVM_NOPACK)
       `ovm_field_int(length, OVM_ALL_ON|OVM_NOPACK)
       `ovm_field_array_int(data, OVM_ALL_ON|OVM_NOPACK)
       `ovm_field_int(fcs, OVM_ALL_ON|OVM_NOPACK)
    `ovm_object_utils_end
    
    function void do_pack(ovm_packer packer);
        super.do_pack(packer);
        packer.pack_field_int(da,$bits(da));
        packer.pack_field_int(sa,$bits(sa));
        packer.pack_field_int(length,$bits(length));
        foreach(data[i])
          packer.pack_field_int(data[i],8);
        packer.pack_field_int(fcs,$bits(fcs));
    endfunction : do_pack
    
    function void do_unpack(ovm_packer packer);
        int sz;
        super.do_pack(packer);

http://testbench.in/CM_07_PHASE_4_PACKET.html[9/26/2012 2:32:21 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

    
        da = packer.unpack_field_int($bits(da));
        sa = packer.unpack_field_int($bits(sa));
        length = packer.unpack_field_int($bits(length));
        
        data.delete();
        data = new[length];
        foreach(data[i])
          data[i] = packer.unpack_field_int(8);
        fcs = packer.unpack_field_int($bits(fcs));
    endfunction : do_unpack

endclass : Packet

Test The Transaction Implementation

Now we will write a small logic to test our packet implantation. This module is not
used in normal verification.

Define a module and take the instance of packet class. Randomize the packet and call
the print method to analyze the generation. Then pack the packet in to bytes and
then unpack bytes and then call compare method to check all the method
implementation.

1) Declare Packet objects and dynamic arrays.

    Packet pkt1 = new("pkt1");


    Packet pkt2 = new("pkt2");
    byte unsigned pkdbytes[];

2) In a initial block, randomize the packet, pack the packet in to pkdbytes and then
unpack it and compare the packets.

       if(pkt1.randomize)
       begin
          $display(" Randomization Sucessesfull.");
          pkt1.print();
          ovm_default_packer.use_metadata = 1;    
          void'(pkt1.pack_bytes(pkdbytes));
          $display("Size of pkd bits %d",pkdbytes.size());
          pkt2.unpack_bytes(pkdbytes);
          pkt2.print();
          if(pkt2.compare(pkt1))
              $display(" Packing,Unpacking and compare worked");
          else
              $display(" *** Something went wrong in Packing or Unpacking or compare ***
\n \n");

Logic to test the transaction implementation


module test;

    Packet pkt1 = new("pkt1");


    Packet pkt2 = new("pkt2");
    byte unsigned pkdbytes[];

    initial
    repeat(10)
       if(pkt1.randomize)
       begin
          $display(" Randomization Successesfull.");
          pkt1.print();
          ovm_default_packer.use_metadata = 1;    
          void'(pkt1.pack_bytes(pkdbytes));
          $display("Size of pkd bits %d",pkdbytes.size());
          pkt2.unpack_bytes(pkdbytes);
          pkt2.print();
          if(pkt2.compare(pkt1))
              $display(" Packing,Unpacking and compare worked");
          else
              $display(" *** Something went wrong in Packing or Unpacking or compare ***

http://testbench.in/CM_07_PHASE_4_PACKET.html[9/26/2012 2:32:21 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

\n \n");
       end
       else
       $display(" *** Randomization Failed ***");
    
endmodule

Download the Source Code

ovm_switch_4.tar
Browse the code in ovm_switch_4.tar

Command to run the simulation

vcs -sverilog +incdir+$OVM_HOME/src $OVM_HOME/src/ovm_pkg.sv  -R Packet.sv


qverilog +incdir+$OVM_HOME/src $OVM_HOME/src/ovm_pkg.sv  -R Packet.sv

Log report after simulation

 Randomization Sucessesfull.
----------------------------------------------------------------------
Name                     Type                Size                Value
----------------------------------------------------------------------
pkt1                     Packet              -                  pkt1@3
--da                     integral            8                    'ha5
--sa                     integral            8                    'ha1
--length                 integral            8                     'h6
--data                   da(integral)        6                       -
----[0]                  integral            8                    'h58
----[1]                  integral            8                    'h60
----[2]                  integral            8                    'h34
----[3]                  integral            8                    'hdd
----[4]                  integral            8                     'h9
----[5]                  integral            8                    'haf
--fcs                    integral            8                    'h75
----------------------------------------------------------------------
Size of pkd bits          10
----------------------------------------------------------------------
Name                     Type                Size                Value
----------------------------------------------------------------------
pkt2                     Packet              -                  pkt2@5
--da                     integral            8                    'ha5
--sa                     integral            8                    'ha1
--length                 integral            8                     'h6
--data                   da(integral)        6                       -
----[0]                  integral            8                    'h58
----[1]                  integral            8                    'h60
----[2]                  integral            8                    'h34
----[3]                  integral            8                    'hdd
----[4]                  integral            8                     'h9
----[5]                  integral            8                    'haf
--fcs                    integral            8                    'h75
----------------------------------------------------------------------
 Packing,Unpacking and compare worked

....
....
....
....

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/CM_07_PHASE_4_PACKET.html[9/26/2012 2:32:21 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CM_07_PHASE_4_PACKET.html[9/26/2012 2:32:21 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PHASE 5 SEQUENCER N SEQUENCE Index


Introduction
SystemVerilog In this phase we will develop Sequence and Sequencer. Specification
Verification Verification Plan
A sequence is series of transaction and sequencer is used to for controlling the flow of Phase 1 Top
Constructs transaction generation. Phase 2 Configuration
Interface A sequence of transaction (which we already developed in previous phase) is defined Phase 3 Environment N
by extending ovm_sequence class. ovm_sequencer does the generation of this Testcase
OOPS Phase 4 Packet
sequence of transaction, ovm_driver takes the transaction from Sequencer and
Randomization processes the packet/ drives to other component or to DUT. Phase 5 Sequencer N
Sequence
Functional Coverage Phase 6 Driver
Assertion Phase 7 Receiver
Phase 8 Scoreboard
DPI
UVM Tutorial Report a Bug or Comment
on This section - Your
VMM Tutorial
input is what keeps
OVM Tutorial Testbench.in improving
with time!
Easy Labs : SV
Easy Labs : UVM
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample Sequencer

A Sequencer is defined by extending ovm_sequencer. ovm_sequencer has a port


Verilog seq_item_export which is used to connect to ovm_driver for transaction transfer.
Verification
Verilog Switch TB 1) Define a sequencer by extending ovm_sequence.
Basic Constructs `ifndef GUARD_SEQUENCER
`define GUARD_SEQUENCER

OpenVera class Sequencer extends ovm_sequencer #(Packet);


Constructs
endclass : Sequencer
Switch TB
RVM Switch TB `endif
RVM Ethernet sample 2) We need Device port address, which are in configuration class. So declare a
configuration class object.

Specman E      Configuration cfg;


Interview Questions 3) Declare Sequencer utility macros.    

    `ovm_sequencer_utils(Sequencer)

4) Define the constructor.  

    function new (string name, ovm_component parent);
        super.new(name, parent);
        `ovm_update_sequence_lib_and_item(Packet)
    endfunction : new

http://testbench.in/CM_08_PHASE_5_SEQUENCER_N_SEQUENCE.html[9/26/2012 2:32:29 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

5) In   end_of_elaboration() method, using get_config_object(), get the configuration


object which will be passed from testcase.
   get_config_object() returns object of type ovm_object, so using a temporary
ovm_object and cast it to configuration object.

    function void end_of_elaboration();
        ovm_object tmp;
        assert(get_config_object("Configuration",tmp));
        $cast(cfg,tmp);
    endfunction

Sequencer source code

`ifndef GUARD_SEQUENCER
`define GUARD_SEQUENCER

class Sequencer extends ovm_sequencer #(Packet);

     Configuration cfg;


  
    `ovm_sequencer_utils(Sequencer)
  
    function new (string name, ovm_component parent);
        super.new(name, parent);
        `ovm_update_sequence_lib_and_item(Packet)
    endfunction : new
  
  
    function void end_of_elaboration();
        ovm_object tmp;
        assert(get_config_object("Configuration",tmp));
        $cast(cfg,tmp);
    endfunction

endclass : Sequencer

`endif
Sequence

A sequence is defined by extending ovm_sequence class. This sequence of transactions


should be defined in budy() method of ovm_sequence class. OVM has macros and
methods to define the transaction types. We will use macros in this example.

You can define as many sequences as you want. We will define 2 sequences.

1) Define sequence by extending

class Seq_device0_and_device1 extends ovm_sequence #(Packet);

endclass: Seq_device0_and_device1

2) Define constructor method.

     function new(string name = "Seq_do");
         super.new(name);
     endfunction : new

3) Declare utilities macro.  With this macro, this sequence is tied to Sequencer.

     `ovm_sequence_utils(Seq_device0_and_device1, Sequencer)    

4) The algorithm for the transaction should be defined in body() method of the
sequence. In this sequence we will define the algorithm such that alternate
transactions for device port 0 and 1 are generated.
  
   The device addresses are available in configuration object which is in sequencer.

http://testbench.in/CM_08_PHASE_5_SEQUENCER_N_SEQUENCE.html[9/26/2012 2:32:29 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

Every sequence has a handle to its sequence through p_sequencer. Using p_sequencer
handle, access the device address.

     virtual task body();
        forever begin
         `ovm_do_with(item, {da == p_sequencer.cfg.device0_add;} ); 
         `ovm_do_with(item, {da == p_sequencer.cfg.device1_add;} ); 
        end
     endtask : body
  

Sequence Source Code

class Seq_device0_and_device1 extends ovm_sequence #(Packet);

     function new(string name = "Seq_device0_and_device1");
         super.new(name);
     endfunction : new
 
     Packet item;
 
     `ovm_sequence_utils(Seq_device0_and_device1, Sequencer)    

     virtual task body();
        forever begin
         `ovm_do_with(item, {da == p_sequencer.cfg.device0_add;} ); 
         `ovm_do_with(item, {da == p_sequencer.cfg.device1_add;} ); 
        end
     endtask : body
  
endclass :Seq_device0_and_device1

One more Sequence

class Seq_constant_length extends ovm_sequence #(Packet);

     function new(string name = "Seq_constant_length");
         super.new(name);
     endfunction : new
 
     Packet item;
 
     `ovm_sequence_utils(Seq_constant_length, Sequencer)    

     virtual task body();
        forever begin
         `ovm_do_with(item, {length == 10;da == p_sequencer.cfg.device0_add;} ); 
        end
     endtask : body
  
endclass : Seq_constant_length

Download the Source Code

ovm_switch_5.tar
Browse the code in ovm_switch_5.tar

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/CM_08_PHASE_5_SEQUENCER_N_SEQUENCE.html[9/26/2012 2:32:29 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CM_08_PHASE_5_SEQUENCER_N_SEQUENCE.html[9/26/2012 2:32:29 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PHASE 6 DRIVER Index


Introduction
SystemVerilog Driver Specification
Verification Verification Plan
In this phase we will develop the driver. Driver is defined by extending ovm_driver. Phase 1 Top
Constructs Driver takes the transaction from the sequencer using seq_item_port. This transaction Phase 2 Configuration
Interface will be driven to DUT as per the interface specification. After driving the transaction Phase 3 Environment N
to DUT, it sends the transaction to scoreboard using ovm_analysis_port. Testcase
OOPS Phase 4 Packet
Randomization In driver class, we will also define task for resetting DUT and configuring the DUT. Phase 5 Sequencer N
After completing the driver class implementation, we will instantiate it in Sequence
Functional Coverage Phase 6 Driver
environment class and connect the sequencer to it. We will also update the test case
Assertion and run the simulation to check the implementation which we did till now. Phase 7 Receiver
Phase 8 Scoreboard
DPI
UVM Tutorial Report a Bug or Comment
on This section - Your
VMM Tutorial
input is what keeps
OVM Tutorial Testbench.in improving
with time!
Easy Labs : SV
Easy Labs : UVM
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

Verilog
Verification
Verilog Switch TB
Basic Constructs

1) Define the driver class by extending ovm_driver;


OpenVera
`ifndef GUARD_DRIVER
Constructs `define GUARD_DRIVER
Switch TB
class Driver extends ovm_driver #(Packet);
RVM Switch TB
RVM Ethernet sample endclass : Driver

2) Create a handle to configuration object. Using this object we can get DUT
interfaces and DUT port addresses.
Specman E
Interview Questions     Configuration cfg;

3) Declare input and memory interfaces

     virtual input_interface.IP   input_intf;


     virtual mem_interface.MEM  mem_intf;

4) Declare ovm_analysis_port which is used to send packets to scoreboard.

     ovm_analysis_port #(Packet) Drvr2Sb_port;

http://testbench.in/CM_09_PHASE_6_DRIVER.html[9/26/2012 2:32:38 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

5) Declare component utilities macro.

    `ovm_component_utils(Driver)  

6) Define the constructor method. Pass the parent object to super class.

   function new( string name = "" , ovm_component parent = null) ;


       super.new( name , parent );
   endfunction : new

7) In the build method and construct Drvr2Sb_port object.

   function void build();
       super.build();
       Drvr2Sb_port = new("Drvr2Sb_port", this);
   endfunction :  build

8) In the end_of_elaboration() method, get the configuration object using


get_config_object and update the virtual interfaces.

  function void end_of_elaboration();
      ovm_object tmp;
      super.end_of_elaboration();
      assert(get_config_object("Configuration",tmp));
      $cast(cfg,tmp);
      this.input_intf = cfg.input_intf;
      this.mem_intf = cfg.mem_intf;
  endfunction : end_of_elaboration

 
9) Define the reset_dut() method which will be used for resetting the DUT.

 virtual task reset_dut();
      ovm_report_info(get_full_name(),"Start of reset_dut() method ",OVM_LOW);
      mem_intf.mem_data      <= 0;
      mem_intf.mem_add       <= 0;
      mem_intf.mem_en        <= 0;
      mem_intf.mem_rd_wr     <= 0;
      input_intf.data_in     <= 0;
      input_intf.data_status <= 0;
      
      input_intf.reset       <= 1;
      repeat (4) @ input_intf.clock;
      input_intf.reset       <= 0;

      ovm_report_info(get_full_name(),"End of reset_dut() method ",OVM_LOW);


 endtask : reset_dut

10) Define the cfg_dut() method which does the configuration due port address.

 virtual task cfg_dut();
      ovm_report_info(get_full_name(),"Start of cfg_dut() method ",OVM_LOW);
      mem_intf.mem_en <= 1;
      @(posedge mem_intf.clock);
      mem_intf.mem_rd_wr <= 1;
      
      @(posedge mem_intf.clock);
      mem_intf.mem_add  <= 8'h0;
      mem_intf.mem_data <= cfg.device0_add;
      ovm_report_info(get_full_name(),
      $psprintf(" Port 0 Address %h ",cfg.device0_add),OVM_LOW);
      
      @(posedge mem_intf.clock);
      mem_intf.mem_add  <= 8'h1;
      mem_intf.mem_data <= cfg.device1_add;
      ovm_report_info(get_full_name(),
      $psprintf(" Port 1 Address %h ",cfg.device1_add),OVM_LOW);
      

http://testbench.in/CM_09_PHASE_6_DRIVER.html[9/26/2012 2:32:38 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

      @(posedge mem_intf.clock);
      mem_intf.mem_add  <= 8'h2;
      mem_intf.mem_data <= cfg.device2_add;
      ovm_report_info(get_full_name(),
      $psprintf(" Port 2 Address %h ",cfg.device2_add),OVM_LOW);
      
      @(posedge mem_intf.clock);
      mem_intf.mem_add  <= 8'h3;
      mem_intf.mem_data <= cfg.device3_add;
      ovm_report_info(get_full_name(),
      $psprintf(" Port 3 Address %h ",cfg.device3_add),OVM_LOW);
      
      @(posedge mem_intf.clock);
      mem_intf.mem_en    <=0;
      mem_intf.mem_rd_wr <= 0;
      mem_intf.mem_add   <= 0;
      mem_intf.mem_data  <= 0;

      ovm_report_info(get_full_name(),"End of cfg_dut() method ",OVM_LOW);


 endtask : cfg_dut

11) Define drive() method which will be used to drive the packet to DUT. In this
method pack the packet fields using the pack_bytes() method of the transaction and
drive the packed data to DUT interface.  

task drive(Packet pkt);
      byte unsigned  bytes[];
      int pkt_len;
      pkt_len = pkt.pack_bytes(bytes);
      ovm_report_info(get_full_name(),"Driving packet ...",OVM_LOW);

      foreach(bytes[i])
      begin
          @(posedge input_intf.clock);
          input_intf.data_status <= 1 ;
          input_intf.data_in <= bytes[i];
      end

      @(posedge input_intf.clock);
      input_intf.data_status <= 0 ;
      input_intf.data_in <= 0;
      repeat(2) @(posedge input_intf.clock);
endtask : drive

12) Now we will use the above 3 defined methods and update the run() method of
ovm_driver.
First call the reset_dut() method and then cfg_dut(). After completing the
configuration, in a forever loop get the transaction from seq_item_port and send it
DUT using drive() method and also to scoreboard using Drvr2SB_port .

 task run();
     Packet pkt;
     @(posedge input_intf.clock);
     reset_dut();
     cfg_dut();
     forever begin
         seq_item_port.get_next_item(pkt);
         Drvr2Sb_port.write(pkt);
         @(posedge input_intf.clock);
         drive(pkt);
         @(posedge input_intf.clock);
         seq_item_port.item_done();
    end
 endtask : run

Driver class source code

`ifndef GUARD_DRIVER
`define GUARD_DRIVER

class Driver extends ovm_driver #(Packet);

    Configuration cfg;

http://testbench.in/CM_09_PHASE_6_DRIVER.html[9/26/2012 2:32:38 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

  
    virtual input_interface.IP   input_intf;
    virtual mem_interface.MEM  mem_intf;
    
    ovm_analysis_port #(Packet) Drvr2Sb_port;

    `ovm_component_utils(Driver) 
  
    function new( string name = "" , ovm_component parent = null) ;
        super.new( name , parent );
    endfunction : new
  
    function void build();
        super.build();
        Drvr2Sb_port = new("Drvr2Sb", this);
    endfunction :  build
  
    function void end_of_elaboration();
        ovm_object tmp;
        super.end_of_elaboration();
        assert(get_config_object("Configuration",tmp));
        $cast(cfg,tmp);
        this.input_intf = cfg.input_intf;
        this.mem_intf = cfg.mem_intf;
    endfunction : end_of_elaboration

    task run();
        Packet pkt;
        @(posedge input_intf.clock);
        reset_dut();
        cfg_dut();
        forever begin
            seq_item_port.get_next_item(pkt);
            Drvr2Sb_port.write(pkt);
            @(posedge input_intf.clock);
            drive(pkt);
            @(posedge input_intf.clock);
            seq_item_port.item_done();
        end
    endtask : run
  
    virtual task reset_dut();
        ovm_report_info(get_full_name(),"Start of reset_dut() method ",OVM_LOW);
        mem_intf.mem_data      <= 0;
        mem_intf.mem_add       <= 0;
        mem_intf.mem_en        <= 0;
        mem_intf.mem_rd_wr     <= 0;
        input_intf.data_in     <= 0;
        input_intf.data_status <= 0;
        
        input_intf.reset       <= 1;
        repeat (4) @ input_intf.clock;
            input_intf.reset       <= 0;
  
        ovm_report_info(get_full_name(),"End of reset_dut() method ",OVM_LOW);
    endtask : reset_dut
  
    virtual task cfg_dut();
        ovm_report_info(get_full_name(),"Start of cfg_dut() method ",OVM_LOW);
        mem_intf.mem_en <= 1;
        @(posedge mem_intf.clock);
        mem_intf.mem_rd_wr <= 1;
        
        @(posedge mem_intf.clock);
        mem_intf.mem_add  <= 8'h0;
        mem_intf.mem_data <= cfg.device0_add;
        ovm_report_info(get_full_name(),
        $psprintf(" Port 0 Address %h ",cfg.device0_add),OVM_LOW);
        
        @(posedge mem_intf.clock);
        mem_intf.mem_add  <= 8'h1;
        mem_intf.mem_data <= cfg.device1_add;
        ovm_report_info(get_full_name(),
        $psprintf(" Port 1 Address %h ",cfg.device1_add),OVM_LOW);

http://testbench.in/CM_09_PHASE_6_DRIVER.html[9/26/2012 2:32:38 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

        
        @(posedge mem_intf.clock);
        mem_intf.mem_add  <= 8'h2;
        mem_intf.mem_data <= cfg.device2_add;
        ovm_report_info(get_full_name(),
        $psprintf(" Port 2 Address %h ",cfg.device2_add),OVM_LOW);
        
        @(posedge mem_intf.clock);
        mem_intf.mem_add  <= 8'h3;
        mem_intf.mem_data <= cfg.device3_add;
        ovm_report_info(get_full_name(),
        $psprintf(" Port 3 Address %h ",cfg.device3_add),OVM_LOW);
        
        @(posedge mem_intf.clock);
        mem_intf.mem_en    <=0;
        mem_intf.mem_rd_wr <= 0;
        mem_intf.mem_add   <= 0;
        mem_intf.mem_data  <= 0;
  
        ovm_report_info(get_full_name(),"End of cfg_dut() method ",OVM_LOW);
    endtask : cfg_dut
  
   task drive(Packet pkt);
        byte unsigned  bytes[];
        int pkt_len;
        pkt_len = pkt.pack_bytes(bytes);
        ovm_report_info(get_full_name(),"Driving packet ...",OVM_LOW);

        foreach(bytes[i])
        begin
            @(posedge input_intf.clock);
            input_intf.data_status <= 1 ;
            input_intf.data_in <= bytes[i];
        end
  
        @(posedge input_intf.clock);
        input_intf.data_status <= 0 ;
        input_intf.data_in <= 0;
        repeat(2) @(posedge input_intf.clock);
   endtask : drive

endclass : Driver

`endif

Environment Updates

We will take the instance of Sequencer and Driver and connect them in Environment
class.

1) Declare handles to Driver and Sequencer.

http://testbench.in/CM_09_PHASE_6_DRIVER.html[9/26/2012 2:32:38 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

     Sequencer Seqncr;


     Driver Drvr;

2) In build method, construct Seqncr and Drvr object using create() method.

        Drvr   = Driver::type_id::create("Drvr",this);
        Seqncr = Sequencer::type_id::create("Seqncr",this);

2) In connect() method connect the sequencer seq_item_port to drivers


seq_item_export.

     Drvr.seq_item_port.connect(Seqncr.seq_item_export);

Environment class code

`ifndef GUARD_ENV
`define GUARD_ENV

class Environment extends ovm_env;

    `ovm_component_utils(Environment)

     Sequencer Seqncr;


     Driver Drvr;

    function new(string name , ovm_component parent = null);


        super.new(name, parent);
    endfunction: new

    function void build();


        super.build();
        ovm_report_info(get_full_name(),"START of build ",OVM_LOW);

        Drvr   = Driver::type_id::create("Drvr",this);
        Seqncr = Sequencer::type_id::create("Seqncr",this);

        ovm_report_info(get_full_name(),"END of build ",OVM_LOW);


    endfunction
    
    function void connect();
        super.connect();
        ovm_report_info(get_full_name(),"START of connect ",OVM_LOW);

        Drvr.seq_item_port.connect(Seqncr.seq_item_export);

        ovm_report_info(get_full_name(),"END of connect ",OVM_LOW);


    endfunction

endclass : Environment

`endif

Testcase Updates

We will update the testcase and run the simulation.

1)In the build() method, update the configuration address in the configuration object
which in top module.

    function void build();
        super.build();

        cfg.device0_add = 0;
        cfg.device1_add = 1;
        cfg.device2_add = 2;
        cfg.device3_add = 3;

2) In the build() method itself, using set_config_object , configure the configuration


object with the one which is in top module.
   with this, the configuration object in Sequencer and Driver will be pointing to the
one which in top module.

        set_config_object("t_env.*","Configuration",cfg);

http://testbench.in/CM_09_PHASE_6_DRIVER.html[9/26/2012 2:32:38 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

3) In the build method, using set_config_string, configure the default_sequence of the


sequencer to use the sequence which we defined.

        set_config_string("*.Seqncr", "default_sequence", "Seq_device0_and_device1");

4) Set the sequencer count value to 2 .

        set_config_int("*.Seqncr", "count",2);

5) Update the run() method to print the Sequencer details.    

     t_env.Seqncr.print();

Testcase code

class test1 extends ovm_test;

    `ovm_component_utils(test1)

     Environment t_env ;

    function new (string name="test1", ovm_component parent=null);


        super.new (name, parent);
        t_env = new("t_env",this);
    endfunction : new

    function void build();
        super.build();

        cfg.device0_add = 0;
        cfg.device1_add = 1;
        cfg.device2_add = 2;
        cfg.device3_add = 3;
 
        set_config_object("t_env.*","Configuration",cfg);
        set_config_string("*.Seqncr", "default_sequence", "Seq_device0_and_device1");
        set_config_int("*.Seqncr", "count",2);

    endfunction

    task run ();

       t_env.Seqncr.print();

        #1000;
        global_stop_request();
    endtask : run

endclass : test1

Download the source code

ovm_switch_6.tar
Browse the code in ovm_switch_6.tar

Command to run the simulation

 vcs -sverilog +incdir+$OVM_HOME/src $OVM_HOME/src/ovm_pkg.sv +incdir+. rtl.sv


interface.sv top.sv -R +OVM_TESTNAME=test1
 qverilog +incdir+$OVM_HOME/src $OVM_HOME/src/ovm_pkg.sv +incdir+. rtl.sv
interface.sv top.sv -R +OVM_TESTNAME=test1

Log report after simulation

OVM_INFO @ 0 [RNTST] Running test test1...


OVM_INFO @ 0: ovm_test_top.t_env [ovm_test_top.t_env] START of build
OVM_INFO @ 0: ovm_test_top.t_env [ovm_test_top.t_env] END of build
OVM_INFO @ 0: ovm_test_top.t_env [ovm_test_top.t_env] START of connect
OVM_INFO @ 0: ovm_test_top.t_env [ovm_test_top.t_env] END of connect
----------------------------------------------------------------------
Name                     Type                Size                Value

http://testbench.in/CM_09_PHASE_6_DRIVER.html[9/26/2012 2:32:38 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

----------------------------------------------------------------------
Seqncr                   Sequencer           -               Seqncr@14
--rsp_export             ovm_analysis_export -           rsp_export@16
--seq_item_export        ovm_seq_item_pull_+ -      seq_item_export@40
--default_sequence       string              19    ovm_random_sequence
--count                  integral            32                     -1
--max_random_count       integral            32                   'd10
--sequences              array               5                       -
----[0]                  string              19    ovm_random_sequence
----[1]                  string              23   ovm_exhaustive_sequ+
----[2]                  string              19    ovm_simple_sequence
----[3]                  string              23   Seq_device0_and_dev+
----[4]                  string              19    Seq_constant_length
--max_random_depth       integral            32                    'd4
--num_last_reqs          integral            32                    'd1
--num_last_rsps          integral            32                    'd1
----------------------------------------------------------------------
OVM_INFO @ 30: ovm_test_top.t_env.Drvr [ovm_test_top.t_env.Drvr]
                Start of reset_dut() method
OVM_INFO @ 70: ovm_test_top.t_env.Drvr [ovm_test_top.t_env.Drvr]
                End of reset_dut() method
OVM_INFO @ 70: ovm_test_top.t_env.Drvr [ovm_test_top.t_env.Drvr]
                Start of cfg_dut() method
OVM_INFO @ 110: ovm_test_top.t_env.Drvr [ovm_test_top.t_env.Drvr]  
                Port 0 Address 00
OVM_INFO @ 130: ovm_test_top.t_env.Drvr [ovm_test_top.t_env.Drvr]  
                Port 1 Address 01
OVM_INFO @ 150: ovm_test_top.t_env.Drvr [ovm_test_top.t_env.Drvr]  
                Port 2 Address 02
OVM_INFO @ 170: ovm_test_top.t_env.Drvr [ovm_test_top.t_env.Drvr]  
                Port 3 Address 03
OVM_INFO @ 190: ovm_test_top.t_env.Drvr [ovm_test_top.t_env.Drvr]
                End of cfg_dut() method
OVM_INFO @ 210: ovm_test_top.t_env.Drvr [ovm_test_top.t_env.Drvr]
                Driving packet ...
OVM_INFO @ 590: ovm_test_top.t_env.Drvr [ovm_test_top.t_env.Drvr]
                Driving packet ...
OVM_INFO @ 970: ovm_test_top.t_env.Drvr [ovm_test_top.t_env.Drvr]
                Driving packet ...

--- OVM Report Summary ---

** Report counts by severity


OVM_INFO :   16
OVM_WARNING :    0
OVM_ERROR :    0
OVM_FATAL :    0

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CM_09_PHASE_6_DRIVER.html[9/26/2012 2:32:38 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PHASE 7 RECEIVER Index


Introduction
SystemVerilog Specification
Verification In this phase, we will write a receiver and use the receiver in environment class to Verification Plan
collect the packets coming from the switch output_interface. Phase 1 Top
Constructs Phase 2 Configuration
Interface Receiver Phase 3 Environment N
Testcase
OOPS
Receiver collects the data bytes from the interface signal. And then unpacks the bytes Phase 4 Packet
Randomization in to packet using unpack_bytes method and pushes it into Rcvr2Sb_port for score Phase 5 Sequencer N
boarding. Sequence
Functional Coverage Phase 6 Driver
Assertion Receiver class is written in Reveicer.sv file. Phase 7 Receiver
Phase 8 Scoreboard
DPI
Receiver class is defined by extending ovm_component class. It will drive the received
UVM Tutorial transaction to scoreboard using ovm_analysis_port. Report a Bug or Comment
on This section - Your
VMM Tutorial
input is what keeps
OVM Tutorial Testbench.in improving
with time!
Easy Labs : SV
Easy Labs : UVM
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

Verilog
Verification
Verilog Switch TB
Basic Constructs

1) Define Receiver class by extending ovm_component.


OpenVera
Constructs `ifndef GUARD_RECEIVER
Switch TB `define GUARD_RECEIVER
RVM Switch TB class Receiver extends ovm_component;
RVM Ethernet sample
endclass : Receiver

`endif
Specman E
Interview Questions 2) Declare configuration class object.

    Configuration cfg;

3) Declare an integer to hold the receiver number.

    integer id;

4) Declare a virtual interface of dut out put side.

  virtual output_interface.OP output_intf;

http://testbench.in/CM_10_PHASE_7_RECEIVER.html[9/26/2012 2:32:47 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

5) Declare analysis port which is used by receiver to send the received transaction to
scoreboard.

  ovm_analysis_port #(Packet) Rcvr2Sb_port;

6) Declare the utility macro. This utility macro provides the implementation of creat()
and get_type_name() methods.

  `ovm_component_utils(Receiver) 

7) Define the constructor.

   function new (string name, ovm_component parent);
      super.new(name, parent);
   endfunction : new

8) Define the build method and construct the Rcvr2Sb_port.

   function void build();
      super.build();
      Rcvr2Sb_port = new("Rcvr2Sb", this); 
   endfunction : build

9) In the end_of_elaboration() method, get the configuration object using


get_config_object and update the virtual interfaces.

   function void end_of_elaboration();
      ovm_object tmp;
      super.end_of_elaboration();
      assert(get_config_object("Configuration",tmp));
      $cast(cfg,tmp);
      output_intf = cfg.output_intf[id]; 
   endfunction : end_of_elaboration

10) Define the run() method. This method collects the packets from the DUT output
interface and unpacks it into high level transaction using transactions unpack_bytes()
method.

    virtual task run();
     bit [7:0] bytes[];
     Packet pkt;

         fork
         forever
         begin
             repeat(2) @(posedge output_intf.clock);
             wait(output_intf.ready)
             output_intf.read <= 1;  
    
             repeat(2) @(posedge output_intf.clock);
             while (output_intf.ready)
             begin
                   bytes = new[bytes.size + 1](bytes);
                   bytes[bytes.size - 1] = output_intf.data_out;
                  @(posedge output_intf.clock);
             end

             output_intf.read <= 0;  


             @(posedge output_intf.clock);
             ovm_report_info(get_full_name(),"Received packet ...",OVM_LOW);
             pkt = new();
             pkt.unpack_bytes(bytes);
             Rcvr2Sb_port.write(pkt);
             bytes.delete();  
         end
         join

     endtask : run

http://testbench.in/CM_10_PHASE_7_RECEIVER.html[9/26/2012 2:32:47 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

Receiver class source code


`ifndef GUARD_RECEIVER
`define GUARD_RECEIVER

class Receiver extends ovm_component;

    virtual output_interface.OP output_intf;

    Configuration cfg;

    integer id;

    ovm_analysis_port #(Packet) Rcvr2Sb_port;

   `ovm_component_utils(Receiver) 

    function new (string name, ovm_component parent);
        super.new(name, parent);
    endfunction : new

    function void build();
        super.build();
        Rcvr2Sb_port = new("Rcvr2Sb", this);
    endfunction : build

    function void end_of_elaboration();
        ovm_object tmp;
        super.end_of_elaboration();
        assert(get_config_object("Configuration",tmp));
        $cast(cfg,tmp);
        output_intf = cfg.output_intf[id]; 
    endfunction : end_of_elaboration

     virtual task run();
     bit [7:0] bytes[];
     Packet pkt;

         fork
         forever
         begin
             repeat(2) @(posedge output_intf.clock);
             wait(output_intf.ready)
             output_intf.read <= 1;  
    
             repeat(2) @(posedge output_intf.clock);
             while (output_intf.ready)
             begin
                   bytes = new[bytes.size + 1](bytes);
                   bytes[bytes.size - 1] = output_intf.data_out;
                  @(posedge output_intf.clock);
             end

             output_intf.read <= 0;  


             @(posedge output_intf.clock);
             ovm_report_info(get_full_name(),"Received packet ...",OVM_LOW);
             pkt = new();
             pkt.unpack_bytes(bytes);
             Rcvr2Sb_port.write(pkt);
             bytes.delete();  
         end
         join

     endtask : run

endclass :  Receiver

Environment Class Updates

We will update the Environment class and take instance of receiver and run the
testcase.

http://testbench.in/CM_10_PHASE_7_RECEIVER.html[9/26/2012 2:32:47 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

1) Declare 4 receivers.

    Receiver Rcvr[4];

2) In the build() method construct the Receivers using create() methods. Also update
the id variable of the receiver object.  

    foreach(Rcvr[i]) begin
        Rcvr[i]   = Receiver::type_id::create($psprintf("Rcvr%0d",i),this);
        Rcvr[i].id = i;
    end

Environment class source code

`ifndef GUARD_ENV
`define GUARD_ENV

class Environment extends ovm_env;

    `ovm_component_utils(Environment)

     Sequencer Seqncr;


     Driver Drvr;

     Receiver Rcvr[4];

    function new(string name , ovm_component parent = null);


        super.new(name, parent);
    endfunction: new

    function void build();


        super.build();
        ovm_report_info(get_full_name(),"START of build ",OVM_LOW);
        Drvr   = Driver::type_id::create("Drvr",this);
        Seqncr = Sequencer::type_id::create("Seqncr",this);

        foreach(Rcvr[i]) begin
            Rcvr[i]   = Receiver::type_id::create($psprintf("Rcvr%0d",i),this);
            Rcvr[i].id = i;
        end

        ovm_report_info(get_full_name(),"END of build ",OVM_LOW);


    endfunction
    
    function void connect();
        super.connect();
        ovm_report_info(get_full_name(),"START of connect ",OVM_LOW);
        Drvr.seq_item_port.connect(Seqncr.seq_item_export);
        ovm_report_info(get_full_name(),"END of connect ",OVM_LOW);
    endfunction

endclass : Environment
`endif

Download the Source Code

ovm_switch_7.tar
Browse the code in ovm_switch_7.tar

http://testbench.in/CM_10_PHASE_7_RECEIVER.html[9/26/2012 2:32:47 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

Command to run the simulation

 vcs -sverilog +incdir+$OVM_HOME/src $OVM_HOME/src/ovm_pkg.sv +incdir+. rtl.sv


interface.sv top.sv -R +OVM_TESTNAME=test1
 qverilog +incdir+$OVM_HOME/src $OVM_HOME/src/ovm_pkg.sv +incdir+. rtl.sv
interface.sv top.sv -R +OVM_TESTNAME=test1

Log report after simulation

OVM_INFO @ 0 [RNTST] Running test test1...


OVM_INFO @ 0: ovm_test_top.t_env [ovm_test_top.t_env] START of build
OVM_INFO @ 0: ovm_test_top.t_env [ovm_test_top.t_env] END of build
OVM_INFO @ 0: ovm_test_top.t_env [ovm_test_top.t_env] START of connect
OVM_INFO @ 0: ovm_test_top.t_env [ovm_test_top.t_env] END of connect
----------------------------------------------------------------------
Name                     Type                Size                Value
----------------------------------------------------------------------
Seqncr                   Sequencer           -               Seqncr@14
--rsp_export             ovm_analysis_export -           rsp_export@16
--seq_item_export        ovm_seq_item_pull_+ -      seq_item_export@40
--default_sequence       string              19    ovm_random_sequence
--count                  integral            32                     -1
--max_random_count       integral            32                   'd10
--sequences              array               5                       -
----[0]                  string              19    ovm_random_sequence
----[1]                  string              23   ovm_exhaustive_sequ+
----[2]                  string              19    ovm_simple_sequence
----[3]                  string              23   Seq_device0_and_dev+
----[4]                  string              19    Seq_constant_length
--max_random_depth       integral            32                    'd4
--num_last_reqs          integral            32                    'd1
--num_last_rsps          integral            32                    'd1
----------------------------------------------------------------------
OVM_INFO @ 30: ovm_test_top.t_env.Drvr [ovm_test_top.t_env.Drvr]
               Start of reset_dut() method
OVM_INFO @ 70: ovm_test_top.t_env.Drvr [ovm_test_top.t_env.Drvr]
               End of reset_dut() method
OVM_INFO @ 70: ovm_test_top.t_env.Drvr [ovm_test_top.t_env.Drvr]
               Start of cfg_dut() method
OVM_INFO @ 110: ovm_test_top.t_env.Drvr [ovm_test_top.t_env.Drvr]
               Port 0 Address 00
OVM_INFO @ 130: ovm_test_top.t_env.Drvr [ovm_test_top.t_env.Drvr]  
               Port 1 Address 01
OVM_INFO @ 150: ovm_test_top.t_env.Drvr [ovm_test_top.t_env.Drvr]
               Port 2 Address 02
OVM_INFO @ 170: ovm_test_top.t_env.Drvr [ovm_test_top.t_env.Drvr]
               Port 3 Address 03
OVM_INFO @ 190: ovm_test_top.t_env.Drvr [ovm_test_top.t_env.Drvr]
               End of cfg_dut() method
OVM_INFO @ 210: ovm_test_top.t_env.Drvr [ovm_test_top.t_env.Drvr]
               Driving packet ...
OVM_INFO @ 590: ovm_test_top.t_env.Drvr [ovm_test_top.t_env.Drvr]
               Driving packet ...
OVM_INFO @ 610: ovm_test_top.t_env.Rcvr0 [ovm_test_top.t_env.Rcvr0]
               Received packet ...
OVM_INFO @ 970: ovm_test_top.t_env.Drvr [ovm_test_top.t_env.Drvr]
               Driving packet ...
OVM_INFO @ 990: ovm_test_top.t_env.Rcvr0 [ovm_test_top.t_env.Rcvr0]
               Received packet ...

--- OVM Report Summary ---

** Report counts by severity


OVM_INFO :   18
OVM_WARNING :    0
OVM_ERROR :    0
OVM_FATAL :    0

http://testbench.in/CM_10_PHASE_7_RECEIVER.html[9/26/2012 2:32:47 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CM_10_PHASE_7_RECEIVER.html[9/26/2012 2:32:47 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PHASE 8 SCOREBOARD Index


Introduction
SystemVerilog Specification
Verification In this phase we will see the scoreboard implementation. Verification Plan
Phase 1 Top
Constructs Scoreboard Phase 2 Configuration
Interface Phase 3 Environment N
Scoreboard is implemented by extending ovm_scorboard. For our requirement, we can Testcase
OOPS Phase 4 Packet
use ovm_in_order_comparator, but we will see develop our own scoreboard by
Randomization extending ovm_scorboard. Scoreboard has 2 analysis imports. One is used to for Phase 5 Sequencer N
getting the packets from the driver and other from the receiver.  Then the packets Sequence
Functional Coverage Phase 6 Driver
are compared and if they don't match, then error is asserted. For comparison,
Assertion compare () method of the Packet class is used. Phase 7 Receiver
Phase 8 Scoreboard
DPI
Implement the scoreboard in file Scoreboard.sv.
UVM Tutorial Report a Bug or Comment
Steps to create a scoreboard: on This section - Your
VMM Tutorial
1) Useing macro `ovm_analysis_imp_decl(<_portname>), to declare input is what keeps
OVM Tutorial ovm_analysis_imp_<_portname>  class. Testbench.in improving
2) The above macro, creates write_<_portname>(). This method has to be define as with time!
Easy Labs : SV
per our requirements.
Easy Labs : UVM
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

Verilog
Verification
Verilog Switch TB
Basic Constructs
1) Declare a scoreboard by extending ovm_scoreboard class.

OpenVera class Scoreboard extends ovm_scoreboard;


Constructs
endclass : Scoreboard
Switch TB
RVM Switch TB
2) We need 2 import, one for expected packet which is sent by driver and received
packet which is coming from receiver.
RVM Ethernet sample    Declare 2 imports using `ovm_analysis_imp_decl macros.

    `ovm_analysis_imp_decl(_rcvd_pkt)
    `ovm_analysis_imp_decl(_sent_pkt)
Specman E
Interview Questions 3)  Declare the utility macro.

   `ovm_component_utils(Scoreboard)

4) Declare a queue which stores the expected packets.

   Packet exp_que[$];

5) Declare imports for getting expected packets and received packets.

   ovm_analysis_imp_rcvd_pkt #(Packet,Scoreboard) Rcvr2Sb_port;

http://testbench.in/CM_11_PHASE_8_SCOREBOARD.html[9/26/2012 2:32:56 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

   ovm_analysis_imp_sent_pkt #(Packet,Scoreboard) Drvr2Sb_port;

6) In the constructor, create objects for the above two declared imports.

    function new(string name, ovm_component parent);
       super.new(name, parent);
       Rcvr2Sb_port = new("Rcvr2Sb", this);
       Drvr2Sb_port = new("Drvr2Sb", this);
    endfunction : new

7) Define write_sent_pkt() method which was created by macro


`ovm_analysis_imp_decl(_sent_pkt).
   In this method, store the received packet in the expected queue.

   virtual function void write_sent_pkt(input Packet pkt);
       exp_que.push_back(pkt);
   endfunction : write_sent_pkt

8) Define write_rcvd_pkt() method which was created by macro


`ovm_analysis_imp_decl(_rcvd_pkt)
  In this method, get the transaction from the expected queue and compare.

   virtual function void write_rcvd_pkt(input Packet pkt);
       Packet exp_pkt;
       pkt.print();
       if(exp_que.size())
       begin
           exp_pkt = exp_que.pop_front();
           exp_pkt.print();
           if( pkt.compare(exp_pkt))
               ovm_report_info(get_type_name(),
               $psprintf("Sent packet and reeived packet mathed"), OVM_LOW);
           else
               ovm_report_error(get_type_name(),
               $psprintf("Sent packet and reeived packet mismatched"), OVM_LOW);
       end
       else
           ovm_report_error(get_type_name(),
           $psprintf("No more packets in the expected queue to compare"), OVM_LOW);
   endfunction : write_rcvd_pkt

9) Define the report() method to print the Scoreboard information.

  virtual function void report();
      ovm_report_info(get_type_name(),
      $psprintf("Scoreboard Report %s", this.sprint()), OVM_LOW);
  endfunction : report

Complete Scoreboard Code


`ifndef GUARD_SCOREBOARD
`define GUARD_SCOREBOARD

`ovm_analysis_imp_decl(_rcvd_pkt)
`ovm_analysis_imp_decl(_sent_pkt)

class Scoreboard extends ovm_scoreboard;
    `ovm_component_utils(Scoreboard)
  
    Packet exp_que[$];
  
    ovm_analysis_imp_rcvd_pkt #(Packet,Scoreboard) Rcvr2Sb_port;
    ovm_analysis_imp_sent_pkt #(Packet,Scoreboard) Drvr2Sb_port;
  
    function new(string name, ovm_component parent);
        super.new(name, parent);
        Rcvr2Sb_port = new("Rcvr2Sb", this);
        Drvr2Sb_port = new("Drvr2Sb", this);
    endfunction : new
  

http://testbench.in/CM_11_PHASE_8_SCOREBOARD.html[9/26/2012 2:32:56 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

    virtual function void write_rcvd_pkt(input Packet pkt);
        Packet exp_pkt;
        pkt.print();

        if(exp_que.size())
        begin
           exp_pkt = exp_que.pop_front();
           exp_pkt.print();
           if( pkt.compare(exp_pkt))
             ovm_report_info(get_type_name(),
             $psprintf("Sent packet and reeived packet mathed"), OVM_LOW);
           else
             ovm_report_error(get_type_name(),  
             $psprintf("Sent packet and reeived packet mismatched"), OVM_LOW);
        end
        else
             ovm_report_error(get_type_name(),
             $psprintf("No more packets to in the expected queue to
compare"), OVM_LOW);
   endfunction : write_rcvd_pkt
  
   virtual function void write_sent_pkt(input Packet pkt);
        exp_que.push_back(pkt);
   endfunction : write_sent_pkt
  
  
   virtual function void report();
        ovm_report_info(get_type_name(),
        $psprintf("Scoreboard Report %s", this.sprint()), OVM_LOW);
   endfunction : report
  
endclass : Scoreboard
`endif

Environment Class Updates

We will take the instance of scoreboard in the environment and connect its ports to
driver and receiver ports.

1) Declare scoreboard object.

     Scoreboard Sbd;

2) Construct the scoreboard object using create() method in build() method.

        Sbd   = Scoreboard::type_id::create("Sbd",this);

3) In connect() method, connect the driver and receiver ports to scoreboard.

        Drvr.Drvr2Sb_port.connect(Sbd.Drvr2Sb_port);

        Rcvr[0].Rcvr2Sb_port.connect(Sbd.Rcvr2Sb_port);
        Rcvr[1].Rcvr2Sb_port.connect(Sbd.Rcvr2Sb_port);
        Rcvr[2].Rcvr2Sb_port.connect(Sbd.Rcvr2Sb_port);
        Rcvr[3].Rcvr2Sb_port.connect(Sbd.Rcvr2Sb_port);

Environemnt class code

http://testbench.in/CM_11_PHASE_8_SCOREBOARD.html[9/26/2012 2:32:56 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

`ifndef GUARD_ENV
`define GUARD_ENV

class Environment extends ovm_env;

    `ovm_component_utils(Environment)

     Sequencer Seqncr;


     Driver Drvr;
     Receiver Rcvr[4];

     Scoreboard Sbd;

    function new(string name , ovm_component parent = null);


        super.new(name, parent);
    endfunction: new

    function void build();


        super.build();
        ovm_report_info(get_full_name(),"START of build ",OVM_LOW);

        Drvr   = Driver::type_id::create("Drvr",this);
        Seqncr = Sequencer::type_id::create("Seqncr",this);
        
        foreach(Rcvr[i]) begin
            Rcvr[i]   = Receiver::type_id::create($psprintf("Rcvr%0d",i),this);
            Rcvr[i].id = i;
        end

        Sbd   = Scoreboard::type_id::create("Sbd",this);

        ovm_report_info(get_full_name(),"END of build ",OVM_LOW);


    endfunction
    
    function void connect();
        super.connect();
        ovm_report_info(get_full_name(),"START of connect ",OVM_LOW);

        Drvr.seq_item_port.connect(Seqncr.seq_item_export);

        Drvr.Drvr2Sb_port.connect(Sbd.Drvr2Sb_port);

        Rcvr[0].Rcvr2Sb_port.connect(Sbd.Rcvr2Sb_port);
        Rcvr[1].Rcvr2Sb_port.connect(Sbd.Rcvr2Sb_port);
        Rcvr[2].Rcvr2Sb_port.connect(Sbd.Rcvr2Sb_port);
        Rcvr[3].Rcvr2Sb_port.connect(Sbd.Rcvr2Sb_port);

        ovm_report_info(get_full_name(),"END of connect ",OVM_LOW);


    endfunction

endclass : Environment
`endif

Download the Source Code

ovm_switch_8.tar
Browse the code in ovm_switch_8.tar

Command to run the simulation

 vcs -sverilog +incdir+$OVM_HOME/src $OVM_HOME/src/ovm_pkg.sv +incdir+. rtl.sv


interface.sv top.sv -R +OVM_TESTNAME=test1
 qverilog +incdir+$OVM_HOME/src $OVM_HOME/src/ovm_pkg.sv +incdir+. rtl.sv
interface.sv top.sv -R +OVM_TESTNAME=test1

Log report after simulation

OVM_INFO @ 0 [RNTST] Running test test1...


OVM_INFO @ 0: ovm_test_top.t_env [ovm_test_top.t_env] START of build
OVM_INFO @ 0: ovm_test_top.t_env [ovm_test_top.t_env] END of build
OVM_INFO @ 0: ovm_test_top.t_env [ovm_test_top.t_env] START of connect
OVM_INFO @ 0: ovm_test_top.t_env [ovm_test_top.t_env] END of connect

http://testbench.in/CM_11_PHASE_8_SCOREBOARD.html[9/26/2012 2:32:56 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

----------------------------------------------------------------------
Name                     Type                Size                Value
----------------------------------------------------------------------
Seqncr                   Sequencer           -               Seqncr@14
  rsp_export             ovm_analysis_export -           rsp_export@16
  seq_item_export        ovm_seq_item_pull_+ -      seq_item_export@40
  default_sequence       string              19    ovm_random_sequence
  count                  integral            32                     -1
  max_random_count       integral            32                   'd10
  sequences              array               5                       -
    [0]                  string              19    ovm_random_sequence
    [1]                  string              23   ovm_exhaustive_sequ+
    [2]                  string              19    ovm_simple_sequence
    [3]                  string              23   Seq_device0_and_dev+
    [4]                  string              19    Seq_constant_length
  max_random_depth       integral            32                    'd4
  num_last_reqs          integral            32                    'd1
  num_last_rsps          integral            32                    'd1
----------------------------------------------------------------------
OVM_INFO @ 30: ovm_test_top.t_env.Drvr [ovm_test_top.t_env.Drvr]
            Start of reset_dut() method
OVM_INFO @ 70: ovm_test_top.t_env.Drvr [ovm_test_top.t_env.Drvr]
            End of reset_dut() method
OVM_INFO @ 70: ovm_test_top.t_env.Drvr [ovm_test_top.t_env.Drvr]
            Start of cfg_dut() method
OVM_INFO @ 110: ovm_test_top.t_env.Drvr [ovm_test_top.t_env.Drvr]  
            Port 0 Address 00
OVM_INFO @ 130: ovm_test_top.t_env.Drvr [ovm_test_top.t_env.Drvr]
            Port 1 Address 01
OVM_INFO @ 150: ovm_test_top.t_env.Drvr [ovm_test_top.t_env.Drvr]
            Port 2 Address 02
OVM_INFO @ 170: ovm_test_top.t_env.Drvr [ovm_test_top.t_env.Drvr]
            Port 3 Address 03
OVM_INFO @ 190: ovm_test_top.t_env.Drvr [ovm_test_top.t_env.Drvr]
            End of cfg_dut() method
OVM_INFO @ 210: ovm_test_top.t_env.Drvr [ovm_test_top.t_env.Drvr]
            Driving packet ...
OVM_INFO @ 590: ovm_test_top.t_env.Drvr [ovm_test_top.t_env.Drvr]
            Driving packet ...
OVM_INFO @ 610: ovm_test_top.t_env.Rcvr0 [ovm_test_top.t_env.Rcvr0]
            Received packet ...
OVM_INFO @ 610: ovm_test_top.t_env.Sbd [Scoreboard]
            Sent packet and reeived packet mathed
OVM_INFO @ 970: ovm_test_top.t_env.Drvr [ovm_test_top.t_env.Drvr]
           Driving packet ...
OVM_INFO @ 990: ovm_test_top.t_env.Rcvr0 [ovm_test_top.t_env.Rcvr0]
           Received packet ...
OVM_INFO @ 990: ovm_test_top.t_env.Sbd [Scoreboard]
            Sent packet and reeived packet mathed
OVM_INFO @ 1000: ovm_test_top.t_env.Sbd [Scoreboard]
           Scoreboard Report
----------------------------------------------------------------------
Name                     Type                Size                Value
----------------------------------------------------------------------
Sbd                      Scoreboard          -                  Sbd@52
  Drvr2Sb                ovm_analysis_imp_s+ -              Drvr2Sb@56
  Rcvr2Sb                ovm_analysis_imp_r+ -              Rcvr2Sb@54
----------------------------------------------------------------------

--- OVM Report Summary ---

** Report counts by severity


OVM_INFO :   21
OVM_WARNING :    0
OVM_ERROR :    0
OVM_FATAL :    0

http://testbench.in/CM_11_PHASE_8_SCOREBOARD.html[9/26/2012 2:32:56 PM]


WWW.TESTBENCH.IN - Easy Labs : OVM

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/CM_11_PHASE_8_SCOREBOARD.html[9/26/2012 2:32:56 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INTRODUCTION Index


Introduction
SystemVerilog Specification
Verification Verification Plan
Phase 1 Top
Constructs In this tutorial, we will verify the Switch RTL core using VMM in SystemVerilog. Phase 2 Environment
Interface Following are the steps we follow to verify the Switch RTL core. Phase 3 Reset
Phase 4 Packet
OOPS Phase 5 Generator
1) Understand the specification
Randomization Phase 6 Driver
2) Developing Verification Plan Phase 7 Receiver
Functional Coverage Phase 8 Scoreboard
Assertion 3) Building the Verification Environment. We will build the Environment in Multiple Phase 9 Coverage
DPI phases, so it will be easy for you to lean step by step.
Report a Bug or Comment
UVM Tutorial Phase 1) We will develop the testcase and interfaces, and integrate them in these on This section - Your
with the DUT in top module. input is what keeps
VMM Tutorial
Testbench.in improving
OVM Tutorial with time!
Phase 2) We will Develop the Environment class.
Easy Labs : SV
Easy Labs : UVM Phase 3) We will develop reset and configuration methods in Environment class.
Then using these methods, we will reset the DUT and configure the port address.
Easy Labs : OVM
Easy Labs : VMM Phase 4) We will develop a packet class based on the stimulus plan. We will also
write a small code to test the packet class implementation.
AVM Switch TB
VMM Ethernet sample Phase 5) We will create atomic generator in the environment class.  

Phase 6) We will develop a driver class. Packets are taken from the generator and
Verilog sent to DUT using driver.  
Verification
Phase 7) We will develop receiver class. Receiver collects the packets coming from
Verilog Switch TB the output port of the DUT.
Basic Constructs
Phase 8) We will develop scoreboard class which does the comparison of the
expected packet with the actual packet received from the DUT.
OpenVera
Phase 9) We will develop coverage class based on the coverage plan. Coverage is
Constructs sampled using the driver callbacks.
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/VL_01_INTRODUCTION.html[9/26/2012 2:33:04 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/VL_01_INTRODUCTION.html[9/26/2012 2:33:04 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS SPECIFICATION Index


Introduction
SystemVerilog Switch Specification: Specification
Verification Verification Plan
This is a simple switch. Switch is a packet based protocol. Switch drives the incoming Phase 1 Top
Constructs packet which comes from the input port to output ports based on the address Phase 2 Environment
Interface contained in the packet. Phase 3 Reset
Phase 4 Packet
OOPS
The switch has a one input port from which the packet enters. It has four output ports Phase 5 Generator
Randomization where the packet is driven out. Phase 6 Driver
Phase 7 Receiver
Functional Coverage Phase 8 Scoreboard
Assertion Phase 9 Coverage
DPI Report a Bug or Comment
UVM Tutorial on This section - Your
input is what keeps
VMM Tutorial
Testbench.in improving
OVM Tutorial with time!
Easy Labs : SV
Easy Labs : UVM
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

Verilog
Verification
Verilog Switch TB
Basic Constructs

Packet Format:
OpenVera
Constructs Packet contains 3 parts. They are Header, data and frame check sequence.
Packet width is 8 bits and the length of the packet can be between 4 bytes to 259
Switch TB bytes.
RVM Switch TB
RVM Ethernet sample
Packet header:

Packet header contains three fields DA, SA and length.


Specman E
Interview Questions DA: Destination address of the packet is of 8 bits. The switch drives the packet to
respective ports based on this destination address of the packets. Each output port
has 8-bit unique port address.  If the destination address of the packet matches the
port address, then switch drives the packet to the output port.

SA: Source address of the packet from where it originate. It is 8 bits.


Length: Length of the data is of 8 bits and  from 0 to 255. Length is measured in terms
of bytes.  
If Length = 0, it means data length is 0 bytes
If Length = 1, it means data length is 1 bytes
If Length = 2, it means data length is 2 bytes

http://testbench.in/VL_02_SPECIFICATION.html[9/26/2012 2:33:13 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

If Length = 255, it means data length is 255 bytes

Data: Data should be in terms of bytes and can take anything.

FCS: Frame check sequence


 This field contains the security check of the packet. It is calculated over the header
and data.

Configuration:

Switch has four output ports. These output ports address have to be configured to a
unique address. Switch matches the DA field of the packet with this configured port
address and sends the packet on to that port. Switch contains a memory. This
memory has 4 locations, each can store 8 bits. To configure the switch port address,
memory write operation has to be done using memory interface. Memory address
(0,1,2,3) contains the address of port(0,1,2,4) respectively.

Interface Specification:

The Switch has one input Interface, from where the packet enters and 4 output
interfaces from where the packet comes out and one memory interface, through the
port address can be configured.  Switch also has a clock and asynchronous reset
signal.  

 
MEMORY INTERFACE:

Through memory interfaced output port address are configured. It accepts 8 bit data
to be written to memory. It has 8 bit address inputs. Address 0,1,2,3 contains the
address of the port 0,1,2,3 respectively.

There are 4 input signals to memory interface. They are

input mem_en;
input mem_rd_wr;
input [1:0] mem_add;
input [7:0] mem_data;

All the signals are active high and are synchronous to the positive edge of clock
signal.
To configure a port address,
1.      Assert the mem_en signal.

http://testbench.in/VL_02_SPECIFICATION.html[9/26/2012 2:33:13 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

2.      Asser the mem_rd_wr signal.


3.      Drive the port number (0 or 1 or 2 or 3) on the mem_add signal
4.      Drive the 8 bit port address on to mem_data signal.

INPUT PORT

Packets are sent into the switch using input port.


All the signals are active high and are synchronous to the positive edge of clock
signal.

input port has 2 input signals. They are


input [7:0] data;
input data_status;

To send the packet in to switch,

1. Assert the data_status signal.


2. Send the packet on the data signal byte by byte.
3. After sending all the data bytes, deassert the data_status signal.
4. There should be at least 3 clock cycles difference between packets.

OUTPUT PORT

Switch sends the packets out using the output ports.  There are 4 ports, each having
data, ready and read signals.  All the signals are active high and are synchronous to
the positive edge of clock signal.

Signal list is

output   [7:0] port0;
output   [7:0] port1;
output   [7:0] port2;
output   [7:0] port3;
output         ready_0;
output       ready_1;
output       ready_2;
output       ready_3;
input       read_0;
input       read_1;
input       read_2;
input       read_3;

When the data is ready to be sent out from the port, switch asserts ready_* signal
high indicating that data is ready to be sent.
If the read_* signal is asserted, when ready_* is high, then the data comes out of the
port_* signal after one clock cycle.

http://testbench.in/VL_02_SPECIFICATION.html[9/26/2012 2:33:13 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

RTL  code:

RTL code is attached with the tar files. From the Phase 1, you can download the tar
files.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/VL_02_SPECIFICATION.html[9/26/2012 2:33:13 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS VERIFICATION PLAN Index


Introduction
SystemVerilog Overview Specification
Verification Verification Plan
This Document describes the Verification Plan for Switch. The Verification Plan is Phase 1 Top
Constructs based on System Verilog Hardware Verification Language. The methodology used for Phase 2 Environment
Interface Verification is Constraint random coverage driven verification. Phase 3 Reset
Phase 4 Packet
OOPS Phase 5 Generator
Randomization Feature Extraction Phase 6 Driver
Phase 7 Receiver
Functional Coverage Phase 8 Scoreboard
This section contains list of all the features to be verified.
Assertion 1) Phase 9 Coverage
DPI ID:  Configuration
Description: Configure all the 4 port address with unique values. Report a Bug or Comment
UVM Tutorial on This section - Your
2) input is what keeps
VMM Tutorial
ID: Packet DA Testbench.in improving
OVM Tutorial Description: DA field of packet should be any of the port address. All the 4 port with time!
Easy Labs : SV address should be used.
Easy Labs : UVM 3)
Easy Labs : OVM ID : Packet payload
Description: Length can be from 0 to 255. Send packets with all the lengths.
Easy Labs : VMM
AVM Switch TB 4)
ID: Length
VMM Ethernet sample Description:
Length field contains length of the payload.
Send Packet with correct length field and incorrect length fields.
Verilog
Verification 5)
ID: FCS
Verilog Switch TB Description:
Basic Constructs Good FCS:  Send packet with good FCS.
Bad FCS: Send packet with corrupted FCS.  

OpenVera Stimulus Generation Plan


Constructs
Switch TB 1) Packet DA: Generate packet DA with the configured address.
2) Payload length: generate payload length ranging from 2 to 255.
RVM Switch TB 3) Correct or Incorrect Length field.
RVM Ethernet sample 4) Generate good and bad FCS.

Coverage Plan
Specman E
Interview Questions 1)      Cover all the port address configurations.
2)      Cover all the packet lengths.
3)      Cover all correct and incorrect length fields.
4)      Cover good and bad FCS.
5)      Cover all the above combinations.

Verification Environment

http://testbench.in/VL_03_VERIFICATION_PLAN.html[9/26/2012 2:33:22 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

  

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/VL_03_VERIFICATION_PLAN.html[9/26/2012 2:33:22 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PHASE 1 TOP Index


Introduction
SystemVerilog Specification
Verification In phase 1, Verification Plan
Phase 1 Top
Constructs 1) We will write SystemVerilog Interfaces for input port, output port and memory Phase 2 Environment
Interface port. Phase 3 Reset
2) We will write Top module where testcase and DUT instances are done. Phase 4 Packet
OOPS Phase 5 Generator
3) DUT and TestBench interfaces are connected in top module.
Randomization 4) Clock is generator in top module. Phase 6 Driver
Phase 7 Receiver
Functional Coverage Phase 8 Scoreboard
Assertion NOTE: In every file you will see the syntax Phase 9 Coverage
DPI `ifndef GUARD_*
`endif GUARD_*  Report a Bug or Comment
UVM Tutorial on This section - Your
input is what keeps
VMM Tutorial
Interfaces Testbench.in improving
OVM Tutorial with time!
Easy Labs : SV
Easy Labs : UVM In the interface.sv file, declare the 3 interfaces in the following way.
Easy Labs : OVM All the interfaces has clock as input.
Easy Labs : VMM All the signals in interface are wire type.
All the signals are synchronized to clock except reset in clocking block.
AVM Switch TB
VMM Ethernet sample This approach will avoid race conditions between the design and the verification
environment.
Define the set-up and hold time using parameters.
Verilog Signal directional w.r.t TestBench is specified with modport.
Verification
Verilog Switch TB
Basic Constructs `ifndef GUARD_INTERFACE
`define GUARD_INTERFACE

OpenVera //////////////////////////////////////////
Constructs // Interface declaration for the memory///
//////////////////////////////////////////
Switch TB
RVM Switch TB interface mem_interface(input bit clock);
RVM Ethernet sample   parameter setup_time = 5ns;
  parameter hold_time = 3ns;

Specman E   wire [7:0] mem_data;
  wire [1:0] mem_add;
Interview Questions   wire       mem_en;
  wire       mem_rd_wr;
  
  clocking cb@(posedge clock);
     default input #setup_time output #hold_time;
     output     mem_data;
     output      mem_add;
     output mem_en;
     output mem_rd_wr;
  endclocking:cb
  

http://testbench.in/VL_04_PHASE_1_TOP.html[9/26/2012 2:33:32 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

  modport MEM(clocking cb,input clock);

endinterface :mem_interface

////////////////////////////////////////////
// Interface for the input side of switch.//
// Reset signal is also passed hear.      //
////////////////////////////////////////////
interface input_interface(input bit clock);

  parameter setup_time = 5ns;
  parameter hold_time = 3ns;

  wire           data_status;
  wire     [7:0] data_in;
  wire           reset; 

  clocking cb@(posedge clock);
     default input #setup_time output #hold_time;
     output    data_status;
     output    data_in;
  endclocking:cb
  
  modport IP(clocking cb,output reset,input clock);
  
endinterface:input_interface

/////////////////////////////////////////////////
// Interface for the output side of the switch.//
// output_interface is for only one output port//
/////////////////////////////////////////////////

interface output_interface(input bit clock);

  parameter setup_time = 5ns;
  parameter hold_time = 3ns;

  wire    [7:0] data_out;
  wire    ready;
  wire    read;
  
  clocking cb@(posedge clock);
    default input #setup_time output #hold_time;
    input     data_out;
    input     ready;
    output    read;
  endclocking:cb
  
  modport OP(clocking cb,input clock);

endinterface:output_interface

//////////////////////////////////////////////////

`endif 

Testcase

Testcase is a program block which provides an entry point for the test and creates a
scope that encapsulates program-wide data. Currently this is an empty testcase which
just ends the simulation.  Program block contains all the above declared interfaces as
arguments. This testcase has initial and final blocks.

Inside the program block, include the vmm.sv file.

http://testbench.in/VL_04_PHASE_1_TOP.html[9/26/2012 2:33:32 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

`ifndef GUARD_TESTCASE
`define GUARD_TESTCASE

program testcase(mem_interface.MEM mem_intf,input_interface.IP input_intf,output_interface.OP output_intf[4
]);

`include "vmm.sv"

initial
begin
$display(" ******************* Start of testcase ****************");

#1000;
end

final
$display(" ******************** End of testcase *****************");

endprogram 
`endif

Top Module

The modules that are included in the source text but are not instantiated are called
top modules. This module is the highest scope of modules. Generally this module is
named as "top" and referenced as "top module".  Module name can be anything.
This top-level module will contain the design portion of the simulation.

Do the following in the top module:

1)Generate the clock signal.

bit Clock;

initial
  begin
      #20;
      forever #10 Clock = ~Clock;
  end

2)Do the instances of memory interface.

mem_interface mem_intf(Clock);

3)Do the instances of input interface.

input_interface input_intf(Clock);

4)There are 4 output ports. So do 4 instances of output_interface.

output_interface output_intf[4](Clock);

5)Do the instance of testcase and pass all the above declared interfaces.

testcase TC (mem_intf,input_intf,output_intf);

6)Do the instance of DUT.

switch DUT    (.

7)Connect all the interfaces and DUT.  The design which we have taken is in
verilog.  So Verilog DUT instance is connected signal by signal.

http://testbench.in/VL_04_PHASE_1_TOP.html[9/26/2012 2:33:32 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

switch DUT    (.clk(Clock),
               .reset(input_intf.reset),
               .data_status(input_intf.data_status),
               .data(input_intf.data_in),
               .port0(output_intf[0].data_out),
               .port1(output_intf[1].data_out),
               .port2(output_intf[2].data_out),
               .port3(output_intf[3].data_out),
               .ready_0(output_intf[0].ready),
               .ready_1(output_intf[1].ready),
               .ready_2(output_intf[2].ready),
               .ready_3(output_intf[3].ready),
               .read_0(output_intf[0].read),
               .read_1(output_intf[1].read),
               .read_2(output_intf[2].read),
               .read_3(output_intf[3].read),
               .mem_en(mem_intf.mem_en),
               .mem_rd_wr(mem_intf.mem_rd_wr),
               .mem_add(mem_intf.mem_add),
               .mem_data(mem_intf.mem_data));

Top Module Source Code:

`ifndef GUARD_TOP
`define GUARD_TOP

module top();

/////////////////////////////////////////////////////
// Clock Declaration and Generation                //
/////////////////////////////////////////////////////
bit Clock;

initial
  begin
      #20;
      forever #10 Clock = ~Clock;
  end
/////////////////////////////////////////////////////
//  Memory interface instance                      //
/////////////////////////////////////////////////////

http://testbench.in/VL_04_PHASE_1_TOP.html[9/26/2012 2:33:32 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

mem_interface mem_intf(Clock);

/////////////////////////////////////////////////////
//  Input interface instance                       //
/////////////////////////////////////////////////////

input_interface input_intf(Clock);

/////////////////////////////////////////////////////
//  output interface instance                      //
/////////////////////////////////////////////////////

output_interface output_intf[4](Clock);

/////////////////////////////////////////////////////
//  Program block Testcase instance                //
/////////////////////////////////////////////////////

testcase TC (mem_intf,input_intf,output_intf);

/////////////////////////////////////////////////////
//  DUT instance and signal connection             //
/////////////////////////////////////////////////////

switch DUT    (.clk(Clock),
               .reset(input_intf.reset),
               .data_status(input_intf.data_status),
               .data(input_intf.data_in),
               .port0(output_intf[0].data_out),
               .port1(output_intf[1].data_out),
               .port2(output_intf[2].data_out),
               .port3(output_intf[3].data_out),
               .ready_0(output_intf[0].ready),
               .ready_1(output_intf[1].ready),
               .ready_2(output_intf[2].ready),
               .ready_3(output_intf[3].ready),
               .read_0(output_intf[0].read),
               .read_1(output_intf[1].read),
               .read_2(output_intf[2].read),
               .read_3(output_intf[3].read),
               .mem_en(mem_intf.mem_en),
               .mem_rd_wr(mem_intf.mem_rd_wr),
               .mem_add(mem_intf.mem_add),
               .mem_data(mem_intf.mem_data));

endmodule

`endif

Download the phase 1 files:

vmm_switch_1.tar
Browse the code in vmm_switch_1.tar

Run the simulation:


vcs -sverilog -f filelist -R -ntb_opts rvm

Log file after simulation:

 ******************* Start of testcase ****************


 ******************** End of testcase *****************

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/VL_04_PHASE_1_TOP.html[9/26/2012 2:33:32 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/VL_04_PHASE_1_TOP.html[9/26/2012 2:33:32 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PHASE 2 ENVIRONMENT Index


Introduction
SystemVerilog Specification
Verification In this phase, we will write Verification Plan
Phase 1 Top
Constructs Phase 2 Environment
Environment class.
Interface Phase 3 Reset
Virtual interface declaration. Phase 4 Packet
OOPS Defining Environment class constructor. Phase 5 Generator
Randomization
Defining required methods for execution . Currently these methods will not be Phase 6 Driver
implemented in this phase. Phase 7 Receiver
Functional Coverage Phase 8 Scoreboard
Assertion All the above are done in Environment .sv file. Phase 9 Coverage
DPI We will write a testcase using the above define environment class in testcase.sv file. Report a Bug or Comment
UVM Tutorial on This section - Your
input is what keeps
VMM Tutorial Environment Class: Testbench.in improving
OVM Tutorial with time!
Easy Labs : SV The class is a base class used to implement verification environments.
Easy Labs : UVM Environment class is extension on vmm_env class.  The testbench simulation needs
some systematic flow like reset, initialize etc. vmm_env base class has methods
Easy Labs : OVM formalize the simulation steps. All methods are declared as virtual methods.
Easy Labs : VMM
We will not implement all the vmm_env virtual methods in this phase but will we print
AVM Switch TB messages from these methods to understand the simulation execution.
VMM Ethernet sample
Testcase contains the instance of the environment class and has access to all the
public declaration of environment class. This testcase Creates a Environment object
and calls the run() method which are defined in the environment class. Run() method
Verilog
runs all the simulation methods which are defined in environment class.
Verification
Verilog Switch TB Verification environment contains the declarations of the virtual interfaces. These
virtual interfaces are pointed to the physical interfaces which are declared in the top
Basic Constructs module.

Constructor method should be declared with virtual interface as arguments, so that


OpenVera when the object is created, in the testcase can pass the interfaces in to environment
Constructs class.
Switch TB
RVM Switch TB
Connecting the virtual interfaces of Environment class to the physical interfaces of
RVM Ethernet sample top module.

Specman E
Interview Questions

http://testbench.in/VL_05_PHASE_2_ENVIRONMENT.html[9/26/2012 2:33:42 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

Extend vmm_env class to define Environment class.

`ifndef GUARD_ENV
`define GUARD_ENV

class Environment extends vmm_env;

endclass

`endif 

Declare virtual interfaces in Environment  class.

  virtual mem_interface.MEM    mem_intf      ;
  virtual input_interface.IP  input_intf     ;
  virtual output_interface.OP output_intf[4] ;

The construction of Environment class is declared with virtual interface as arguments.

function new(virtual mem_interface.MEM    mem_intf_new       ,
             virtual input_interface.IP  input_intf_new     ,
             virtual output_interface.OP output_intf_new[4] );

  super.new("Environment ");

In constructor methods, the interfaces which are arguments are connected to the
virtual interfaces of environment class.

  this.mem_intf      = mem_intf_new    ;
  this.input_intf    = input_intf_new  ;
  this.output_intf   = output_intf_new ;

 `vmm_note(this.log, "Created env object");

Extend all the vmm_env virtual methods. Call the super.<method_name> in all the
vmm_env virtual method extensions.

Include `vmm_note() messages for identifying the simulation steps in the log file.

  virtual function void gen_cfg();
            super.gen_cfg();

http://testbench.in/VL_05_PHASE_2_ENVIRONMENT.html[9/26/2012 2:33:42 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

            `vmm_note(this.log,"Start of gen_cfg() method ");


            `vmm_note(this.log,"End of gen_cfg() method ");
          endfunction
  virtual function void build();
            super.build();
            `vmm_note(this.log,"Start of build() method ");
            `vmm_note(this.log,"End of build() method ");
          endfunction
  ....
  ....
  ....

Do the above for reset_dut(), cfg_dut(), start(), wait_for_end(), stop() cleanup() and
report() methods.

Run :

The run method is called from the testcase to start the simulation. run method calls
all the methods which are defined in the Environment class.

Environment Class Source Code:

`ifndef GUARD_ENV
`define GUARD_ENV

class Environment extends vmm_env;

  virtual mem_interface.MEM    mem_intf      ;
  virtual input_interface.IP  input_intf     ;
  virtual output_interface.OP output_intf[4] ;

function new(virtual mem_interface.MEM    mem_intf_new       ,
             virtual input_interface.IP  input_intf_new     ,
             virtual output_interface.OP output_intf_new[4] );

http://testbench.in/VL_05_PHASE_2_ENVIRONMENT.html[9/26/2012 2:33:42 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

  super.new("Environment ");
  this.mem_intf      = mem_intf_new    ;
  this.input_intf    = input_intf_new  ;
  this.output_intf   = output_intf_new ;
  
  `vmm_note(this.log, "Created env object");
endfunction : new

  virtual function void gen_cfg();
            super.gen_cfg();
            `vmm_note(this.log,"Start of gen_cfg() method ");
            `vmm_note(this.log,"End of gen_cfg() method ");
          endfunction

  virtual function void build();
            super.build();
            `vmm_note(this.log,"Start of build() method ");
            `vmm_note(this.log,"End of build() method ");
          endfunction

  virtual task reset_dut();
            super.reset_dut();
            `vmm_note(this.log,"Start of reset_dut() method ");
            `vmm_note(this.log,"End of reset_dut() method ");
          endtask

  virtual task cfg_dut();
            super.cfg_dut();
            `vmm_note(this.log,"Start of cfg_dut() method ");
            `vmm_note(this.log,"End of cfg_dut() method ");
          endtask

  virtual task start();
            super.start();
            `vmm_note(this.log,"Start of start() method ");
            `vmm_note(this.log,"End of start() method ");
          endtask

  virtual task wait_for_end();
            super.wait_for_end();
            `vmm_note(this.log,"Start of  wait_for_end() method ");
            `vmm_note(this.log,"End of  wait_for_end() method ");
          endtask

  virtual task stop();
            super.stop();
            `vmm_note(this.log,"Start of stop() method ");
            `vmm_note(this.log,"End of stop() method ");
          endtask

  virtual task cleanup();
            super.cleanup();
            `vmm_note(this.log,"Start of cleanup() method ");
            `vmm_note(this.log,"End of cleanup() method ");
          endtask

  virtual task report();
            `vmm_note(this.log,"Start of report() method \n\n\n");
            $display("---------------------------------------------------------------------");
            super.report();
            $display("---------------------------------------------------------------------");
             $display("\n\n");
            `vmm_note(this.log,"End of report() method");
          endtask

endclass
`endif 

We will create a file Global.sv for global requirement. In this file,  define all the port
address as macros in this file.

http://testbench.in/VL_05_PHASE_2_ENVIRONMENT.html[9/26/2012 2:33:42 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

`ifndef GUARD_GLOBALS
`define GUARD_GLOBALS

`define P0 8'h00
`define P1 8'h11
`define P2 8'h22
`define P3 8'h33

`endif

Now We will update the testcase. Take an instance of the Environment class and call
the run method of the Environment class.

`ifndef GUARD_TESTCASE
`define GUARD_TESTCASE

program testcase(mem_interface.MEM mem_intf,input_interface.IP


input_intf,output_interface.OP output_intf[4]);

`include "vmm.sv"

Environment env;

initial
begin
$display(" ******************* Start of testcase ****************");

env = new(mem_intf,input_intf,output_intf);
env.run();

end

final
$display(" ******************** End of testcase *****************");

endprogram
`endif

Download the phase 2 source code:

vmm_switch_2.tar
Browse the code in vmm_switch_2.tar

Run the simulation:


vcs -sverilog -f filelist -R -ntb_opts rvm

Log report after the simulation:

 ******************* Start of testcase ****************


Normal[NOTE] on Environment() at                    0:
    Created env object
Normal[NOTE] on Environment() at                    0:
    Start of gen_cfg() method
Normal[NOTE] on Environment() at                    0:
    End of gen_cfg() method
Normal[NOTE] on Environment() at                    0:
    Start of build() method
Normal[NOTE] on Environment() at                    0:
    End of build() method
Normal[NOTE] on Environment() at                    0:
    Start of reset_dut() method
Normal[NOTE] on Environment() at                    0:
    End of reset_dut() method
Normal[NOTE] on Environment() at                    0:
    Start of cfg_dut() method
Normal[NOTE] on Environment() at                    0:
    End of cfg_dut() method
Normal[NOTE] on Environment() at                    0:
    Start of start() method
Normal[NOTE] on Environment() at                    0:
    End of start() method

http://testbench.in/VL_05_PHASE_2_ENVIRONMENT.html[9/26/2012 2:33:42 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

Normal[NOTE] on Environment() at                    0:


    Start of  wait_for_end() method
Normal[NOTE] on Environment() at                    0:
    End of  wait_for_end() method
Normal[NOTE] on Environment() at                    0:
    Start of stop() method
Normal[NOTE] on Environment() at                    0:
    End of stop() method
Normal[NOTE] on Environment() at                    0:
    Start of cleanup() method
Normal[NOTE] on Environment() at                    0:
    End of cleanup() method
Normal[NOTE] on Environment() at                    0:
    Start of report() method
    
    
    
---------------------------------------------------------------------
Simulation PASSED on /./ (/./) at                    0 (0 warnings, 0 demoted errors & 0
demoted warnings)
---------------------------------------------------------------------

Normal[NOTE] on Environment() at                    0:


    End of report() method
 ******************** End of testcase *****************

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/VL_05_PHASE_2_ENVIRONMENT.html[9/26/2012 2:33:42 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PHASE 3 RESET Index


Introduction
SystemVerilog Specification
Verification In this phase we will reset and configure the DUT. Verification Plan
Phase 1 Top
Constructs The Environment class has reset_dut() method which contains the logic to reset the Phase 2 Environment
Interface DUT and cfg_dut() method which contains the logic to configure the DUT port address. Phase 3 Reset
Phase 4 Packet
OOPS Phase 5 Generator
Randomization Phase 6 Driver
Phase 7 Receiver
Functional Coverage Phase 8 Scoreboard
Assertion Phase 9 Coverage
DPI Report a Bug or Comment
UVM Tutorial on This section - Your
input is what keeps
VMM Tutorial
Testbench.in improving
OVM Tutorial with time!
Easy Labs : SV
Easy Labs : UVM
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

Verilog NOTE: Clocking block signals can be driven only using a non-blocking assignment.
Verification
Verilog Switch TB
In reset_dut() method.
Basic Constructs 1) Set all the DUT input signals to a known state. And reset the DUT.

OpenVera   virtual task reset_dut();


            super.reset_dut();
Constructs
            `vmm_note(this.log,"Start of reset_dut() method ");
Switch TB
              mem_intf.cb.mem_data      <= 0;
RVM Switch TB
              mem_intf.cb.mem_add       <= 0;
RVM Ethernet sample               mem_intf.cb.mem_en        <= 0;
              mem_intf.cb.mem_rd_wr     <= 0;
              input_intf.cb.data_in     <= 0;
              input_intf.cb.data_status <= 0;
Specman E
              output_intf[0].cb.read    <= 0;
Interview Questions               output_intf[1].cb.read    <= 0;
              output_intf[2].cb.read    <= 0;
              output_intf[3].cb.read    <= 0;
              
              // Reset the DUT
              input_intf.reset       <= 1;
              repeat (4) @ input_intf.clock;
              input_intf.reset       <= 0;

            `vmm_note(this.log,"End of reset_dut() method ");


endtask

http://testbench.in/VL_06_PHASE_3_RESET.html[9/26/2012 2:33:52 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

2) Updated the cfg_dut method.

virtual task cfg_dut();


            super.cfg_dut();
            `vmm_note(this.log,"Start of cfg_dut() method ");

            mem_intf.cb.mem_en <= 1;
            @(posedge mem_intf.clock);
            mem_intf.cb.mem_rd_wr <= 1;
            
            @(posedge mem_intf.clock);
            mem_intf.cb.mem_add  <= 8'h0;
            mem_intf.cb.mem_data <= `P0;
            `vmm_note(this.log ,$psprintf(" Port 0 Address %h ",`P0));
            
            @(posedge mem_intf.clock);
            mem_intf.cb.mem_add  <= 8'h1;
            mem_intf.cb.mem_data <= `P1;
            `vmm_note(this.log ,$psprintf(" Port 1 Address %h ",`P1));
            
            @(posedge mem_intf.clock);
            mem_intf.cb.mem_add  <= 8'h2;
            mem_intf.cb.mem_data <= `P2;
            `vmm_note(this.log ,$psprintf(" Port 2 Address %h ",`P2));
            
            @(posedge mem_intf.clock);
            mem_intf.cb.mem_add  <= 8'h3;
            mem_intf.cb.mem_data <= `P3;
            `vmm_note(this.log ,$psprintf(" Port 3 Address %h ",`P3));
            
            @(posedge mem_intf.clock);
            mem_intf.cb.mem_en    <=0;
            mem_intf.cb.mem_rd_wr <= 0;
            mem_intf.cb.mem_add   <= 0;
            mem_intf.cb.mem_data  <= 0;

            `vmm_note(this.log,"End of cfg_dut() method ");


endtask

(3) In wait_for_end method, wait for some clock cycles.

  repeat(10000) @(input_intf.clock);

Download the Phase 3 source code:

vmm_switch_3.tar
Browse the code in vmm_switch_3.tar

Run the simulation:


vcs -sverilog -f filelist -R -ntb_opts rvm

Log File report

 ******************* Start of testcase ****************


Normal[NOTE] on Environment() at                    0:
    Created env object
Normal[NOTE] on Environment() at                    0:
    Start of gen_cfg() method
Normal[NOTE] on Environment() at                    0:
    End of gen_cfg() method
Normal[NOTE] on Environment() at                    0:
    Start of build() method
Normal[NOTE] on Environment() at                    0:
    End of build() method
Normal[NOTE] on Environment() at                    0:

http://testbench.in/VL_06_PHASE_3_RESET.html[9/26/2012 2:33:52 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

    Start of reset_dut() method


Normal[NOTE] on Environment() at                   60:
    End of reset_dut() method
Normal[NOTE] on Environment() at                   60:
    Start of cfg_dut() method
Normal[NOTE] on Environment() at                   90:
     Port 0 Address 00
Normal[NOTE] on Environment() at                  110:
     Port 1 Address 11
Normal[NOTE] on Environment() at                  130:
     Port 2 Address 22
Normal[NOTE] on Environment() at                  150:
     Port 3 Address 33
Normal[NOTE] on Environment() at                  170:
    End of cfg_dut() method
Normal[NOTE] on Environment() at                  170:
    Start of start() method
Normal[NOTE] on Environment() at                  170:
    End of start() method
Normal[NOTE] on Environment() at                  170:
    Start of  wait_for_end() method
Normal[NOTE] on Environment() at               100170:
    End of  wait_for_end() method
Normal[NOTE] on Environment() at               100170:
    Start of stop() method
Normal[NOTE] on Environment() at               100170:
    End of stop() method
Normal[NOTE] on Environment() at               100170:
    Start of cleanup() method
Normal[NOTE] on Environment() at               100170:
    End of cleanup() method
Normal[NOTE] on Environment() at               100170:
    Start of report() method
    
    
    
---------------------------------------------------------------------
Simulation PASSED on /./ (/./) at               100170 (0 warnings, 0 demoted errors & 0
demoted warnings)
---------------------------------------------------------------------

Normal[NOTE] on Environment() at               100170:


    End of report() method
 ******************** End of testcase *****************

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/VL_06_PHASE_3_RESET.html[9/26/2012 2:33:52 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PHASE 4 PACKET Index


Introduction
SystemVerilog Specification
Verification In this Phase , We will define a packet and then test it whether it is generating as Verification Plan
expected. Phase 1 Top
Constructs Phase 2 Environment
Interface Packet is modeled using class. Packet class should be able to generate all possible Phase 3 Reset
packet types randomly. Packet class should also implement allocate(), psdisplay(), Phase 4 Packet
OOPS Phase 5 Generator
copy(), compare(), byte_pack() and byte_unpack()  of vmm_data methods.
Randomization Phase 6 Driver
Using vmm macros, we will create atomic generator and channel for Packet. Phase 7 Receiver
Functional Coverage Phase 8 Scoreboard
Assertion We will write the packet class in Packet.sv file. Packet class variables and constraints Phase 9 Coverage
DPI have been derived from stimulus generation plan.
Report a Bug or Comment
UVM Tutorial Revisit Stimulus Generation Plan on This section - Your
1) Packet DA: Generate packet DA with the configured address. input is what keeps
VMM Tutorial
2) Payload length: generate payload length ranging from 2 to 255. Testbench.in improving
OVM Tutorial 3) Correct or Incorrect Length field. with time!
Easy Labs : SV 4) Generate good and bad FCS.
Easy Labs : UVM
Easy Labs : OVM
1) Declare FCS types as enumerated data types. Name members as GOOD_FCS and
Easy Labs : VMM BAD_FCS.
AVM Switch TB
typedef enum { GOOD_FCS, BAD_FCS } fcs_kind_t;
VMM Ethernet sample
2) Declare the length type as enumerated data type. Name members as
GOOD_LENGTH and BAD_LENGTH.
Verilog
Verification typedef enum { GOOD_LENGTH, BAD_LENGTH } length_kind_t;
Verilog Switch TB 3) Extend vmm_data class to define Paclet class.
Basic Constructs
class Packet extends vmm_data;

4) Declare a vmm_log object and construct it.


OpenVera
Constructs static vmm_log log = new("Packet","Class");
Switch TB
5) Declare the length type and fcs type variables as rand.
RVM Switch TB
RVM Ethernet sample rand fcs_kind_t     fcs_kind;
rand length_kind_t  length_kind;

6) Declare the packet field as rand. All fields are bit data types. All fields are 8 bit
Specman E packet array. Declare the payload as dynamic array.
Interview Questions
rand bit [7:0] length;
rand bit [7:0] da;
rand bit [7:0] sa;
rand bit [7:0] data[];//Payload using Dynamic array,size is generated on the fly
rand byte fcs;

7) Constraint the DA field to be any one of the configured address.

constraint address_c { da inside {`P0,`P1,`P2,`P3} ; }

http://testbench.in/VL_07_PHASE_4_PACKET.html[9/26/2012 2:34:03 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

8) Constrain the payload dynamic array size to between 1 to 255.

constraint payload_size_c { data.size inside { [1 : 255]};}

9) Constrain the payload length to the length field based on the length type.

constraint length_kind_c { 
   (length_kind == GOOD_LENGTH) -> length == data.size; 
   (length_kind == BAD_LENGTH)  -> length == data.size + 2 ; }

Use solve before to direct the randomization to generate first the payload dynamic
array size and then randomize length field.

constraint solve_size_length { solve  data.size before length; }

10) Define a port_randomize method. In this method calculate the fcs based on the
fcs_kind.

function void post_randomize();
     if(fcs_kind == GOOD_FCS)
         fcs = 8'b0;
     else
        fcs = 8'b1;
     fcs = cal_fcs();
endfunction : post_randomize

11) Define the FCS method.

virtual function byte cal_fcs;
  integer i;
  byte result ;
  result = 0;
  result = result ^ da;
  result = result ^ sa;
  result = result ^ length;
  for (i = 0;i< data.size;i++)
  result = result ^ data[i];
  result = fcs ^ result;
  return result;
endfunction : cal_fcs

12) Define acllocate() method.

virtual function vmm_data allocate();
     Packet pkt;
     pkt = new();
     return pkt;
endfunction:allocate

13) Define psdisplay() method. psdisplay() method displays the current value of the
packet fields to a string.

virtual function string psdisplay(string prefix = "");
    int i;
 
    $write(psdisplay, "   %s   packet
#%0d.%0d.%0d\n", prefix,this.stream_id, this.scenario_id, this.data_id);
    $write(psdisplay, "   %s%s   da:0x%h\n", psdisplay, prefix,this.da);
    $write(psdisplay, "   %s%s   sa:0x%h\n", psdisplay, prefix,this.sa);
    $write(psdisplay, "   %s%s   length:0x%h
(data.size=%0d)\n", psdisplay, prefix,this.length,this.data.size());
    $write(psdisplay, "   %s%s   data[%0d]:0x%h", psdisplay, prefix,0,data[0]);
    if(data.size() > 1)
        $write(psdisplay, "   data[%0d]:0x%h", 1,data[1]);
    if(data.size() > 4)
        $write(psdisplay, "  ....  ");
    if(data.size() > 2)

http://testbench.in/VL_07_PHASE_4_PACKET.html[9/26/2012 2:34:03 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

        $write(psdisplay, "   data[%0d]:0x%h", data.size() -2,data[data.size() -2]);
    if(data.size() > 3)
        $write(psdisplay, "   data[%0d]:0x%h", data.size() -1,data[data.size() -1]);
    $write(psdisplay, "\n   %s%s   fcs:0x%h \n", psdisplay, prefix, this.fcs);
    
 endfunction

14) Define copy() method. copy() method copies the current values of the object
instance.

virtual function vmm_data copy(vmm_data to = null);


    Packet cpy;
 
    // Copying to a new instance?
    if (to == null) 
       cpy = new;
     else
 
    // Copying to an existing instance. Correct type?
    if (!$cast(cpy, to))    
       begin
       `vmm_fatal(this.log, "Attempting to copy to a non packet instance");
       copy = null;
       return copy;
       end
    
 
    super.copy_data(cpy);
    
    cpy.da = this.da;
    cpy.sa = this.sa;
    cpy.length = this.length;
    cpy.data = new[this.data.size()];
    foreach(data[i])
        begin
       cpy.data[i] = this.data[i];
        end                    
    cpy.fcs = this.fcs;
    copy = cpy;
 endfunction:copy

15) Define Compare() method. Compares the current value of the object instance with
the specified object instance.
If the value is different, FALSE is returned.

virtual function bit compare(input vmm_data   to,output string diff,input int   kind


= -1);
    Packet cmp;
 
    compare = 1; // Assume success by default.
    diff    = "No differences found";
    
    if (!$cast(cmp, to)) 
    begin
       `vmm_fatal(this.log, "Attempting to compare to a non packet instance");
       compare = 0;
       diff = "Cannot compare non packets";
       return compare;
     end 
 
    // data types are the same, do comparison:
    if (this.da != cmp.da) 
    begin
       diff = $psprintf("Different DA values: %b != %b", this.da, cmp.da);
       compare = 0;
       return compare;
    end 
      
    if (this.sa != cmp.sa) 
    begin
       diff = $psprintf("Different SA values: %b != %b", this.sa, cmp.sa);
       compare = 0;
       return compare;
    end 

http://testbench.in/VL_07_PHASE_4_PACKET.html[9/26/2012 2:34:03 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

    if (this.length != cmp.length) 
    begin
       diff = $psprintf("Different LEN values: %b != %b", this.length, cmp.length);
       compare = 0;
       return compare;
    end 
 
    foreach(data[i]) 
       if (this.data[i] != cmp.data[i]) 
       begin
          diff = $psprintf("Different data[%0d] values: 0x%h !=
0x%h",i, this.data[i], cmp.data[i]);
          compare = 0;
          return compare;
       end 
    if (this.fcs != cmp.fcs) 
    begin
       diff = $psprintf("Different FCS values: %b != %b", this.fcs, cmp.fcs);
       compare = 0;
       return compare;
    end 
 endfunction:compare

16)Define byte_pack() method().

Packing is commonly used to convert the high level data to low level data that can be
applied to DUT.  In packet class various fields are generated. Required fields are
concatenated to form a stream of bytes which can be driven conveniently to DUT
interface by the driver.

virtual function int unsigned byte_pack(
                     ref logic [7:0] bytes[],
                     input int unsigned offset =0 ,
                     input int   kind = -1);
      byte_pack = 0;
      bytes = new[this.data.size() + 4];
      bytes[0] = this.da;
      bytes[1] = this.sa;
      bytes[2] = this.length;

      foreach(data[i])
          bytes[3+i] = data[i];

      bytes[this.data.size() + 3 ] = fcs;
      byte_pack = this.data.size() + 4;
endfunction:byte_pack  

17) Define byte_unpack() method:

http://testbench.in/VL_07_PHASE_4_PACKET.html[9/26/2012 2:34:03 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

The unpack() method does exactly the opposite of pack method. Unpacking is
commonly used to convert a data stream coming from DUT to high level data packet
object.

virtual function int unsigned byte_unpack(
                     const ref logic [7:0] bytes[],
                     input int unsigned offset = 0,
                     input int len = -1,
                     input int kind = -1);
      this.da = bytes[0];
      this.sa = bytes[1];
      this.length = bytes[2];
      this.fcs = bytes[bytes.size() -1];
      this.data = new[bytes.size() - 4];
      foreach(data[i])
      this.data[i] = bytes[i+3];
      return bytes.size();
endfunction:byte_unpack

18) Define Packet_channel for Packet using macro.

`vmm_channel(Packet)

19) Define Packet_atomic_gen for generating Packet instances using macro.

`vmm_atomic_gen(Packet, "Packet Gen")

Packet Class Source Code

`ifndef GUARD_PACKET
`define GUARD_PACKET

//Define the enumerated types for packet types


typedef enum { GOOD_FCS, BAD_FCS } fcs_kind_t;
typedef enum { GOOD_LENGTH, BAD_LENGTH } length_kind_t;

class Packet extends vmm_data;

static vmm_log log = new("Packet","Class");

rand fcs_kind_t     fcs_kind;
rand length_kind_t  length_kind;

rand bit [7:0] length;
rand bit [7:0] da;
rand bit [7:0] sa;
rand bit [7:0] data[];//Payload using Dynamic array,size is generated on the fly
rand byte fcs;

constraint address_c { da inside {`P0,`P1,`P2,`P3} ; }

constraint payload_size_c { data.size inside { [1 : 255};}

http://testbench.in/VL_07_PHASE_4_PACKET.html[9/26/2012 2:34:03 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

constraint length_kind_c { 
     (length_kind == GOOD_LENGTH) -> length == data.size; 
     (length_kind == BAD_LENGTH)  -> length == data.size + 2 ; }
                
constraint solve_size_length { solve  data.size before length; }

function new();
     super.new(this.log);
endfunction:new

function void post_randomize();
     if(fcs_kind == GOOD_FCS)
         fcs = 8'b0;
     else
        fcs = 8'b1;
     fcs = cal_fcs();
endfunction : post_randomize

///// method to calculate the fcs /////


virtual function byte cal_fcs;
     integer i;
     byte result ;
     result = 0;
     result = result ^ da;
     result = result ^ sa;
     result = result ^ length;
     for (i = 0;i< data.size;i++)
     result = result ^ data[i];
     result = fcs ^ result;
     return result;
endfunction : cal_fcs

virtual function vmm_data allocate();
     Packet pkt;
     pkt = new();
     return pkt;
endfunction:allocate

virtual function string psdisplay(string prefix = "");
    int i;
 
    $write(psdisplay, "   %s   packet
#%0d.%0d.%0d\n", prefix,this.stream_id, this.scenario_id, this.data_id);
    $write(psdisplay, "   %s%s   da:0x%h\n", psdisplay, prefix,this.da);
    $write(psdisplay, "   %s%s   sa:0x%h\n", psdisplay, prefix,this.sa);
    $write(psdisplay, "   %s%s   length:0x%h
(data.size=%0d)\n", psdisplay, prefix,this.length,this.data.size());
    $write(psdisplay, "   %s%s   data[%0d]:0x%h", psdisplay, prefix,0,data[0]);
    if(data.size() > 1)
        $write(psdisplay, "   data[%0d]:0x%h", 1,data[1]);
    if(data.size() > 4)
        $write(psdisplay, "  ....  ");
    if(data.size() > 2)
        $write(psdisplay, "   data[%0d]:0x%h", data.size() -2,data[data.size() -2]);
    if(data.size() > 3)
        $write(psdisplay, "   data[%0d]:0x%h", data.size() -1,data[data.size() -1]);
    $write(psdisplay, "\n   %s%s   fcs:0x%h \n", psdisplay, prefix, this.fcs);
    
 endfunction
 
 
virtual function vmm_data copy(vmm_data to = null);
    Packet cpy;
 
    // Copying to a new instance?
    if (to == null) 
       cpy = new;
     else
 
    // Copying to an existing instance. Correct type?
    if (!$cast(cpy, to))    
       begin
       `vmm_fatal(this.log, "Attempting to copy to a non packet instance");
       copy = null;

http://testbench.in/VL_07_PHASE_4_PACKET.html[9/26/2012 2:34:03 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

       return copy;
       end
    
 
    super.copy_data(cpy);
    
    cpy.da = this.da;
    cpy.sa = this.sa;
    cpy.length = this.length;
    cpy.data = new[this.data.size()];
    foreach(data[i])
        begin
       cpy.data[i] = this.data[i];
        end                    
    cpy.fcs = this.fcs;
    copy = cpy;
 endfunction:copy
 
 
 
virtual function bit compare(input vmm_data   to,output string diff,input int   kind
= -1);
    Packet cmp;
 
    compare = 1; // Assume success by default.
    diff    = "No differences found";
    
    if (!$cast(cmp, to)) 
    begin
       `vmm_fatal(this.log, "Attempting to compare to a non packet instance");
       compare = 0;
       diff = "Cannot compare non packets";
       return compare;
     end 
 
    // data types are the same, do comparison:
    if (this.da != cmp.da) 
    begin
       diff = $psprintf("Different DA values: %b != %b", this.da, cmp.da);
       compare = 0;
       return compare;
    end 
      
    if (this.sa != cmp.sa) 
    begin
       diff = $psprintf("Different SA values: %b != %b", this.sa, cmp.sa);
       compare = 0;
       return compare;
    end 
    if (this.length != cmp.length) 
    begin
       diff = $psprintf("Different LEN values: %b != %b", this.length, cmp.length);
       compare = 0;
       return compare;
    end 
 
    foreach(data[i]) 
       if (this.data[i] != cmp.data[i]) 
       begin
          diff = $psprintf("Different data[%0d] values: 0x%h !=
0x%h",i, this.data[i], cmp.data[i]);
          compare = 0;
          return compare;
       end 
    if (this.fcs != cmp.fcs) 
    begin
       diff = $psprintf("Different FCS values: %b != %b", this.fcs, cmp.fcs);
       compare = 0;
       return compare;
    end 
 endfunction:compare

virtual function int unsigned byte_pack(
                     ref logic [7:0] bytes[],

http://testbench.in/VL_07_PHASE_4_PACKET.html[9/26/2012 2:34:03 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

                     input int unsigned offset =0 ,


                     input int   kind = -1);
      byte_pack = 0;
      bytes = new[this.data.size() + 4];
      bytes[0] = this.da;
      bytes[1] = this.sa;
      bytes[2] = this.length;

      foreach(data[i])
          bytes[3+i] = data[i];

      bytes[this.data.size() + 3 ] = fcs;
      byte_pack = this.data.size() + 4;
endfunction:byte_pack    

virtual function int unsigned byte_unpack(
                     const ref logic [7:0] bytes[],
                     input int unsigned offset = 0,
                     input int len = -1,
                     input int kind = -1);
      this.da = bytes[0];
      this.sa = bytes[1];
      this.length = bytes[2];
      this.fcs = bytes[bytes.size() -1];
      this.data = new[bytes.size() - 4];
      foreach(data[i])
      this.data[i] = bytes[i+3];
      return bytes.size();
endfunction:byte_unpack

endclass

/////////////////////////////////////////////////////////
//// Create vmm_channel and vmm_atomic_gen for packet////
/////////////////////////////////////////////////////////
`vmm_channel(Packet)
`vmm_atomic_gen(Packet, "Packet Gen")

Now we will write a small program to test our packet implantation. This program
block is not used to verify the DUT.

Write a simple program block and do the instance of packet class. Randomize the
packet and call the display method to analyze the generation. Then pack the packet
in to bytes and then unpack bytes and then call compare method to check all the
methods.

Program Block Source Code

program test;

packet pkt1 = new();


packet pkt2 = new();
logic [7:0] bytes[];
initial
repeat(10)
if(pkt1.randomize)
begin
$display(" Randomization Successes full.");
pkt1.display();
void'(pkt1.byte_pack(bytes));
pkt2 = new();
pkt2.byte_unpack(bytes);
if(pkt2.compare(pkt1))
$display(" Packing, Unpacking and compare worked");
else
$display(" *** Something went wrong in Packing or Unpacking or compare ***");

end
else
$display(" *** Randomization Failed ***");

http://testbench.in/VL_07_PHASE_4_PACKET.html[9/26/2012 2:34:03 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

endprogram

Download the packet class with program block.

vmm_switch_4.tar
Browse the code in vmm_switch_4.tar

Run the simulation


vcs -sverilog -f filelist -R -ntb_opts rvm

Log file report:

 Randomization Sucessesfull.
   Pkt1   packet #0.0.0
   Pkt1   da:0x00
   Pkt1   sa:0x40
   Pkt1   length:0xbe (data.size=190)
   Pkt1   data[0]:0xf7   data[1]:0xa6  ....     data[188]:0x49   data[189]:0x79
   Pkt1   fcs:0x1a

   Pkt2   packet #0.0.0


   Pkt2   da:0x00
   Pkt2   sa:0x40
   Pkt2   length:0xbe (data.size=190)
   Pkt2   data[0]:0xf7   data[1]:0xa6  ....     data[188]:0x49   data[189]:0x79
   Pkt2   fcs:0x1a

 Packing,Unpacking and compare worked


 Randomization Sucessesfull.
   Pkt1   packet #0.0.0
   Pkt1   da:0x33
   Pkt1   sa:0xfd
   Pkt1   length:0xc7 (data.size=199)
   Pkt1   data[0]:0x1e   data[1]:0x80  ....     data[197]:0x15   data[198]:0x30
   Pkt1   fcs:0xa5

   Pkt2   packet #0.0.0


   Pkt2   da:0x33
   Pkt2   sa:0xfd
   Pkt2   length:0xc7 (data.size=199)
   Pkt2   data[0]:0x1e   data[1]:0x80  ....     data[197]:0x15   data[198]:0x30
   Pkt2   fcs:0xa5

 Packing,Unpacking and compare worked


 Randomization Sucessesfull.
   Pkt1   packet #0.0.0
   Pkt1   da:0x00
   Pkt1   sa:0xa6
   Pkt1   length:0x9b (data.size=155)
   Pkt1   data[0]:0x72   data[1]:0x9f  ....     data[153]:0x53   data[154]:0x4b
   Pkt1   fcs:0x24

   Pkt2   packet #0.0.0


   Pkt2   da:0x00
   Pkt2   sa:0xa6
   Pkt2   length:0x9b (data.size=155)
   Pkt2   data[0]:0x72   data[1]:0x9f  ....     data[153]:0x53   data[154]:0x4b
   Pkt2   fcs:0x24
..........
..........
..........

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/VL_07_PHASE_4_PACKET.html[9/26/2012 2:34:03 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/VL_07_PHASE_4_PACKET.html[9/26/2012 2:34:03 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PHASE 5 GENERATOR Index


Introduction
SystemVerilog Specification
Verification In This phase, we will the usage of vmm atomic generator.  In phase 4, Verification Plan
using`vmm_atomic_gen macro we defined Packet_atomic_gen. Phase 1 Top
Constructs Phase 2 Environment
Interface In Environment class, we will create an instance of  Packet_atomic_gen, and connect Phase 3 Reset
it to the instance of Packet_channel, i.e gen2drvr_chan. The Packet_channel instance Phase 4 Packet
OOPS Phase 5 Generator
gen2drvr_chan will be used to connect the atomic generator to the driver
Randomization instance.  We will also configure the atomic generator to generate 10 instances of Phase 6 Driver
packet. Phase 7 Receiver
Functional Coverage Phase 8 Scoreboard
Assertion Phase 9 Coverage
DPI Report a Bug or Comment
UVM Tutorial on This section - Your
input is what keeps
VMM Tutorial
Testbench.in improving
OVM Tutorial with time!
Easy Labs : SV
Easy Labs : UVM
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

Verilog
Verification 1) In Environment class, declare a Packet_atomic_gen instance.
Verilog Switch TB
     Packet_atomic_gen atomic_gen;
Basic Constructs
2) Declare a Packet_channel instance.

OpenVera      Packet_channel gen2drvr_chan;


Constructs
3) Construct the gen2drvr_chan in build() method.
Switch TB
RVM Switch TB
     gen2drvr_chan = new("gen2drvr","chan");

RVM Ethernet sample 4) Construct the atomic_gen in build() method.

     atomic_gen = new("atomic_gen",0,gen2drvr_chan);


Specman E
5) Configure the atomic_gen to generate 10 instances.
Interview Questions
     atomic_gen.stop_after_n_insts = 10;

6) In start() method, start the atomic_gen.

     atomic_gen.start_xactor();

7) In stop() method, call the stop_xactor() method of atomic_gen.

     atomic_gen.stop_xactor();

http://testbench.in/VL_08_PHASE_5_GENERATOR.html[9/26/2012 2:34:13 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

Environment Class Source Code:

`ifndef GUARD_ENV
`define GUARD_ENV

class Environment extends vmm_env;

  virtual mem_interface.MEM    mem_intf      ;
  virtual input_interface.IP  input_intf     ;
  virtual output_interface.OP output_intf[4] ;

  Packet_atomic_gen atomic_gen;
  Packet_channel gen2drvr_chan;

function new(virtual mem_interface.MEM    mem_intf_new       ,


             virtual input_interface.IP  input_intf_new     ,
             virtual output_interface.OP output_intf_new[4] );
  super.new("Environment ");
  this.mem_intf      = mem_intf_new    ;
  this.input_intf    = input_intf_new  ;
  this.output_intf   = output_intf_new ;
  
  `vmm_note(this.log, "Created env object");
endfunction : new

  virtual function void gen_cfg();


            super.gen_cfg();
            `vmm_note(this.log,"Start of gen_cfg() method ");
            `vmm_note(this.log,"End of gen_cfg() method ");
          endfunction
  virtual function void build();
            super.build();
            `vmm_note(this.log,"Start of build() method ");

            gen2drvr_chan = new("gen2drvr","chan");
            atomic_gen = new("atomic_gen",0,gen2drvr_chan);
            atomic_gen.stop_after_n_insts = 10;

           `vmm_note(this.log,"End of build() method ");


          endfunction

  virtual task reset_dut();


            super.reset_dut();
            `vmm_note(this.log,"Start of reset_dut() method ");
              mem_intf.cb.mem_data      <= 0;
              mem_intf.cb.mem_add       <= 0;
              mem_intf.cb.mem_en        <= 0;
              mem_intf.cb.mem_rd_wr     <= 0;
              input_intf.cb.data_in     <= 0;
              input_intf.cb.data_status <= 0;
              output_intf[0].cb.read    <= 0;
              output_intf[1].cb.read    <= 0;
              output_intf[2].cb.read    <= 0;
              output_intf[3].cb.read    <= 0;
              
              // Reset the DUT
              input_intf.reset       <= 1;
              repeat (4) @ input_intf.clock;
              input_intf.reset       <= 0;

            `vmm_note(this.log,"End of reset_dut() method ");


          endtask

  virtual task cfg_dut();


            super.cfg_dut();
            `vmm_note(this.log,"Start of cfg_dut() method ");
            mem_intf.cb.mem_en <= 1;
            @(posedge mem_intf.clock);

http://testbench.in/VL_08_PHASE_5_GENERATOR.html[9/26/2012 2:34:13 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

            mem_intf.cb.mem_rd_wr <= 1;
            
            @(posedge mem_intf.clock);
            mem_intf.cb.mem_add  <= 8'h0;
            mem_intf.cb.mem_data <= `P0;
            `vmm_note(this.log ,$psprintf(" Port 0 Address %h ",`P0));
            
            @(posedge mem_intf.clock);
            mem_intf.cb.mem_add  <= 8'h1;
            mem_intf.cb.mem_data <= `P1;
            `vmm_note(this.log ,$psprintf(" Port 1 Address %h ",`P1));
            
            @(posedge mem_intf.clock);
            mem_intf.cb.mem_add  <= 8'h2;
            mem_intf.cb.mem_data <= `P2;
            `vmm_note(this.log ,$psprintf(" Port 2 Address %h ",`P2));
            
            @(posedge mem_intf.clock);
            mem_intf.cb.mem_add  <= 8'h3;
            mem_intf.cb.mem_data <= `P3;
            `vmm_note(this.log ,$psprintf(" Port 3 Address %h ",`P3));
            
            @(posedge mem_intf.clock);
            mem_intf.cb.mem_en    <=0;
            mem_intf.cb.mem_rd_wr <= 0;
            mem_intf.cb.mem_add   <= 0;
            mem_intf.cb.mem_data  <= 0;

            `vmm_note(this.log,"End of cfg_dut() method ");


          endtask

  virtual task start();


            super.start();
            `vmm_note(this.log,"Start of start() method ");

            atomic_gen.start_xactor();

            `vmm_note(this.log,"End of start() method ");


          endtask

  virtual task wait_for_end();


            super.wait_for_end();
            `vmm_note(this.log,"Start of  wait_for_end() method ");
             repeat(1000) @(input_intf.clock);
            `vmm_note(this.log,"End of  wait_for_end() method ");
          endtask

  virtual task stop();


            super.stop();
            `vmm_note(this.log,"Start of stop() method ");

            atomic_gen.stop_xactor();

            `vmm_note(this.log,"End of stop() method ");


          endtask

  virtual task cleanup();


            super.cleanup();
            `vmm_note(this.log,"Start of cleanup() method ");
            `vmm_note(this.log,"End of cleanup() method ");
          endtask

  virtual task report();


            `vmm_note(this.log,"Start of report() method \n\n\n");
            $display("---------------------------------------------------------------------");
            super.report();
            $display("---------------------------------------------------------------------");
             $display("\n\n");
            `vmm_note(this.log,"End of report() method");
          endtask

endclass
`endif

http://testbench.in/VL_08_PHASE_5_GENERATOR.html[9/26/2012 2:34:13 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

Download the phase 5 source code.

vmm_switch_5.tar
Browse the code in vmm_switch_5.tar

Run the simulation


vcs -sverilog -f filelist -R -ntb_opts rvm

Log file report:

 ******************* Start of testcase ****************


Normal[NOTE] on Environment() at                    0:
    Created env object
Normal[NOTE] on Environment() at                    0:
    Start of gen_cfg() method
Normal[NOTE] on Environment() at                    0:
    End of gen_cfg() method
Normal[NOTE] on Environment() at                    0:
    Start of build() method
Normal[NOTE] on Environment() at                    0:
    End of build() method
Normal[NOTE] on Environment() at                    0:
    Start of reset_dut() method
Normal[NOTE] on Environemnt() at                   60:
    End of reset_dut() method
Normal[NOTE] on Environemnt() at                   60:
    Start of cfg_dut() method
Normal[NOTE] on Environemnt() at                   90:
     Port 0 Address 00
Normal[NOTE] on Environemnt() at                  110:
     Port 1 Address 11
Normal[NOTE] on Environemnt() at                  130:
     Port 2 Address 22
Normal[NOTE] on Environemnt() at                  150:
     Port 3 Address 33
Normal[NOTE] on Environemnt() at                  170:
    End of cfg_dut() method
Normal[NOTE] on Environemnt() at                  170:
    Start of start() method
Normal[NOTE] on Environemnt() at                  170:
    End of start() method
Normal[NOTE] on Environemnt() at                  170:
    Start of  wait_for_end() method
Normal[NOTE] on Environemnt() at                10170:
    End of  wait_for_end() method
Normal[NOTE] on Environemnt() at                10170:
    Start of stop() method
Normal[NOTE] on Environemnt() at                10170:
    End of stop() method
Normal[NOTE] on Environemnt() at                10170:
    Start of cleanup() method
Normal[NOTE] on Environemnt() at                10170:
    End of cleanup() method
Normal[NOTE] on Environemnt() at                10170:
    Start of report() method
    
    
    
---------------------------------------------------------------------
Simulation PASSED on /./ (/./) at                10170 (0 warnings, 0 demoted errors & 0
demoted warnings)
---------------------------------------------------------------------

Normal[NOTE] on Environemnt() at                10170:


    End of report() method
 ******************** End of testcase *****************

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/VL_08_PHASE_5_GENERATOR.html[9/26/2012 2:34:13 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/VL_08_PHASE_5_GENERATOR.html[9/26/2012 2:34:13 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PHASE 6 DRIVER Index


Introduction
SystemVerilog Specification
Verification In phase 6 we will write a driver and then insatiate the driver in environment and Verification Plan
send packet in to DUT. Driver class is defined in Driver.sv file. Phase 1 Top
Constructs Phase 2 Environment
Interface In this Driver class, take the packets from the generator and then drives it to the DUT Phase 3 Reset
input interface and then send the packet to a channel for scoreboard purpose. Phase 4 Packet
OOPS Phase 5 Generator
Randomization In this class, we also add 2 callback methods. Phase 6 Driver
Phase 7 Receiver
Functional Coverage Phase 8 Scoreboard
Assertion Phase 9 Coverage
DPI Report a Bug or Comment
UVM Tutorial on This section - Your
input is what keeps
VMM Tutorial
Testbench.in improving
OVM Tutorial with time!
Easy Labs : SV
Easy Labs : UVM
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

Verilog
Verification
Verilog Switch TB
1) Extend vmm_xactor_callbacks to define Driver_callbacks. In this class, declare 2
Basic Constructs methods pre_trans() and post_trans(). pre_trans() method is called before driving the
packet transaction and post_trans() method will be called after driving the packet
transaction.
OpenVera
class Driver_callbacks extends vmm_xactor_callbacks;
Constructs
Switch TB    // Called before a transaction is executed
RVM Switch TB    virtual task pre_trans(Packet tr);
   endtask: pre_trans
RVM Ethernet sample
   // Called after a transaction has been executed
   virtual task post_trans(Packet tr);
Specman E    endtask: post_trans

Interview Questions endclass:Driver_callbacks

1) Extend vmm_xactor to define Driver class.

class Driver extends vmm_xactor;

2) Declare a virtual input_interface of the switch. We will connect this to the Physical
interface of the top module same as what we did in environment class.

  virtual input_interface.IP  input_intf;

http://testbench.in/VL_09_PHASE_6_DRIVER.html[9/26/2012 2:34:23 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

3) Define a channel "gen2drv_chan" which is used to get packets from generator.

   Packet_channel  gen2drv_chan;

4) Define a channel "drv2sb_chan" which is used to send the packets to the score
board.

   Packet_channel  drv2sb_chan;

4) Define new constructor with arguments, virtual input interface and channels
"gen2drv_chan" and "drv2sb_chan".
In the constructor, call the parent constructor and pass the instance name and
stream_id.
Connect the channel and virtual interfaces which are passed as constructor arguments
to the class members.

function new(string inst,
             int stream_id = -1,
             virtual input_interface.IP  input_intf_new,
             Packet_channel   gen2drv_chan = null,
             Packet_channel   drv2sb_chan = null);
      
      super.new("driver",inst,stream_id);

      this.input_intf = input_intf_new;
      
      if(gen2drv_chan == null)
            `vmm_fatal(log,"gen2drv_channel is null");
      else
            this.gen2drv_chan = gen2drv_chan;
      
      if(drv2sb_chan == null)
            `vmm_fatal(log,"drvr2sb_channel is null");
      else
            this.drv2sb_chan = drv2sb_chan;
      
      `vmm_note(log,"Driver created ");
endfunction

4)Define drive() method. This method drives the packet to the dut.

task drive(Packet pkt);
    logic [7:0] pack[];
    int pkt_len;

    pkt_len = pkt.byte_pack(pack,0,0);
    @(posedge input_intf.clock);

    for (int i=0;i< pkt_len - 1;i++)
    begin
        @(posedge input_intf.clock);
        input_intf.cb.data_status <= 1 ;
        input_intf.cb.data_in <= pack[i];
    end

    @(input_intf.clock);
    input_intf.cb.data_status <= 0 ;
    input_intf.cb.data_in <= pack[pkt_len -1];
    @(input_intf.clock);
    this.drv2sb_chan.put(pkt);
endtask 

4) Define the main() method. First call the super.main() method.  

  super.main();
    `vmm_note(this.log," started main task ");
5) In main() method, start a forever thread, which gets the packets from the

http://testbench.in/VL_09_PHASE_6_DRIVER.html[9/26/2012 2:34:23 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

'gen2drv_chan' . The thread iteration has to be block if the channel is


empty or stopped.

     forever begin 
         Packet pkt;

         wait_if_stopped_or_empty(this.gen2drv_chan);
         this.gen2drv_chan.get(pkt);
 
         `vmm_trace(this.log, "Starting transaction...");
         `vmm_debug(this.log, pkt.psdisplay("   "));

6) Call the drive() method, which drives the packet to DUT. Call the pre_tans() call


back method using `vmm_callback macro before calling the drive method
and post_trans() callback method after driving the packet.

        `vmm_callback(Driver_callbacks,pre_trans(pkt));

         drive(pkt);

         `vmm_callback(Driver_callbacks,post_trans(pkt));

Driver Class Source Code:

`ifndef GUARD_DRIVER
`define GUARD_DRIVER

class Driver_callbacks extends vmm_xactor_callbacks;

   // Called before a transaction is executed


   virtual task pre_trans(Packet tr);
   endtask: pre_trans

   // Called after a transaction has been executed


   virtual task post_trans(Packet tr);
   endtask: post_trans

endclass:Driver_callbacks

class Driver extends vmm_xactor;

   virtual input_interface.IP  input_intf;
   Packet_channel              gen2drv_chan;
   Packet_channel              drv2sb_chan;

function new(string inst,
             int stream_id = -1,
             virtual input_interface.IP  input_intf_new,
             Packet_channel   gen2drv_chan = null,
             Packet_channel   drv2sb_chan = null);
      
      super.new("driver",inst,stream_id);

      this.input_intf = input_intf_new;
      
      if(gen2drv_chan == null)
            `vmm_fatal(log,"gen2drv_channel is null");
      else
            this.gen2drv_chan = gen2drv_chan;
      
      if(drv2sb_chan == null)
            `vmm_fatal(log,"drvr2sb_channel is null");
      else
            this.drv2sb_chan = drv2sb_chan;
      
      `vmm_note(log,"Driver created ");

http://testbench.in/VL_09_PHASE_6_DRIVER.html[9/26/2012 2:34:23 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

endfunction

task drive(Packet pkt);
    logic [7:0] pack[];
    int pkt_len;

    pkt_len = pkt.byte_pack(pack,0,0);
    @(posedge input_intf.clock);

    for (int i=0;i< pkt_len - 1;i++)
    begin
        @(posedge input_intf.clock);
        input_intf.cb.data_status <= 1 ;
        input_intf.cb.data_in <= pack[i];
    end

    @(input_intf.clock);
    input_intf.cb.data_status <= 0 ;
    input_intf.cb.data_in <= pack[pkt_len -1];
    @(input_intf.clock);
    this.drv2sb_chan.put(pkt);
endtask 

task main();
    super.main();
    `vmm_note(this.log," started main task ");

     forever begin 
         Packet pkt;

         wait_if_stopped_or_empty(this.gen2drv_chan);
         this.gen2drv_chan.get(pkt);
 
         `vmm_trace(this.log, "Starting transaction...");
         `vmm_debug(this.log, pkt.psdisplay("   "));

         `vmm_callback(Driver_callbacks,pre_trans(pkt));

         drive(pkt);

         `vmm_callback(Driver_callbacks,post_trans(pkt));

         `vmm_trace(this.log, "Completed transaction...");


         `vmm_debug(this.log, pkt.psdisplay("   "));
         @(posedge input_intf.clock);

     end
endtask

endclass
`endif

Now we will take the instance of the driver in the environment class.

http://testbench.in/VL_09_PHASE_6_DRIVER.html[9/26/2012 2:34:23 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

1) Declare a channel "drvr2sb_chan" which will be used to connect the scoreboard and
driver.

    Packet_channel drvr2sb_chan;

2) Declare a driver object "drvr".

    Driver drvr;

3) In build method, construct the channel.

    drvr2sb_chan = new("drvr2sb","chan");

4) In build method, construct the driver object. Pass the input_intf and drvr2sb_chan
channel and gen2drvr_chan channel.

    drvr = new("Drvr",0,input_intf,gen2drvr_chan,drvr2sb_chan);

5) To start sending the packets to the DUT, call the start method of "drvr" in the start
method of Environment class.

    drvr.start();

5)In the stop() method, call the stop_xactor() method of drvr.

    drvr.stop_xactor();

Environment Class Source Code:

`ifndef GUARD_ENV
`define GUARD_ENV

class Environment extends vmm_env;

  virtual mem_interface.MEM    mem_intf      ;
  virtual input_interface.IP  input_intf     ;
  virtual output_interface.OP output_intf[4] ;

  Packet_atomic_gen atomic_gen;

  Driver drvr;

  Packet_channel gen2drvr_chan;

  Packet_channel drvr2sb_chan;

function new(virtual mem_interface.MEM    mem_intf_new       ,


             virtual input_interface.IP  input_intf_new     ,
             virtual output_interface.OP output_intf_new[4] );

http://testbench.in/VL_09_PHASE_6_DRIVER.html[9/26/2012 2:34:23 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

  super.new("Environment ");
  this.mem_intf      = mem_intf_new    ;
  this.input_intf    = input_intf_new  ;
  this.output_intf   = output_intf_new ;
  
  `vmm_note(this.log, "Created env object");
endfunction : new

  virtual function void gen_cfg();


            super.gen_cfg();
            `vmm_note(this.log,"Start of gen_cfg() method ");
            `vmm_note(this.log,"End of gen_cfg() method ");
          endfunction
  virtual function void build();
            super.build();
            `vmm_note(this.log,"Start of build() method ");
            gen2drvr_chan = new("gen2drvr","chan");

            drvr2sb_chan = new("drvr2sb","chan");
            drvr = new("Drvr",0,input_intf,gen2drvr_chan,drvr2sb_chan);

            atomic_gen = new("atomic_gen",0,gen2drvr_chan);
            atomic_gen.stop_after_n_insts = 10;
            `vmm_note(this.log,"End of build() method ");
          endfunction

  virtual task reset_dut();


            super.reset_dut();
            `vmm_note(this.log,"Start of reset_dut() method ");
              mem_intf.cb.mem_data      <= 0;
              mem_intf.cb.mem_add       <= 0;
              mem_intf.cb.mem_en        <= 0;
              mem_intf.cb.mem_rd_wr     <= 0;
              input_intf.cb.data_in     <= 0;
              input_intf.cb.data_status <= 0;
              output_intf[0].cb.read    <= 0;
              output_intf[1].cb.read    <= 0;
              output_intf[2].cb.read    <= 0;
              output_intf[3].cb.read    <= 0;
              
              // Reset the DUT
              input_intf.reset       <= 1;
              repeat (4) @ input_intf.clock;
              input_intf.reset       <= 0;

            `vmm_note(this.log,"End of reset_dut() method ");


          endtask

  virtual task cfg_dut();


            super.cfg_dut();
            `vmm_note(this.log,"Start of cfg_dut() method ");
            mem_intf.cb.mem_en <= 1;
            @(posedge mem_intf.clock);
            mem_intf.cb.mem_rd_wr <= 1;
            
            @(posedge mem_intf.clock);
            mem_intf.cb.mem_add  <= 8'h0;
            mem_intf.cb.mem_data <= `P0;
            `vmm_note(this.log ,$psprintf(" Port 0 Address %h ",`P0));
            
            @(posedge mem_intf.clock);
            mem_intf.cb.mem_add  <= 8'h1;
            mem_intf.cb.mem_data <= `P1;
            `vmm_note(this.log ,$psprintf(" Port 1 Address %h ",`P1));
            
            @(posedge mem_intf.clock);
            mem_intf.cb.mem_add  <= 8'h2;
            mem_intf.cb.mem_data <= `P2;
            `vmm_note(this.log ,$psprintf(" Port 2 Address %h ",`P2));
            
            @(posedge mem_intf.clock);
            mem_intf.cb.mem_add  <= 8'h3;
            mem_intf.cb.mem_data <= `P3;

http://testbench.in/VL_09_PHASE_6_DRIVER.html[9/26/2012 2:34:23 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

            `vmm_note(this.log ,$psprintf(" Port 3 Address %h ",`P3));


            
            @(posedge mem_intf.clock);
            mem_intf.cb.mem_en    <=0;
            mem_intf.cb.mem_rd_wr <= 0;
            mem_intf.cb.mem_add   <= 0;
            mem_intf.cb.mem_data  <= 0;

            `vmm_note(this.log,"End of cfg_dut() method ");


          endtask

  virtual task start();


            super.start();
            `vmm_note(this.log,"Start of start() method ");
            atomic_gen.start_xactor();

            drvr.start_xactor();

            `vmm_note(this.log,"End of start() method ");


          endtask

  virtual task wait_for_end();


            super.wait_for_end();
            `vmm_note(this.log,"Start of  wait_for_end() method ");
             repeat(1000) @(input_intf.clock);
            `vmm_note(this.log,"End of  wait_for_end() method ");
          endtask

  virtual task stop();


            super.stop();
            `vmm_note(this.log,"Start of stop() method ");
            atomic_gen.stop_xactor();

            drvr.stop_xactor();

            `vmm_note(this.log,"End of stop() method ");


          endtask

  virtual task cleanup();


            super.cleanup();
            `vmm_note(this.log,"Start of cleanup() method ");
            `vmm_note(this.log,"End of cleanup() method ");
          endtask

  virtual task report();


            `vmm_note(this.log,"Start of report() method \n\n\n");
            $display("---------------------------------------------------------------------");
            super.report();
            $display("---------------------------------------------------------------------");
             $display("\n\n");
            `vmm_note(this.log,"End of report() method");
          endtask

endclass
`endif

Download the phase 6 source code:

vmm_switch_6.tar
Browse the code in vmm_switch_6.tar

Run the command:


vcs -sverilog -f filelist -R -ntb_opts rvm

Log file report.

 ******************* Start of testcase ****************


Normal[NOTE] on Environemnt() at                    0:
    Created env object
Normal[NOTE] on Environemnt() at                    0:
    Start of gen_cfg() method
Normal[NOTE] on Environemnt() at                    0:
    End of gen_cfg() method
Normal[NOTE] on Environemnt() at                    0:

http://testbench.in/VL_09_PHASE_6_DRIVER.html[9/26/2012 2:34:23 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

    Start of build() method


Normal[NOTE] on driver(Drvr) at                    0:
    Driver created
Normal[NOTE] on Environemnt() at                    0:
    End of build() method
Normal[NOTE] on Environemnt() at                    0:
    Start of reset_dut() method
Normal[NOTE] on Environemnt() at                   60:
    End of reset_dut() method
Normal[NOTE] on Environemnt() at                   60:
    Start of cfg_dut() method
Normal[NOTE] on Environemnt() at                   90:
     Port 0 Address 00
Normal[NOTE] on Environemnt() at                  110:
     Port 1 Address 11
Normal[NOTE] on Environemnt() at                  130:
     Port 2 Address 22
Normal[NOTE] on Environemnt() at                  150:
     Port 3 Address 33
Normal[NOTE] on Environemnt() at                  170:
    End of cfg_dut() method
Normal[NOTE] on Environemnt() at                  170:
    Start of start() method
Normal[NOTE] on Environemnt() at                  170:
    End of start() method
Normal[NOTE] on Environemnt() at                  170:
    Start of  wait_for_end() method
Normal[NOTE] on driver(Drvr) at                  170:
     started main task
Normal[NOTE] on Environemnt() at                10170:
    End of  wait_for_end() method
Normal[NOTE] on Environemnt() at                10170:
    Start of stop() method
Normal[NOTE] on Environemnt() at                10170:
    End of stop() method
Normal[NOTE] on Environemnt() at                10170:
    Start of cleanup() method
Normal[NOTE] on Environemnt() at                10170:
    End of cleanup() method
Normal[NOTE] on Environemnt() at                10170:
    Start of report() method
    
    
    
---------------------------------------------------------------------
Simulation PASSED on /./ (/./) at                10170 (0 warnings, 0 demoted errors & 0
demoted warnings)
---------------------------------------------------------------------

Normal[NOTE] on Environemnt() at                10170:


    End of report() method
 ******************** End of testcase *****************

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/VL_09_PHASE_6_DRIVER.html[9/26/2012 2:34:23 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PHASE 7 RECEIVER Index


Introduction
SystemVerilog Specification
Verification In this phase, we will write a receiver and use the receiver in environment class to Verification Plan
collect the packets coming from the switch output_interface. Phase 1 Top
Constructs Phase 2 Environment
Interface Receiver collects the data bytes from the interface signal. And then unpacks the bytes Phase 3 Reset
in to packet and pushes it into channel for score boarding. Phase 4 Packet
OOPS Phase 5 Generator
Randomization Receiver class is written in Reveicer.sv file. Phase 6 Driver
Phase 7 Receiver
Functional Coverage Phase 8 Scoreboard
Assertion Phase 9 Coverage
DPI Report a Bug or Comment
UVM Tutorial on This section - Your
input is what keeps
VMM Tutorial
Testbench.in improving
OVM Tutorial with time!
Easy Labs : SV
Easy Labs : UVM
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

Verilog
Verification
Verilog Switch TB
Basic Constructs 1) Extend vmm_xactor and define Receiver class.

    class Receiver extends vmm_xactor;
OpenVera 1) Declare a virtual output_interface. We will connect this to the Physical interface of
Constructs the top module, same as what we did in environment class.
Switch TB
    virtual output_interface.OP output_intf;
RVM Switch TB
RVM Ethernet sample 2) Declare a channel "rcvr2sb_chan" which is used to send the packets to the score
board

     Packet_channel rcvr2sb_chan;


Specman E
Interview Questions 3) Define new constructor with arguments, virtual input interface and a channel which
is used to send packets from the receiver to scoreboard. Implement the restof the
logic as it was done in the driver constructor.

function new(string inst = "class",
             int unsigned stream_id = -1,
             virtual output_interface.OP  output_intf_new,
             Packet_channel rcvr2sb_chan);

   super.new("Receiver",inst,stream_id);

http://testbench.in/VL_10_PHASE_7_RECEIVER.html[9/26/2012 2:34:33 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

   this.output_intf    = output_intf_new  ;

   if(rcvr2sb_chan == null)
        `vmm_fatal(log,"rcvr2sb_channel is null");
   else
        this.rcvr2sb_chan = rcvr2sb_chan;

   `vmm_note(log,"Receiver created ");

endfunction : new  

4) Define the main() method.

In start method, do the following


First call the super.main() method.
Then start a thread which collects the data from the outputinterface and then unpack
the data to a packet and put into channel.

   forever
     begin
         repeat(2) @(posedge output_intf.clock);
         wait(output_intf.cb.ready)
         output_intf.cb.read <= 1;  
         repeat(2) @(posedge output_intf.clock);

         while (output_intf.cb.ready)
         begin
               bytes = new[bytes.size + 1](bytes);
               bytes[bytes.size - 1] = output_intf.cb.data_out;
              @(posedge output_intf.clock);
         end

         bytes[bytes.size - 1] = output_intf.cb.data_out;
         output_intf.cb.read <= 0;  
         @(posedge output_intf.clock);
         `vmm_note(this.log,"Received a packet ");
         pkt = new();
         pkt.byte_unpack(bytes);
         pkt.display("rcvr");

         rcvr2sb_chan.put(pkt); 

         bytes.delete();  
     end

Receiver Class Source Code:


`ifndef GUARD_RECEIVER
`define GUARD_RECEIVER

class Receiver extends vmm_xactor;

virtual output_interface.OP output_intf;
Packet_channel rcvr2sb_chan;

function new(string inst = "class",
             int unsigned stream_id = -1,
             virtual output_interface.OP  output_intf_new,
             Packet_channel rcvr2sb_chan);

   super.new("Receiver",inst,stream_id);

   this.output_intf    = output_intf_new  ;

   if(rcvr2sb_chan == null)
        `vmm_fatal(log,"rcvr2sb_channel is null");
   else
        this.rcvr2sb_chan = rcvr2sb_chan;

http://testbench.in/VL_10_PHASE_7_RECEIVER.html[9/26/2012 2:34:33 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

   `vmm_note(log,"Receiver created ");

endfunction : new  

task main();
logic [7:0] bytes[];
Packet pkt;

    super.main();
    `vmm_note(this.log," started main task ");

     forever
     begin
         repeat(2) @(posedge output_intf.clock);
         wait(output_intf.cb.ready)
         output_intf.cb.read <= 1;  
         repeat(2) @(posedge output_intf.clock);

         while (output_intf.cb.ready)
         begin
               bytes = new[bytes.size + 1](bytes);
               bytes[bytes.size - 1] = output_intf.cb.data_out;
              @(posedge output_intf.clock);
         end

         bytes[bytes.size - 1] = output_intf.cb.data_out;
         output_intf.cb.read <= 0;  
         @(posedge output_intf.clock);
         `vmm_note(this.log,"Received a packet ");
         pkt = new();
         pkt.byte_unpack(bytes);
         pkt.display("rcvr");

         rcvr2sb_chan.put(pkt); 

         bytes.delete();  
     end
endtask : main

endclass

`endif

Now we will take the instance of the receiver in the environment class.

1) Declare a channel "rcvr2sb_chan" which will be used to connect the scoreboard and

http://testbench.in/VL_10_PHASE_7_RECEIVER.html[9/26/2012 2:34:33 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

receiver.

  Packet_channel rcvr2sb_chan;

2) Declare 4 receiver object "rcvr".

  Receiver rcvr[4];

3) In build method, construct the rcvr2sb_chan.

  rcvr2sb_chan = new("rcvr2sb","chan");

4) In build method, construct the receiver object. Pass the output_intf and
rcvr2sb_chan. There are 4 output interfaces and receiver objects. We will connect
one receiver for one output interface.

  foreach(rcvr[i])
      rcvr[i] = new($psprintf("Rcvr-%0d",i),i,output_intf[i],rcvr2sb_chan);

5) To start  the receiver activities, call the start_xactor() method of rcvr objects in


the start() method of Environment class.

      rcvr[0].start_xactor();
      rcvr[1].start_xactor();
      rcvr[2].start_xactor();
      rcvr[3].start_xactor();

6) Call the stop_xactor() method of the receiver object in the stop() method of the
Environment .

      rcvr[0].stop_xactor();
      rcvr[1].stop_xactor();
      rcvr[2].stop_xactor();
      rcvr[3].stop_xactor();

Environment Class Source Code:

`ifndef GUARD_ENV
`define GUARD_ENV

class Environment extends vmm_env;

  virtual mem_interface.MEM    mem_intf      ;
  virtual input_interface.IP  input_intf     ;
  virtual output_interface.OP output_intf[4] ;

  Packet_atomic_gen atomic_gen;
  Driver drvr;

  Receiver rcvr[4];

  Packet_channel gen2drvr_chan;
  Packet_channel drvr2sb_chan;

  Packet_channel rcvr2sb_chan;

function new(virtual mem_interface.MEM    mem_intf_new       ,


             virtual input_interface.IP  input_intf_new     ,
             virtual output_interface.OP output_intf_new[4] );
  super.new("Environment ");
  this.mem_intf      = mem_intf_new    ;
  this.input_intf    = input_intf_new  ;
  this.output_intf   = output_intf_new ;
  
  `vmm_note(this.log, "Created env object");
endfunction : new

  virtual function void gen_cfg();


            super.gen_cfg();
            `vmm_note(this.log,"Start of gen_cfg() method ");
            `vmm_note(this.log,"End of gen_cfg() method ");

http://testbench.in/VL_10_PHASE_7_RECEIVER.html[9/26/2012 2:34:33 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

          endfunction

  virtual function void build();


            super.build();
            `vmm_note(this.log,"Start of build() method ");
            gen2drvr_chan = new("gen2drvr","chan");
            drvr2sb_chan = new("drvr2sb","chan");

            rcvr2sb_chan = new("rcvr2sb","chan");

            atomic_gen = new("atomic_gen",0,gen2drvr_chan);
            atomic_gen.stop_after_n_insts = 10;
            drvr = new("Drvr",0,input_intf,gen2drvr_chan,drvr2sb_chan);

            foreach(rcvr[i])
            rcvr[i] = new($psprintf("Rcvr-%0d",i),i,output_intf[i],rcvr2sb_chan);

            `vmm_note(this.log,"End of build() method ");


          endfunction

  virtual task reset_dut();


            super.reset_dut();
            `vmm_note(this.log,"Start of reset_dut() method ");
              mem_intf.cb.mem_data      <= 0;
              mem_intf.cb.mem_add       <= 0;
              mem_intf.cb.mem_en        <= 0;
              mem_intf.cb.mem_rd_wr     <= 0;
              input_intf.cb.data_in     <= 0;
              input_intf.cb.data_status <= 0;
              output_intf[0].cb.read    <= 0;
              output_intf[1].cb.read    <= 0;
              output_intf[2].cb.read    <= 0;
              output_intf[3].cb.read    <= 0;
              
              // Reset the DUT
              input_intf.reset       <= 1;
              repeat (4) @ input_intf.clock;
              input_intf.reset       <= 0;

            `vmm_note(this.log,"End of reset_dut() method ");


          endtask

  virtual task cfg_dut();


            super.cfg_dut();
            `vmm_note(this.log,"Start of cfg_dut() method ");
            mem_intf.cb.mem_en <= 1;
            @(posedge mem_intf.clock);
            mem_intf.cb.mem_rd_wr <= 1;
            
            @(posedge mem_intf.clock);
            mem_intf.cb.mem_add  <= 8'h0;
            mem_intf.cb.mem_data <= `P0;
            `vmm_note(this.log ,$psprintf(" Port 0 Address %h ",`P0));
            
            @(posedge mem_intf.clock);
            mem_intf.cb.mem_add  <= 8'h1;
            mem_intf.cb.mem_data <= `P1;
            `vmm_note(this.log ,$psprintf(" Port 1 Address %h ",`P1));
            
            @(posedge mem_intf.clock);
            mem_intf.cb.mem_add  <= 8'h2;
            mem_intf.cb.mem_data <= `P2;
            `vmm_note(this.log ,$psprintf(" Port 2 Address %h ",`P2));
            
            @(posedge mem_intf.clock);
            mem_intf.cb.mem_add  <= 8'h3;
            mem_intf.cb.mem_data <= `P3;
            `vmm_note(this.log ,$psprintf(" Port 3 Address %h ",`P3));
            
            @(posedge mem_intf.clock);
            mem_intf.cb.mem_en    <=0;
            mem_intf.cb.mem_rd_wr <= 0;
            mem_intf.cb.mem_add   <= 0;
            mem_intf.cb.mem_data  <= 0;

http://testbench.in/VL_10_PHASE_7_RECEIVER.html[9/26/2012 2:34:33 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

            `vmm_note(this.log,"End of cfg_dut() method ");


          endtask

  virtual task start();


            super.start();
            `vmm_note(this.log,"Start of start() method ");
            atomic_gen.start_xactor();
            drvr.start_xactor();

            rcvr[0].start_xactor();
            rcvr[1].start_xactor();
            rcvr[2].start_xactor();
            rcvr[3].start_xactor();

            `vmm_note(this.log,"End of start() method ");


          endtask

  virtual task wait_for_end();


            super.wait_for_end();
            `vmm_note(this.log,"Start of  wait_for_end() method ");
             repeat(1000) @(input_intf.clock);
            `vmm_note(this.log,"End of  wait_for_end() method ");
          endtask

  virtual task stop();


            super.stop();
            `vmm_note(this.log,"Start of stop() method ");
            atomic_gen.stop_xactor();
            drvr.stop_xactor();

            rcvr[0].stop_xactor();
            rcvr[1].stop_xactor();
            rcvr[2].stop_xactor();
            rcvr[3].stop_xactor();

            `vmm_note(this.log,"End of stop() method ");


          endtask

  virtual task cleanup();


            super.cleanup();
            `vmm_note(this.log,"Start of cleanup() method ");
            `vmm_note(this.log,"End of cleanup() method ");
          endtask

  virtual task report();


            `vmm_note(this.log,"Start of report() method \n\n\n");
            $display("---------------------------------------------------------------------");
            super.report();
            $display("---------------------------------------------------------------------");
             $display("\n\n");
            `vmm_note(this.log,"End of report() method");
          endtask

endclass
`endif

Download the phase 7 source code:

vmm_switch_7.tar
Browse the code in vmm_switch_7.tar

Run the command:


vcs -sverilog -f filelist -R -ntb_opts rvm

Log file report.

 ******************* Start of testcase ****************


Normal[NOTE] on Environemnt() at                    0:
    Created env object
Normal[NOTE] on Environemnt() at                    0:
    Start of gen_cfg() method
Normal[NOTE] on Environemnt() at                    0:
    End of gen_cfg() method

http://testbench.in/VL_10_PHASE_7_RECEIVER.html[9/26/2012 2:34:33 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

Normal[NOTE] on Environemnt() at                    0:


    Start of build() method
Normal[NOTE] on driver(Drvr) at                    0:
    Driver created
Normal[NOTE] on Receiver(Rcvr-0) at                    0:
    Receiver created
Normal[NOTE] on Receiver(Rcvr-1) at                    0:
    Receiver created
Normal[NOTE] on Receiver(Rcvr-2) at                    0:
    Receiver created
Normal[NOTE] on Receiver(Rcvr-3) at                    0:
    Receiver created
Normal[NOTE] on Environemnt() at                    0:
    End of build() method
Normal[NOTE] on Environemnt() at                    0:
    Start of reset_dut() method
Normal[NOTE] on Environemnt() at                   60:
    End of reset_dut() method
Normal[NOTE] on Environemnt() at                   60:
    Start of cfg_dut() method
Normal[NOTE] on Environemnt() at                   90:
     Port 0 Address 00
Normal[NOTE] on Environemnt() at                  110:
     Port 1 Address 11
Normal[NOTE] on Environemnt() at                  130:
     Port 2 Address 22
Normal[NOTE] on Environemnt() at                  150:
     Port 3 Address 33
Normal[NOTE] on Environemnt() at                  170:
    End of cfg_dut() method
Normal[NOTE] on Environemnt() at                  170:
    Start of start() method
Normal[NOTE] on Environemnt() at                  170:
    End of start() method
Normal[NOTE] on Environemnt() at                  170:
    Start of  wait_for_end() method
Normal[NOTE] on driver(Drvr) at                  170:
     started main task
Normal[NOTE] on Receiver(Rcvr-0) at                  170:
     started main task
Normal[NOTE] on Receiver(Rcvr-1) at                  170:
     started main task
Normal[NOTE] on Receiver(Rcvr-2) at                  170:
     started main task
Normal[NOTE] on Receiver(Rcvr-3) at                  170:
     started main task
Normal[NOTE] on Receiver(Rcvr-0) at                  470:
    Received a packet
   rcvr   packet #0.0.0
   rcvr   da:0x00
   rcvr   sa:0xac
   rcvr   length:0x05 (data.size=4)
   rcvr   data[0]:0xcb   data[1]:0x7e   data[2]:0x52   data[3]:0xa4
   rcvr   fcs:0x29

Normal[NOTE] on Receiver(Rcvr-1) at                  710:


    Received a packet
   rcvr   packet #0.0.0
   rcvr   da:0x11
   rcvr   sa:0xf3
   rcvr   length:0x06 (data.size=5)
   rcvr   data[0]:0xc4   data[1]:0xd5  ....     data[3]:0xf3   data[4]:0x88
   rcvr   fcs:0x5b

Normal[NOTE] on Receiver(Rcvr-3) at                  890:


    Received a packet
   rcvr   packet #0.0.0
   rcvr   da:0x33
   rcvr   sa:0x6b
   rcvr   length:0x03 (data.size=2)
   rcvr   data[0]:0x32   data[1]:0x27
   rcvr   fcs:0x1c

Normal[NOTE] on Environemnt() at                10170:

http://testbench.in/VL_10_PHASE_7_RECEIVER.html[9/26/2012 2:34:33 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

    End of  wait_for_end() method


Normal[NOTE] on Environemnt() at                10170:
    Start of stop() method
Normal[NOTE] on Environemnt() at                10170:
    End of stop() method
Normal[NOTE] on Environemnt() at                10170:
    Start of cleanup() method
Normal[NOTE] on Environemnt() at                10170:
    End of cleanup() method
Normal[NOTE] on Environemnt() at                10170:
    Start of report() method
    
    
    
---------------------------------------------------------------------
Simulation PASSED on /./ (/./) at                10170 (0 warnings, 0 demoted errors & 0
demoted warnings)
---------------------------------------------------------------------

Normal[NOTE] on Environemnt() at                10170:


    End of report() method
 ******************** End of testcase *****************

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/VL_10_PHASE_7_RECEIVER.html[9/26/2012 2:34:33 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PHASE 8 SCOREBOARD Index


Introduction
SystemVerilog Specification
Verification In this phase we will see the scoreboard implementation. Vmm has scoreboard classes Verification Plan
with lot of features. For this example, we will write a simple scoreboard which is Phase 1 Top
Constructs implemented using the vmm_xactor. Phase 2 Environment
Interface Phase 3 Reset
Scoreboard has 2 channels. One is used to for getting the packets from the driver and Phase 4 Packet
OOPS Phase 5 Generator
other from the receiver.  Then the packets are compared and if they don't match,
Randomization then error is asserted. For comparison, compare () method of the Packet class is used. Phase 6 Driver
Phase 7 Receiver
Functional Coverage Phase 8 Scoreboard
Assertion Scoreboard in implemented in file Scoreboard.sv. Phase 9 Coverage
DPI Report a Bug or Comment
UVM Tutorial on This section - Your
input is what keeps
VMM Tutorial
Testbench.in improving
OVM Tutorial with time!
Easy Labs : SV
Easy Labs : UVM
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

Verilog
Verification
Verilog Switch TB
1) Declare 2 channels drvr2sb_chan and rcvr2sb_chan.
Basic Constructs
     Packet_channel   drvr2sb_chan;
     Packet_channel   rcvr2sb_chan;
OpenVera
Constructs 2) Declare a constructor method with drvr2sb_chan , rcvr2sb_chan , a string for
instance name and stream_id as arguments.
Switch TB
RVM Switch TB function new(string inst = "class",
             int unsigned stream_id = -1,
RVM Ethernet sample              Packet_channel   drvr2sb_chan = null,
             Packet_channel   rcvr2sb_chan = null);

Specman E
3) Call the super.new() method and Connect the channels of the constructor to the
Interview Questions channels of the scoreboard.

      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");

http://testbench.in/VL_11_PHASE_8_SCOREBOARD.html[9/26/2012 2:34:42 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

      else
           this.rcvr2sb_chan = rcvr2sb_chan;
      
      `vmm_note(log,"Scoreboard created ");

4) Define  vmm_xactor main() method. First call the super.main() method and then do
the following steps forever.
Wait until there is a packet is in "rcvr2sb_chan". Then pop the packet from channel.

    rcvr2sb_chan.get(pkt_rcv);
    $display(" %0d : Scorebooard : Scoreboard received a packet from receiver
",$time);

Then pop the packet from drvr2sb_chan.

     drvr2sb_chan.get(pkt_exp);

Compare both packets and assert an error if the comparison fails using `vmm_error.

    if(pkt_rcv.compare(pkt_exp,msg)) 
    $display(" %0d : Scoreboard :Packet Matched ",$time);
    else
    `vmm_error(this.log,$psprintf(" Packet MissMatched \n %s ",msg));

Scoreboard Class Source Code:


`ifndef GUARD_SCOREBOARD
`define GUARD_SCOREBOARD

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);

http://testbench.in/VL_11_PHASE_8_SCOREBOARD.html[9/26/2012 2:34:42 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

    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

`endif

Now we will see how to connect the scoreboard in the Environment class.

1) Declare a scoreboard handle.

  Scoreboard sb;

2) Construct the scoreboard in the build() method. Pass the drvr2sb_chan and
rcvr2sb_chan channels to the score board constructor.

  sb = new("Sb",0,drvr2sb_chan,rcvr2sb_chan);

3) Start the scoreboard activities in the start() method.

   sb.start_xactor();

4) Stop the scoreoard activities in stop() method.

   sb.stop_xactor();

Source Code Of The Environment Class:

`ifndef GUARD_ENV
`define GUARD_ENV

class Environment extends vmm_env;

  virtual mem_interface.MEM    mem_intf      ;
  virtual input_interface.IP  input_intf     ;
  virtual output_interface.OP output_intf[4] ;

  Packet_atomic_gen atomic_gen;
  Driver drvr;
  Receiver rcvr[4];

http://testbench.in/VL_11_PHASE_8_SCOREBOARD.html[9/26/2012 2:34:42 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

  Scoreboard sb;

  Packet_channel gen2drvr_chan;
  Packet_channel drvr2sb_chan;
  Packet_channel rcvr2sb_chan;

function new(virtual mem_interface.MEM    mem_intf_new       ,


             virtual input_interface.IP  input_intf_new     ,
             virtual output_interface.OP output_intf_new[4] );
  super.new("Environment ");
  this.mem_intf      = mem_intf_new    ;
  this.input_intf    = input_intf_new  ;
  this.output_intf   = output_intf_new ;
  
  `vmm_note(this.log, "Created env object");
endfunction : new

  virtual function void gen_cfg();


            super.gen_cfg();
            `vmm_note(this.log,"Start of gen_cfg() method ");
            `vmm_note(this.log,"End of gen_cfg() method ");
          endfunction

  virtual function void build();


            super.build();
            `vmm_note(this.log,"Start of build() method ");
            gen2drvr_chan = new("gen2drvr","chan");
            drvr2sb_chan = new("drvr2sb","chan");
            rcvr2sb_chan = new("rcvr2sb","chan");
            atomic_gen = new("atomic_gen",0,gen2drvr_chan);
            atomic_gen.stop_after_n_insts = 10;
            drvr = new("Drvr",0,input_intf,gen2drvr_chan,drvr2sb_chan);
            foreach(rcvr[i])
            rcvr[i] = new($psprintf("Rcvr-%0d",i),i,output_intf[i],rcvr2sb_chan);

            sb = new("Sb",0,drvr2sb_chan,rcvr2sb_chan);

            `vmm_note(this.log,"End of build() method ");


          endfunction

  virtual task reset_dut();


            super.reset_dut();
            `vmm_note(this.log,"Start of reset_dut() method ");
              mem_intf.cb.mem_data      <= 0;
              mem_intf.cb.mem_add       <= 0;
              mem_intf.cb.mem_en        <= 0;
              mem_intf.cb.mem_rd_wr     <= 0;
              input_intf.cb.data_in     <= 0;
              input_intf.cb.data_status <= 0;
              output_intf[0].cb.read    <= 0;
              output_intf[1].cb.read    <= 0;
              output_intf[2].cb.read    <= 0;
              output_intf[3].cb.read    <= 0;
              
              // Reset the DUT
              input_intf.reset       <= 1;
              repeat (4) @ input_intf.clock;
              input_intf.reset       <= 0;

            `vmm_note(this.log,"End of reset_dut() method ");


          endtask

  virtual task cfg_dut();


            super.cfg_dut();
            `vmm_note(this.log,"Start of cfg_dut() method ");
            mem_intf.cb.mem_en <= 1;
            @(posedge mem_intf.clock);
            mem_intf.cb.mem_rd_wr <= 1;
            
            @(posedge mem_intf.clock);
            mem_intf.cb.mem_add  <= 8'h0;
            mem_intf.cb.mem_data <= `P0;

http://testbench.in/VL_11_PHASE_8_SCOREBOARD.html[9/26/2012 2:34:42 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

            `vmm_note(this.log ,$psprintf(" Port 0 Address %h ",`P0));


            
            @(posedge mem_intf.clock);
            mem_intf.cb.mem_add  <= 8'h1;
            mem_intf.cb.mem_data <= `P1;
            `vmm_note(this.log ,$psprintf(" Port 1 Address %h ",`P1));
            
            @(posedge mem_intf.clock);
            mem_intf.cb.mem_add  <= 8'h2;
            mem_intf.cb.mem_data <= `P2;
            `vmm_note(this.log ,$psprintf(" Port 2 Address %h ",`P2));
            
            @(posedge mem_intf.clock);
            mem_intf.cb.mem_add  <= 8'h3;
            mem_intf.cb.mem_data <= `P3;
            `vmm_note(this.log ,$psprintf(" Port 3 Address %h ",`P3));
            
            @(posedge mem_intf.clock);
            mem_intf.cb.mem_en    <=0;
            mem_intf.cb.mem_rd_wr <= 0;
            mem_intf.cb.mem_add   <= 0;
            mem_intf.cb.mem_data  <= 0;

            `vmm_note(this.log,"End of cfg_dut() method ");


          endtask

  virtual task start();


            super.start();
            `vmm_note(this.log,"Start of start() method ");
            atomic_gen.start_xactor();
            drvr.start_xactor();
            rcvr[0].start_xactor();
            rcvr[1].start_xactor();
            rcvr[2].start_xactor();
            rcvr[3].start_xactor();

            sb.start_xactor();

            `vmm_note(this.log,"End of start() method ");


          endtask

  virtual task wait_for_end();


            super.wait_for_end();
            `vmm_note(this.log,"Start of  wait_for_end() method ");
             repeat(1000) @(input_intf.clock);
            `vmm_note(this.log,"End of  wait_for_end() method ");
          endtask

  virtual task stop();


            super.stop();
            `vmm_note(this.log,"Start of stop() method ");
            atomic_gen.stop_xactor();
            drvr.stop_xactor();
            rcvr[0].stop_xactor();
            rcvr[1].stop_xactor();
            rcvr[2].stop_xactor();
            rcvr[3].stop_xactor();

            sb.stop_xactor();

            `vmm_note(this.log,"End of stop() method ");


          endtask

  virtual task cleanup();


            super.cleanup();
            `vmm_note(this.log,"Start of cleanup() method ");
            `vmm_note(this.log,"End of cleanup() method ");
          endtask

  virtual task report();


            `vmm_note(this.log,"Start of report() method \n\n\n");
            $display("---------------------------------------------------------------------");
            super.report();
            $display("---------------------------------------------------------------------");

http://testbench.in/VL_11_PHASE_8_SCOREBOARD.html[9/26/2012 2:34:42 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

             $display("\n\n");
            `vmm_note(this.log,"End of report() method");
          endtask

endclass
`endif

Download the phase 8 score code:

vmm_switch_8.tar
Browse the code in vmm_switch_8.tar

Run the simulation:


vcs -sverilog -f filelist -R -ntb_opts rvm

Log File Report:

 ******************* Start of testcase ****************


Normal[NOTE] on Environemnt() at                    0:
    Created env object
Normal[NOTE] on Environemnt() at                    0:
    Start of gen_cfg() method
Normal[NOTE] on Environemnt() at                    0:
    End of gen_cfg() method
Normal[NOTE] on Environemnt() at                    0:
    Start of build() method
Normal[NOTE] on driver(Drvr) at                    0:
    Driver created
Normal[NOTE] on Receiver(Rcvr-0) at                    0:
    Receiver created
Normal[NOTE] on Receiver(Rcvr-1) at                    0:
    Receiver created
Normal[NOTE] on Receiver(Rcvr-2) at                    0:
    Receiver created
Normal[NOTE] on Receiver(Rcvr-3) at                    0:
    Receiver created
Normal[NOTE] on sb(Sb) at                    0:
    Scoreboard created
Normal[NOTE] on Environemnt() at                    0:
    End of build() method
Normal[NOTE] on Environemnt() at                    0:
    Start of reset_dut() method
Normal[NOTE] on Environemnt() at                   60:
    End of reset_dut() method
Normal[NOTE] on Environemnt() at                   60:
    Start of cfg_dut() method
Normal[NOTE] on Environemnt() at                   90:
     Port 0 Address 00
Normal[NOTE] on Environemnt() at                  110:
     Port 1 Address 11
Normal[NOTE] on Environemnt() at                  130:
     Port 2 Address 22
Normal[NOTE] on Environemnt() at                  150:
     Port 3 Address 33
Normal[NOTE] on Environemnt() at                  170:
    End of cfg_dut() method
Normal[NOTE] on Environemnt() at                  170:
    Start of start() method
Normal[NOTE] on Environemnt() at                  170:
    End of start() method
Normal[NOTE] on Environemnt() at                  170:
    Start of  wait_for_end() method
Normal[NOTE] on driver(Drvr) at                  170:
     started main task
Normal[NOTE] on Receiver(Rcvr-0) at                  170:
     started main task
Normal[NOTE] on Receiver(Rcvr-1) at                  170:
     started main task
Normal[NOTE] on Receiver(Rcvr-2) at                  170:
     started main task
Normal[NOTE] on Receiver(Rcvr-3) at                  170:
     started main task
 size           8 ****

http://testbench.in/VL_11_PHASE_8_SCOREBOARD.html[9/26/2012 2:34:42 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

Normal[NOTE] on Receiver(Rcvr-0) at                  470:


    Received a packet
   rcvr   packet #0.0.0
   rcvr   da:0x00
   rcvr   sa:0xac
   rcvr   length:0x05 (data.size=4)
   rcvr   data[0]:0xcb   data[1]:0x7e   data[2]:0x52   data[3]:0xa4
   rcvr   fcs:0x29

 470 : Scorebooard : Scoreboard received a packet from receiver


 size           9 ****
Normal[NOTE] on Receiver(Rcvr-1) at                  710:
    Received a packet
   rcvr   packet #0.0.0
   rcvr   da:0x11
   rcvr   sa:0xf3
   rcvr   length:0x06 (data.size=5)
   rcvr   data[0]:0xc4   data[1]:0xd5  ....     data[3]:0xf3   data[4]:0x88
   rcvr   fcs:0x5b

 size           6 ****
Normal[NOTE] on Receiver(Rcvr-3) at                  890:
    Received a packet
   rcvr   packet #0.0.0
   rcvr   da:0x33
   rcvr   sa:0x6b
   rcvr   length:0x03 (data.size=2)
   rcvr   data[0]:0x32   data[1]:0x27
   rcvr   fcs:0x1c

Normal[NOTE] on Environemnt() at                10170:


    End of  wait_for_end() method
Normal[NOTE] on Environemnt() at                10170:
    Start of stop() method
Normal[NOTE] on Environemnt() at                10170:
    End of stop() method
Normal[NOTE] on Environemnt() at                10170:
    Start of cleanup() method
Normal[NOTE] on Environemnt() at                10170:
    End of cleanup() method
Normal[NOTE] on Environemnt() at                10170:
    Start of report() method
    
    
    
---------------------------------------------------------------------
Simulation PASSED on /./ (/./) at                10170 (0 warnings, 0 demoted errors & 0
demoted warnings)
---------------------------------------------------------------------

Normal[NOTE] on Environemnt() at                10170:


    End of report() method
 ******************** End of testcase *****************

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/VL_11_PHASE_8_SCOREBOARD.html[9/26/2012 2:34:42 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

http://testbench.in/VL_11_PHASE_8_SCOREBOARD.html[9/26/2012 2:34:42 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PHASE 9 COVERAGE Index


Introduction
SystemVerilog Specification
Verification In this phase we will write the functional coverage for switch protocol. Functional Verification Plan
coverage is written in DrvrCovCallback.sv file. After running simulation, you will Phase 1 Top
Constructs analyze the coverage results and find out if some test scenarios have not been Phase 2 Environment
Interface exercised and write tests to exercise them. Phase 3 Reset
Phase 4 Packet
OOPS Phase 5 Generator
The points which we need to cover are  
Randomization 1) Cover all the port address configurations. Phase 6 Driver
2) Cover all the packet lengths. Phase 7 Receiver
Functional Coverage Phase 8 Scoreboard
3) Cover all correct and incorrect length fields.
Assertion 4) Cover good and bad FCS. Phase 9 Coverage
DPI 5) Cover all the above combinations.
Report a Bug or Comment
UVM Tutorial on This section - Your
input is what keeps
VMM Tutorial
Testbench.in improving
OVM Tutorial with time!
Easy Labs : SV
Easy Labs : UVM
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample
We will do the coverage sampling in the driver porst_trans() callback method which
we developed in PHASE_6.  
1) Define a cover group with following cover points. Define this cover group in a class
Verilog which extends Driver_callbacks.
Verification
  class DrvrCovCallback extends Driver_callbacks;
Verilog Switch TB
Basic Constructs a) All packet lengths:

length : coverpoint pkt.length;
OpenVera
b) All port address:
Constructs
Switch TB da     : coverpoint pkt.da {
            bins p0 = { `P0 }; 
RVM Switch TB
            bins p1 = { `P1 }; 
RVM Ethernet sample             bins p2 = { `P2 }; 
            bins p3 = { `P3 }; } 

c) Correct and incorrect Length field types:


Specman E
Interview Questions length_kind : coverpoint pkt.length_kind;

d) Good and Bad FCS:

fcs_kind : coverpoint pkt.fcs_kind;

5) Cross product of all the above cover points:

all_cross:  cross length,da,length_kind,fcs_kind;

2) In constructor method, construct the cover group

http://testbench.in/VL_12_PHASE_9_COVERAGE.html[9/26/2012 2:34:52 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

function new();
 switch_coverage = new();
endfunction : new

3) Write task which calls the sample method to cover the points.

task sample(packet pkt);
 this.pkt = pkt;
 switch_coverage.sample();
endtask:sample

Source Code Of Coverage Class:


`ifndef GUARD_DRVR_CALLBACK_1
`define GUARD_DRVR_CALLBACK_1

class DrvrCovCallback extends Driver_callbacks;
    Packet pkt;
    
    
    covergroup switch_coverage;
    
        length : coverpoint pkt.length;
        da     : coverpoint pkt.da {
                    bins p0 = { `P0 }; 
                    bins p1 = { `P1 }; 
                    bins p2 = { `P2 }; 
                    bins p3 = { `P3 }; } 
        length_kind : coverpoint pkt.length_kind;
        fcs_kind : coverpoint pkt.fcs_kind;
        
        all_cross:  cross length,da,length_kind,fcs_kind;
    endgroup
    
    function new();
        switch_coverage = new();
    endfunction : new
    

    virtual task post_trans(Packet pkt);
        this.pkt = pkt;
        switch_coverage.sample();
    endtask: post_trans

endclass:DrvrCovCallback

`endif

Now we will connect this callback instance to the Driver.

1) Take the instance of DrvrCovCallback in the Environemtn class.

            DrvrCovCallback cov_cb;

2) Construct the cov_cb object in build method.

            cov_cb = new();

3) In the Build method, call the append_callback() of the drvr and pass the cov_cb
 object.

            drvr.append_callback(cov_cb);

http://testbench.in/VL_12_PHASE_9_COVERAGE.html[9/26/2012 2:34:52 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

Source code of the Environment class:

`ifndef GUARD_ENV
`define GUARD_ENV

class Environment extends vmm_env;

  virtual mem_interface.MEM    mem_intf      ;
  virtual input_interface.IP  input_intf     ;
  virtual output_interface.OP output_intf[4] ;

  Packet_atomic_gen atomic_gen;
  Driver drvr;
  Receiver rcvr[4];
  Scoreboard sb;

  DrvrCovCallback cov_cb;

  Packet_channel gen2drvr_chan;
  Packet_channel drvr2sb_chan;
  Packet_channel rcvr2sb_chan;

function new(virtual mem_interface.MEM    mem_intf_new       ,


             virtual input_interface.IP  input_intf_new     ,
             virtual output_interface.OP output_intf_new[4] );
  super.new("Environment ");
  this.mem_intf      = mem_intf_new    ;
  this.input_intf    = input_intf_new  ;
  this.output_intf   = output_intf_new ;
  
  `vmm_note(this.log, "Created env object");
endfunction : new

  virtual function void gen_cfg();


            super.gen_cfg();
            `vmm_note(this.log,"Start of gen_cfg() method ");
            `vmm_note(this.log,"End of gen_cfg() method ");
          endfunction

  virtual function void build();


            super.build();
            `vmm_note(this.log,"Start of build() method ");
            gen2drvr_chan = new("gen2drvr","chan");
            drvr2sb_chan = new("drvr2sb","chan");
            rcvr2sb_chan = new("rcvr2sb","chan");

http://testbench.in/VL_12_PHASE_9_COVERAGE.html[9/26/2012 2:34:52 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

            atomic_gen = new("atomic_gen",0,gen2drvr_chan);
            atomic_gen.stop_after_n_insts = 10;
            drvr = new("Drvr",0,input_intf,gen2drvr_chan,drvr2sb_chan);
            foreach(rcvr[i])
            rcvr[i] = new($psprintf("Rcvr-%0d",i),i,output_intf[i],rcvr2sb_chan);
            sb = new("Sb",0,drvr2sb_chan,rcvr2sb_chan);

            cov_cb = new();
            drvr.append_callback(cov_cb);

            `vmm_note(this.log,"End of build() method ");


          endfunction

  virtual task reset_dut();


            super.reset_dut();
            `vmm_note(this.log,"Start of reset_dut() method ");
              mem_intf.cb.mem_data      <= 0;
              mem_intf.cb.mem_add       <= 0;
              mem_intf.cb.mem_en        <= 0;
              mem_intf.cb.mem_rd_wr     <= 0;
              input_intf.cb.data_in     <= 0;
              input_intf.cb.data_status <= 0;
              output_intf[0].cb.read    <= 0;
              output_intf[1].cb.read    <= 0;
              output_intf[2].cb.read    <= 0;
              output_intf[3].cb.read    <= 0;
              
              // Reset the DUT
              input_intf.reset       <= 1;
              repeat (4) @ input_intf.clock;
              input_intf.reset       <= 0;

            `vmm_note(this.log,"End of reset_dut() method ");


          endtask

  virtual task cfg_dut();


            super.cfg_dut();
            `vmm_note(this.log,"Start of cfg_dut() method ");
            mem_intf.cb.mem_en <= 1;
            @(posedge mem_intf.clock);
            mem_intf.cb.mem_rd_wr <= 1;
            
            @(posedge mem_intf.clock);
            mem_intf.cb.mem_add  <= 8'h0;
            mem_intf.cb.mem_data <= `P0;
            `vmm_note(this.log ,$psprintf(" Port 0 Address %h ",`P0));
            
            @(posedge mem_intf.clock);
            mem_intf.cb.mem_add  <= 8'h1;
            mem_intf.cb.mem_data <= `P1;
            `vmm_note(this.log ,$psprintf(" Port 1 Address %h ",`P1));
            
            @(posedge mem_intf.clock);
            mem_intf.cb.mem_add  <= 8'h2;
            mem_intf.cb.mem_data <= `P2;
            `vmm_note(this.log ,$psprintf(" Port 2 Address %h ",`P2));
            
            @(posedge mem_intf.clock);
            mem_intf.cb.mem_add  <= 8'h3;
            mem_intf.cb.mem_data <= `P3;
            `vmm_note(this.log ,$psprintf(" Port 3 Address %h ",`P3));
            
            @(posedge mem_intf.clock);
            mem_intf.cb.mem_en    <=0;
            mem_intf.cb.mem_rd_wr <= 0;
            mem_intf.cb.mem_add   <= 0;
            mem_intf.cb.mem_data  <= 0;

            `vmm_note(this.log,"End of cfg_dut() method ");


          endtask

  virtual task start();


            super.start();
            `vmm_note(this.log,"Start of start() method ");

http://testbench.in/VL_12_PHASE_9_COVERAGE.html[9/26/2012 2:34:52 PM]


WWW.TESTBENCH.IN - Easy Labs : VMM

            atomic_gen.start_xactor();
            drvr.start_xactor();
            rcvr[0].start_xactor();
            rcvr[1].start_xactor();
            rcvr[2].start_xactor();
            rcvr[3].start_xactor();
            sb.start_xactor();
            `vmm_note(this.log,"End of start() method ");
          endtask

  virtual task wait_for_end();


            super.wait_for_end();
            `vmm_note(this.log,"Start of  wait_for_end() method ");
             repeat(1000) @(input_intf.clock);
            `vmm_note(this.log,"End of  wait_for_end() method ");
          endtask

  virtual task stop();


            super.stop();
            `vmm_note(this.log,"Start of stop() method ");
            `vmm_note(this.log,"End of stop() method ");
          endtask

  virtual task cleanup();


            super.cleanup();
            `vmm_note(this.log,"Start of cleanup() method ");
            `vmm_note(this.log,"End of cleanup() method ");
          endtask

  virtual task report();


            `vmm_note(this.log,"Start of report() method \n\n\n");
            $display("---------------------------------------------------------------------");
            super.report();
            $display("---------------------------------------------------------------------");
             $display("\n\n");
            `vmm_note(this.log,"End of report() method");
          endtask

endclass
`endif

Download the phase 9 score code:

vmm_switch_9.tar
Browse the code in vmm_switch_9.tar

Run the simulation:


vcs -sverilog -f filelist -R -ntb_opts rvm
urg -dir simv.cm/

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/VL_12_PHASE_9_COVERAGE.html[9/26/2012 2:34:52 PM]


WWW.TESTBENCH.IN - AVM Switch TB

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS AVM INTRODUCTION Index


Avm Introduction
SystemVerilog Mentor Graphics Advanced Verification Methodology(AVM) is opensource and non- Dut Specification
Verification properietary SystemVerilog and systemc methodology. This is based on OSCI(open Rtl
systemC initiative) TLM standared. AVM can be downloaded for free from mentors Top
Constructs website. AVM contains TLM(Transaction Level modaling) concepts, rules, suggesation Interface
Interface with lot of examples for better understanding. AVM focuses on constrained Environment
randomization, Coverage , Assertions & scorboarding. Packet
OOPS Packet Generator
Randomization AVM provides base classes to improve user productivity. AVM has TLM interfaces to Configuration
communicate between testbench components. AVM liberary has the following base Driver
Functional Coverage Reciever
classes.
Assertion Scoreboard
DPI Reporting class: Has reporting methods, verbosity level controls etc.
Building Blocks: avm_transaction, avm_stimulus, avm_in_order_comparator, avm_env Report a Bug or Comment
UVM Tutorial etc. on This section - Your
TML library: TLM inteaces, TLM channels. input is what keeps
VMM Tutorial
Testbench.in improving
OVM Tutorial Verification components can be class or modules. Modules are handy for HDL users. with time!
Easy Labs : SV One of the main advantage of using module based avm testbench is it supports system
verilog assertions.In SystemVerilog ,Assertions canot be part of class.
Easy Labs : UVM
Easy Labs : OVM Where as class are more flexible as they are OO. Randomization is easy with class.
Dynamic instancsation and classes can be used as varibles for communication.
Easy Labs : VMM
AVM Switch TB AVM components intarect with DUT using SystemVerilog virtual interface.
VMM Ethernet sample Hear Im going to discussing the avm base classes which are used in the example. For
more details refer to avm cookbook.

Verilog Tlm:
Verification
All the verification components use TLM interfacess whether they are class based or
Verilog Switch TB module based. Main operations on the TLM or put,get and peek.
Basic Constructs
Initiator puts transaction to a target and can get trasaction from a target.

There are two types of TLMs.


OpenVera BLOCKING MODEL: Waits until the put transaction is completed befor the next put
Constructs operation. Blocking operation is time consuming.
Switch TB NON BLOCKING MODEL: Nonblocking operations are instansations. Every thing happens
in zero time.
RVM Switch TB
RVM Ethernet sample TLM supports unidirectional and bidirectional data flow. tlm_fifos are bases for TLM.
tlm_fifo has put,peek(get a copy) and get interface for communication tranctions. It
also has put_ap,get_ap(analaysis ports for commucating with score board or covarage
model).
Specman E
Interview Questions Lets see how to use ports and exports.
The TLM interface is called port. tlm_fifo sub blocks are called export.

EXAMPLE
Declare a tlm_fifo:

tlm_fifo#(packet) gen2drv;

Creat put port in initiator block(lets call it gen):


tlm_blocking_put_if#(packet) put_port;

http://testbench.in/AV_01_AVM_INTRODUCTION.html[9/26/2012 2:35:02 PM]


WWW.TESTBENCH.IN - AVM Switch TB

Creat get port in target block(lets call it drvr):


tlm_blocking_get_if#(packet) get_port;

Connect the exports to ports:

gen.put_port = gen2drv.blocking_put_export;
drvr.get_port = gen2drv.blocking_get_export;

Noe put can be done in gen and get can be done in drvr.

Building Blocks

There are two types of bases class used for building AVM components.
1)avm_named_component
2)avm_verificatino_component.

avm_named_components has information about the hierarchy of the instantiatio and


are used for TLM port and export connections. This also has built in message
controlling system.

avm_verification_components are inherited from avm_named_component.


avm_verification_component are used to build testbench component like
driver,monitor,transactor etc. In addition to avm_named_component feauters, a run()
method is provided for uses to define, and this run() method is forked from avm_env
automatically.

Avm_transactors:

Avm transaction is base class for creating tranctions. In order to allow the avm and
tlm libraries to work, we need methods to print, compare and clone transactions.
        
For any given transaction, T, to do four things to use avm_transaction:
Inherit from avm_transaction
Implement the virtual function string convert2string. This is for messaging.
Implement a function bit comp( input T t ). Used by the comparators for checking in
scoreboard.
Implement a function T clone(). This used for tlm_fifos. clone() returns a copy() of
.this(its object handle).

Avm_env:

avm_env class is the top level of testbench. avm_env has do_test() method which
starts building and execution of the testbench components.

Environment execution stars when do_test() task is called.


There are 5 execution phases.
Construct: Constructs all the class based verification components.
Connect:   Connect the class based verification components together.
Configure: Configuration of the testbench components in Zero time.
Execute:   do_run() forks off all the components run() methods and then execute
method.
Report:    End of simulation messages goes hear.

Avm_messaging:

avm_messaging supports four types of severity levels. They are


MESSAGE,WARNING,ERROR,FATAL
avm_messaging supports four types of actions. They are DISPLAY,LOG,COUNT,EXIT.
Each of the actions are define by severity and id.
        

http://testbench.in/AV_01_AVM_INTRODUCTION.html[9/26/2012 2:35:02 PM]


WWW.TESTBENCH.IN - AVM Switch TB

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/AV_01_AVM_INTRODUCTION.html[9/26/2012 2:35:02 PM]


WWW.TESTBENCH.IN - AVM Switch TB

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS DUT SPECIFICATION Index


Avm Introduction
SystemVerilog Dut Specification
Verification Rtl
This DUT is a simple switch, which can drive the incoming packet to destination ports Top
Constructs based on the address contained in the packet. Interface
Interface Environment
The dut contain one input interface from which the packet enters the dut. It has four Packet
OOPS Packet Generator
output interfaces where the packet is driven out.
Randomization Configuration
Driver
Functional Coverage Reciever
Assertion Scoreboard
DPI Report a Bug or Comment
UVM Tutorial on This section - Your
input is what keeps
VMM Tutorial
Testbench.in improving
OVM Tutorial with time!
Easy Labs : SV
Easy Labs : UVM
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

Verilog
Verification
Verilog Switch TB
Basic Constructs

Packet format:
OpenVera
Constructs Packet : Header, data and frame check sequence. Packet width is 8 bits and the
Switch TB length of the packet can be between 4 bytes to 259 bytes.
RVM Switch TB Packet header:
RVM Ethernet sample Packet header contains three fields DA, SA and length.
DA: Destination address of the packet. It is 8 bits. The switch drives the packet to
respective ports based on this destination address of the packets.
SA: Source address of the packet from where it originate.
Specman E Length: This is the length of the data. It can be from 0 to 255.
Interview Questions
Data: Data should be in terms of bytes. It can be between 0 to 255 bytes.

FCS: This field contains the security check of the packet. It is calculated over the
header and data.

http://testbench.in/AV_02_DUT_SPECIFICATION.html[9/26/2012 2:35:12 PM]


WWW.TESTBENCH.IN - AVM Switch TB

Configuration:

Dut has four output ports. These output ports have to be configure to a address. Dut
matches the DA field of the packet with this configured port address and sends the
packet on to that port. To configure the dut, a memory interface is provided. The
address of the ports should be unique. It is 8 bits wide. Memory address (0,1,2,3)
contains the address of port(0,1,2,4) respectively.

Interface Specification:

The dut has one input Interface, from where the packet enters the dut and 4 output
interfaces from where the packet comes out and one memory interface, through the
port address can be configured.

Memory Interface:

Through memory interfaced output port address are configured. It accepts 8 bit data
to be written to memory. It has 8 bit address inputs. Address 0,1,2,3 contains the
address of the port 0,1,2,3 respectively. If the DA feild in the packet matches with
the confugured address of any port ,then the packet comes out of that  port.

Input Interface:

The status signal has to be high when data is when packet is sent on to the dut it has
to become low after sending last byte of the packet. 2 clocks gap should be
maintained between packets.

Output Interface:

There are 4 ports, each having data, ready and read signals.

When the data is ready to be sent out from the port, dut makes the ready signal high
indicating that data is ready to be sent.
If the read signal is made high when ready is high, then the data comes out of the
data signal.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/AV_02_DUT_SPECIFICATION.html[9/26/2012 2:35:12 PM]


WWW.TESTBENCH.IN - AVM Switch TB

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS RTL Index


Avm Introduction
SystemVerilog Dut Specification
Verification CODE:rtl.v Rtl
module fifo (clk, Top
Constructs              reset, Interface
Interface              write_enb, Environment
             read, Packet
OOPS Packet Generator
             data_in,
Randomization              data_out, Configuration
             empty, Driver
Functional Coverage Reciever
             full);
Assertion input     clk; Scoreboard
DPI input     reset;
input write_enb; Report a Bug or Comment
UVM Tutorial input read; on This section - Your
input  [7:0] data_in; input is what keeps
VMM Tutorial
output [7:0] data_out; Testbench.in improving
OVM Tutorial output empty; with time!
Easy Labs : SV output full;
wire     clk;
Easy Labs : UVM wire write_enb;
Easy Labs : OVM wire read;
wire   [7:0] data_in;
Easy Labs : VMM reg    [7:0] data_out;
AVM Switch TB wire empty;
wire full;
VMM Ethernet sample reg      [7:0] ram[0:25];
reg            tmp_empty;
reg            tmp_full;
Verilog integer        write_ptr;
Verification integer        read_ptr;
   always@(negedge reset)
Verilog Switch TB    begin
Basic Constructs       data_out  = 8'b0000_0000;
      tmp_empty = 1'b1;
      tmp_full  = 1'b0;
      write_ptr = 0;
OpenVera       read_ptr  = 0;
Constructs    end
Switch TB
   assign empty = tmp_empty;
RVM Switch TB    assign full  = tmp_full;
RVM Ethernet sample  always @(posedge clk) begin 
      if ((write_enb == 1'b1) &&  (tmp_full == 1'b0)) begin
         ram[write_ptr] = data_in;
         tmp_empty <= 1'b0;
Specman E          write_ptr = (write_ptr + 1) % 16;
Interview Questions          if ( read_ptr == write_ptr ) begin
            tmp_full <= 1'b1;
         end 
      end 

 if ((read == 1'b1) &&  (tmp_empty == 1'b0)) begin


         data_out <= ram[read_ptr];
         tmp_full <= 1'b0;
         read_ptr = (read_ptr + 1) % 16;
         if ( read_ptr == write_ptr ) begin
            tmp_empty <= 1'b1;

http://testbench.in/AV_03_RTL.html[9/26/2012 2:35:22 PM]


WWW.TESTBENCH.IN - AVM Switch TB

         end 
      end 
   end  
endmodule //fifo

module port_fsm (clk,
                 reset,
                 write_enb,
                 ffee,
                 hold,
                 data_status,
                 data_in,
                 data_out,
                 mem0,
                 mem1,
                 mem2,
                 mem3,
                 addr);
input      clk;
input      reset;
input   [7:0]   mem0;
input   [7:0]   mem1;
input   [7:0]   mem2;
input   [7:0]   mem3;
output[3:0]  write_enb;
input  ffee;
input      hold;
input      data_status;
input[7:0]  data_in;
output[7:0]  data_out;
output  [7:0]     addr;
reg [7:0]  data_out;
reg [7:0]  addr;
reg    [3:0] write_enb_r;
reg          fsm_write_enb;
reg    [3:0] state_r;
reg    [3:0] state;
reg    [7:0] parity;
reg    [7:0] parity_delayed;
reg          sus_data_in,error;

parameter ADDR_WAIT   = 4'b0000;
parameter DATA_LOAD   = 4'b0001;
parameter PARITY_LOAD = 4'b0010;
parameter HOLD_STATE  = 4'b0011;
parameter BUSY_STATE  = 4'b0100;

  always@(negedge reset)
  begin
       error            = 1'b0;
       data_out       = 8'b0000_0000;
       addr           = 8'b00000000;
       write_enb_r    = 3'b000;
       fsm_write_enb  = 1'b0;
       state_r        = 4'b0000;
       state          = 4'b0000;
       parity         = 8'b0000_0000;
       parity_delayed = 8'b0000_0000;
       sus_data_in    = 1'b0;
  end
  assign busy = sus_data_in;
  always @(data_status) begin : addr_mux
    if (data_status == 1'b1) begin
      case (data_in)
      mem0 :  begin
            write_enb_r[0] = 1'b1;
            write_enb_r[1] = 1'b0;
            write_enb_r[2] = 1'b0;
            write_enb_r[3] = 1'b0;

http://testbench.in/AV_03_RTL.html[9/26/2012 2:35:22 PM]


WWW.TESTBENCH.IN - AVM Switch TB

      end
      mem1 :  begin
        write_enb_r[0] = 1'b0;
        write_enb_r[1] = 1'b1;
        write_enb_r[2] = 1'b0;
        write_enb_r[3] = 1'b0;
       end
      mem2 :  begin
        write_enb_r[0] = 1'b0;
        write_enb_r[1] = 1'b0;
        write_enb_r[2] = 1'b1;
        write_enb_r[3] = 1'b0;
      end
      
      mem3 :  begin
        write_enb_r[0] = 1'b0;
        write_enb_r[1] = 1'b0;
        write_enb_r[2] = 1'b0;
        write_enb_r[3] = 1'b1;
     end
     default :write_enb_r = 3'b000;
    endcase
  //  $display(" data_inii %d ,mem0 %d ,mem1 %d ,mem2 %d
mem3",data_in,mem0,mem1,mem2,mem3);
     end //if
end //addr_mux;
 always @(posedge clk) begin : fsm_state
     state_r <= state;
  end //fsm_state;

  always @(state_r or data_status or ffee or hold or data_in)


  begin : fsm_core
  state = state_r;   //Default state assignment
      case (state_r)
        ADDR_WAIT :   begin
                  if ((data_status == 1'b1) &&
                      ((mem0 == data_in)||(mem1 == data_in)||(mem3 == data_in) ||(mem2
== data_in))) begin
                     if (ffee == 1'b1) begin
                       state = DATA_LOAD;
                     end
                     else begin
                       state = BUSY_STATE;
                     end //if
                   end //if;
                  sus_data_in = !ffee;
                  if ((data_status == 1'b1) &&
                      ((mem0 == data_in)||(mem1 == data_in)||(mem3 == data_in) ||(mem2
== data_in)) &&
                      (ffee == 1'b1)) begin
                          addr = data_in;
                          data_out  = data_in;
                          fsm_write_enb = 1'b1;
                        
                  end
                  else begin
                      fsm_write_enb = 1'b0;
                  end //if
                end // of case ADDR_WAIT
         PARITY_LOAD : begin
                  state = ADDR_WAIT;
                  data_out = data_in;
                  fsm_write_enb = 1'b0;
                end // of case PARITY_LOAD
         DATA_LOAD :   begin
              if ((data_status == 1'b1) &&
               (hold == 1'b0)) begin
                  state = DATA_LOAD;
              end
              else if ((data_status == 1'b0) &&
              (hold == 1'b0)) begin
                  state = PARITY_LOAD;
              end
              else begin

http://testbench.in/AV_03_RTL.html[9/26/2012 2:35:22 PM]


WWW.TESTBENCH.IN - AVM Switch TB

                  state = HOLD_STATE;
              end  //if
             sus_data_in = 1'b0;
             if ((data_status == 1'b1) &&
               (hold == 1'b0)) begin
                  data_out = data_in;
                  fsm_write_enb = 1'b1;
             end
             else if ((data_status == 1'b0) &&
              (hold == 1'b0)) begin
                  data_out = data_in;
                  fsm_write_enb = 1'b1;
             end
             else begin
             fsm_write_enb = 1'b0;
             end //if
        end  //end of case DATA_LOAD
       HOLD_STATE :  begin
             if (hold == 1'b1) begin
                  state = HOLD_STATE;
             end
             else if ((hold == 1'b0) && (data_status == 1'b0)) begin
                  state = PARITY_LOAD;
             end
             else begin
                  state = DATA_LOAD;
             end //if
             if (hold == 1'b1) begin
                   sus_data_in = 1'b1;
                   fsm_write_enb = 1'b0;
             end
             else begin
                   fsm_write_enb = 1'b1;
                   data_out = data_in;
             end //if
         end  //end of case HOLD_STATE
            BUSY_STATE :  begin
             if (ffee == 1'b0) begin
                   state = BUSY_STATE;
             end
             else begin
                   state = DATA_LOAD;
             end //if
             if (ffee == 1'b0) begin
                   sus_data_in = 1'b1;
             end
             else begin
                   addr = data_in; // hans
                   data_out  = data_in;
                   fsm_write_enb = 1'b1;
             end //if
         end  //end of case BUSY_STATE
   endcase
  end //fsm_core

  assign write_enb[0] = write_enb_r[0] & fsm_write_enb;
  assign write_enb[1] = write_enb_r[1] & fsm_write_enb;
  assign write_enb[2] = write_enb_r[2] & fsm_write_enb;
  assign write_enb[3] = write_enb_r[3] & fsm_write_enb;

endmodule //port_fsm
module switch (clk,
               reset,
               data_status,
               data,
               port0,
               port1,
               port2,
               port3,
               ready_0,
               ready_1,
               ready_2,
               ready_3,
               read_0,

http://testbench.in/AV_03_RTL.html[9/26/2012 2:35:22 PM]


WWW.TESTBENCH.IN - AVM Switch TB

               read_1,
               read_2,
               read_3,
               mem_en,
               mem_rd_wr,
               mem_add,
               mem_data);
input          clk;
input          reset;
input          data_status;
input    [7:0] data;
input mem_en;
input mem_rd_wr;
input [1:0] mem_add;
input  [7:0] mem_data;
output   [7:0] port0;
output   [7:0] port1;
output   [7:0] port2;
output   [7:0] port3;
output         ready_0;
output       ready_1;
output       ready_2;
output       ready_3;
input       read_0;
input       read_1;
input       read_2;
input       read_3;
wire   [7:0] data_out_0;
wire   [7:0] data_out_1;
wire   [7:0] data_out_2;
wire   [7:0] data_out_3;
wire ll0;
wire ll1;
wire ll2;
wire ll3;
wire empty_0;
wire empty_1;
wire empty_2;
wire empty_3;
wire ffee;
wire ffee0;
wire ffee1;
wire ffee2;
wire ffee3;
wire ld0;
wire ld1;
wire ld2;
wire ld3;
wire hold;
wire   [3:0] write_enb;
wire   [7:0] data_out_fsm;
wire   [7:0] addr;

reg  [7:0]mem[3:0];
wire reset;
  fifo queue_0 (.clk     (clk),
                .reset     (reset),
                .write_enb (write_enb[0]),
                .read  (read_0),
                .data_in   (data_out_fsm),
                .data_out  (data_out_0),
                .empty     (empty_0),
                .full      (ll0));

  fifo queue_1 (.clk     (clk),


                .reset     (reset),
                .write_enb (write_enb[1]),
                .read  (read_1),
                .data_in   (data_out_fsm),
                .data_out  (data_out_1),
                .empty     (empty_1),
                .full      (ll1));

  fifo queue_2 (.clk     (clk),

http://testbench.in/AV_03_RTL.html[9/26/2012 2:35:22 PM]


WWW.TESTBENCH.IN - AVM Switch TB

                .reset     (reset),
                .write_enb (write_enb[2]),
                .read  (read_2),
                .data_in   (data_out_fsm),
                .data_out  (data_out_2),
                .empty     (empty_2),
                .full      (ll2));

 fifo queue_3 (.clk     (clk),


                .reset     (reset),
                .write_enb (write_enb[3]),
                .read  (read_3),
                .data_in   (data_out_fsm),
                .data_out  (data_out_3),
                .empty     (empty_3),
                .full      (ll3));

  port_fsm in_port (.clk           (clk),


                    .reset           (reset),
                    .write_enb       (write_enb),
                    .ffee      (ffee),
                    .hold            (hold),
                    .data_status    (data_status),
                    .data_in         (data),
                    .data_out        (data_out_fsm),
                    .mem0            (mem[0]),
                    .mem1            (mem[1]),
                    .mem2            (mem[2]),
                    .mem3            (mem[3]),
                    .addr            (addr));
  assign port0 = data_out_0;   //make note assignment only for
                                  //consistency with vlog env
  assign port1 = data_out_1;
  assign port2 = data_out_2;
  assign port3 = data_out_3;
  
  assign ready_0 = ~empty_0;
  assign ready_1 = ~empty_1;
  assign ready_2 = ~empty_2;
  assign ready_3 = ~empty_3;

  assign ffee0 = (empty_0 | ( addr != mem[0])); 


  assign ffee1 = (empty_1 | ( addr != mem[1])); 
  assign ffee2 = (empty_2 | ( addr != mem[2])); 
  assign ffee3 = (empty_3 | ( addr != mem[3])); 

  assign ffee  = ffee0 & ffee1 & ffee2 & ffee3;

  assign ld0 = (ll0 & (addr == mem[0])); 


  assign ld1 = (ll1 & (addr == mem[1])); 
  assign ld2 = (ll2 & (addr == mem[2])); 
  assign ld3 = (ll3 & (addr == mem[3])); 

  assign hold   = ld0 | ld1 | ld2 | ld3;

always@(posedge clk)
begin

if(mem_en)
if(mem_rd_wr)
begin
mem[mem_add]=mem_data;
///$display("%d  %d %d %d %d",mem_add,mem[0],mem[1],mem[2],mem[3]);
end
end
endmodule //router

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/AV_03_RTL.html[9/26/2012 2:35:22 PM]


WWW.TESTBENCH.IN - AVM Switch TB

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/AV_03_RTL.html[9/26/2012 2:35:22 PM]


WWW.TESTBENCH.IN - AVM Switch TB

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS TOP Index


Avm Introduction
SystemVerilog Verilog Top Dut Specification
Verification Rtl
Top level module containts the design and testbench instance. Top module also Top
Constructs contains clock generator. There is no need to instantiate the top module. Testbench Interface
Interface and dut instances are connected using interface instance. Make an instance of env Environment
class and creat it. Call the do_test() method which starts the testbench components. Packet
OOPS Packet Generator
Randomization Configuration
Driver
Functional Coverage Reciever
Assertion Scoreboard
DPI Report a Bug or Comment
UVM Tutorial on This section - Your
input is what keeps
VMM Tutorial
Testbench.in improving
OVM Tutorial with time!
Easy Labs : SV
Easy Labs : UVM
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

Verilog
CODE: top.v
Verification `include "mem_env.sv"
Verilog Switch TB
module top();
Basic Constructs

// Make an instance of SystemVerilog interface.


OpenVera switch_if intf();
Constructs
Switch TB
RVM Switch TB //As the RTL is in verilog and the SV Interface ports are not used,Connect signals by
signal names
RVM Ethernet sample  switch switch1  (.clk          (intf.clock),
                  .reset          (intf.reset),
                  .data_status   (intf.data_status),
Specman E                   .data           (intf.data_in),
                  .port0       (intf.data_out[0]),
Interview Questions                   .port1       (intf.data_out[1]),
                  .port2       (intf.data_out[2]),
                  .port3       (intf.data_out[3]),
                  .ready_0     (intf.ready[0]),
                  .ready_1     (intf.ready[1]),
                  .ready_2     (intf.ready[2]),
                  .ready_3     (intf.ready[3]),
                  .read_0     (intf.read[0]),
                  .read_1     (intf.read[1]),
                  .read_2    (intf.read[2]),
                  .read_3    (intf.read[3]),

http://testbench.in/AV_04_TOP.html[9/26/2012 2:35:32 PM]


WWW.TESTBENCH.IN - AVM Switch TB

                  .mem_en         (intf.mem_en),
                  .mem_rd_wr      (intf.mem_rd_wr),
                  .mem_add        (intf.mem_add),
                  .mem_data       (intf.mem_data));

// Creat a clock generator.


   initial begin
   intf.clock = 0;
   #10;
   forever begin
   #5 intf.clock = !intf.clock;
   end
   end

// Make an instance of testbench env


  sw_env env;
  
  initial
  begin
      @(posedge intf.clock);
// Pass the interface to testbench environment.
       env = new(intf);
//Call do_test task. extecution of the testbench starts.
       env.do_test;
     $finish;
  end
  
endmodule //top

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/AV_04_TOP.html[9/26/2012 2:35:32 PM]


WWW.TESTBENCH.IN - AVM Switch TB

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INTERFACE Index


Avm Introduction
SystemVerilog Dut Specification
Verification Creat an interface .Define modport to specifies direction. These are used to connect Rtl
testbench environment and dut in top module. Top
Constructs Interface
Interface CODE:interface Environment
`ifndef INTF Packet
OOPS Packet Generator
`define INTF
Randomization Configuration
interface switch_if(); Driver
Functional Coverage Reciever
bit           data_status;
Assertion bit     [7:0] data_in; Scoreboard
DPI wire    [3:0][7:0] data_out;
wire         [3:0] ready; Report a Bug or Comment
UVM Tutorial bit         [3:0] read; on This section - Your
bit        [7:0] mem_data; input is what keeps
VMM Tutorial
bit        [1:0] mem_add; Testbench.in improving
OVM Tutorial bit reset; with time!
Easy Labs : SV bit mem_en;
bit mem_rd_wr;
Easy Labs : UVM bit clock;
Easy Labs : OVM
modport TB(
Easy Labs : VMM output    data_status,
AVM Switch TB output    data_in,
input     data_out,
VMM Ethernet sample input     ready,
output    read,
output     mem_data,
Verilog output      mem_add,
Verification output reset,
output mem_en,
Verilog Switch TB output mem_rd_wr
Basic Constructs );

endinterface:switch_if
`endif
OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/AV_05_INTERFACE.html[9/26/2012 2:35:39 PM]


WWW.TESTBENCH.IN - AVM Switch TB

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/AV_05_INTERFACE.html[9/26/2012 2:35:39 PM]


WWW.TESTBENCH.IN - AVM Switch TB

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS ENVIRONMENT Index


Avm Introduction
SystemVerilog Dut Specification
Verification Environment is extended class of avm_env. Environment holds all the instancess of Rtl
avm_verification_component and fifos for connections. Top
Constructs Interface
Interface Environment
CODE:env.sv Packet
OOPS Packet Generator
  import avm_pkg::*;
Randomization    Configuration
   Driver
Functional Coverage Reciever
 `include "Configuration.sv"
Assertion  `include "packet.sv" Scoreboard
DPI  `include "mem_driver.sv"
 `include "reciever.sv" Report a Bug or Comment
UVM Tutorial  `include "score_board.sv" on This section - Your
input is what keeps
VMM Tutorial
  class sw_env extends avm_env; Testbench.in improving
OVM Tutorial with time!
Easy Labs : SV     // channels and interface
    local virtual switch_if intf;
Easy Labs : UVM     tlm_fifo#(packet) gen2drv;
Easy Labs : OVM     tlm_fifo#(packet) drv2sb;
    tlm_fifo#(packet) rcv2sb;
Easy Labs : VMM     
AVM Switch TB     // specific components
    local Configuration cfg;
VMM Ethernet sample     local driver drvr;
    local reciever rcvr_0;
    local reciever rcvr_1;
Verilog     local reciever rcvr_2;
Verification     local reciever rcvr_3;
    local scoreboard sb;
Verilog Switch TB     local generator gen;
Basic Constructs     local packet pkt;
  
    string msg;
    
OpenVera     function new( virtual switch_if intf );
Constructs       
Switch TB       this.intf = intf;
      cfg = new("cfg",intf);
RVM Switch TB       pkt = new();
RVM Ethernet sample       drvr = new("driver",cfg);
     rcvr_0 = new("reciever_0",0);
     rcvr_1 = new("reciever_1",1);
     rcvr_2 = new("reciever_2",2);
Specman E      rcvr_3 = new("reciever_3",3);
Interview Questions      sb = new();
      gen = new();
      gen2drv = new();
      drv2sb = new();
      rcv2sb = new();
      
    endfunction
    
    function void connect();
      
       avm_report_message("gen_cfg"," Starting... Gen_cfg \n");

http://testbench.in/AV_06_ENVIRONMENT.html[9/26/2012 2:35:52 PM]


WWW.TESTBENCH.IN - AVM Switch TB

       if (!cfg.randomize())
           avm_report_error("gen_cfg","Configuration Randomization Failed!\n");
           cfg.display();  
           avm_report_message("gen_cfg"," Ending.... Gen_cfg \n");
          
           pkt.do_cfg(cfg);
     // connect all the virtual interfacess.
      drvr.intf = intf;
      rcvr_0.intf = intf;
      rcvr_1.intf = intf;
      rcvr_2.intf = intf;
      rcvr_3.intf = intf;
      
      // connect all the TLM interfacess
      gen.put_port = gen2drv.blocking_put_export;
      drvr.get_port = gen2drv.blocking_get_export;
      drvr.put_sb = drv2sb.blocking_put_export;
      rcvr_0.put_sb = rcv2sb.blocking_put_export;
       sb.drv_port = drv2sb.blocking_get_export; 
       sb.rcv_port = rcv2sb.blocking_get_export; 

    endfunction

    task execute;

     wait(sb.no_rcv_pkt == 10 );


        terminate;
    
    
    endtask
      
    task terminate;
     $swrite(msg,"\n\n Total number of packets sent %d, Total no of packet recieved
%d\n\n",sb.no_drv_pkt,sb.no_rcv_pkt);
     avm_report_message("env",msg);
    endtask
      
  endclass

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/AV_06_ENVIRONMENT.html[9/26/2012 2:35:52 PM]


WWW.TESTBENCH.IN - AVM Switch TB

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PACKET Index


Avm Introduction
SystemVerilog Dut Specification
Verification Packet is inherited from avm_tranction. 3 methods copy,comp and convert2string Rtl
definition. convert2string method returns a string which describes the transaction. Top
Constructs comp method is for determining equality of two objects. clone method returns a Interface
Interface handle to a newly allocated copy of this(object). Environment
Packet
OOPS Packet Generator
CODE:packet.sv
Randomization Configuration
Driver
Functional Coverage Reciever
`ifndef PKT_CLASS
Assertion `define PKT_CLASS Scoreboard
DPI Report a Bug or Comment
UVM Tutorial on This section - Your
//Define the enumerated types for packet payload size type input is what keeps
VMM Tutorial
typedef enum { SMALL_P, MEDIUM_P, LARGE_P } payload_size_t ; Testbench.in improving
OVM Tutorial typedef enum { GOOD_P, BAD_P } packet_kind_t; with time!
Easy Labs : SV
Easy Labs : UVM class packet extends avm_transaction ;
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB string msg;
VMM Ethernet sample rand payload_size_t payload_size;//Control field for the payload size
byte uid;    // Unique id field to identify the packet    
rand bit [7:0] len;
Verilog rand bit [7:0] da;
Verification rand bit [7:0] sa;
Verilog Switch TB rand byte data[];//Payload using Dynamic array,size is generated on the fly
Basic Constructs rand byte parity;
static bit [7:0] mem [3:0];

constraint addr_8bit {(da == mem[3])||(da == mem[0])||(da == mem[1])||(da


OpenVera == mem[2]);}
Constructs
Switch TB // Constrain the len according the payload_size control field
constraint len_size {
RVM Switch TB    (payload_size == SMALL_P  ) -> len inside { [5 : 6]};
RVM Ethernet sample    (payload_size == MEDIUM_P ) -> len inside { [7 : 8]};
   (payload_size == LARGE_P  ) -> len inside {[9 : 10]}; }

Specman E
Interview Questions // Control field for GOOD/BAD
rand packet_kind_t packet_kind;

// May be assigned either a good or bad value,parity will be calculated in


portrandomize
constraint parity_type {
   (packet_kind == GOOD_P  ) -> parity == 0;
   (packet_kind == BAD_P   ) -> parity != 0;}

// define clone as per avm


 function packet clone();

http://testbench.in/AV_07_PACKET.html[9/26/2012 2:35:59 PM]


WWW.TESTBENCH.IN - AVM Switch TB

   packet t = new();
   t.copy( this );
   return t;
 endfunction

 function void do_cfg(Configuration cfg);
    this.mem[0]= cfg.da_port[0];
    this.mem[1]= cfg.da_port[1];
    this.mem[2]= cfg.da_port[2];
    this.mem[3]= cfg.da_port[3];
  $swrite(msg," packet new ::%x %x %x %x",mem[0],mem[1],mem[2],mem[3]);
  avm_report_message("packet",msg);
    endfunction
 
    // as per avm, define convert2string
  function string convert2string;
     string psdisplay;
     int i;
    
    $write(psdisplay, "da:0x%h  sa:0x%h  len:0x%h \n",this.da,this.sa,this.len,);
    
    for (i = 0; i < this.len; i++) $write(psdisplay, "%s data[%0d] 0x%h
\n", psdisplay,i, data[i]);
 $write(psdisplay,"%s parity :0x%h \n",psdisplay,this.parity);
 convert2string = psdisplay;
 endfunction
 
 
 

 function void copy(input packet to = null);
    

    // Copying to an existing instance. Correct type?


    if (!$cast(this, to))    
       begin
       avm_report_error("packet", "Attempting to copy to a non packet instance");
       return;
       end
    
 
    
    this.da = to.da;
    this.sa = to.sa;
    this.len = to.len;
    this.data = new[to.len];
    foreach(data[i])
        begin
       this.data[i] = to.data[i];
        end                    
 
    this.parity = to.parity;
   return;
    
 endfunction
 
 
  
 //unpacking function for converting recived data to class properties
function void unpack(byte bytes[$]);
      $swrite(msg," bytes size %d",bytes.size());
      void'(bytes.pop_front());
      da = bytes.pop_front();
      sa = bytes.pop_front();
     len = bytes.pop_front();
 
    
    $swrite(msg,"recieved packet::da:0x%h  sa:0x%h  len:0x%h

http://testbench.in/AV_07_PACKET.html[9/26/2012 2:35:59 PM]


WWW.TESTBENCH.IN - AVM Switch TB

\n", this.da,      this.sa,      this.len);
    avm_report_message("packet",msg);
      data = new [len - 4];
      parity = bytes.pop_back();
      foreach (data[i]) data[i] = bytes.pop_front();
endfunction 
 
function byte parity_cal();
integer i;
byte result ;
result = result ^ this.da;
result = result ^ this.sa;
result = result ^ this.len;
for (i = 0;i<this.len;i++)
begin
result = result ^ this.data[i];
end
return result;
endfunction
 
//post randomize fun to cal parity
function void post_randomize();
    data = new[len];
    foreach(data[i])
    data[i] = $random();
   parity = parity ^ parity_cal();
 endfunction

function void pre_randomize();
   data.delete();
endfunction

// define comp a per avm


function bit comp(input packet cmp,input packet to);
   string diff;
   bit compare;
    compare = 1; // Assume success by default.
    diff    = "No differences found";
    
    if (!$cast(cmp, to)) 
                                                begin
       avm_report_error("packet", "Attempting to compare to a non packet instance");
       compare = 0;
       diff = "Cannot compare non packets";
      
       return compare;
          end 
 
    // data types are the same, do comparison:
    if (to.da != cmp.da) 
                                                begin
       $swrite(diff,"Different DA values: %b != %b", to.da, cmp.da);
       compare = 0;
       avm_report_error("packet",diff);      
       return compare;
   end 
      
    if (to.sa != cmp.sa) 
                                                begin
       $swrite(diff,"Different SA values: %b != %b", to.sa, cmp.sa);
       compare = 0;
        avm_report_error("packet",diff);      
       return compare;
   end 
    if (to.len != cmp.len) 
        begin
       $swrite(diff,"Different LEN values: %b != %b", to.len, cmp.len);
       compare = 0;
        avm_report_error("packet",diff);      
       return compare;
   end 
 
    foreach(data[i]) 
       if (to.data[i] != cmp.data[i]) 

http://testbench.in/AV_07_PACKET.html[9/26/2012 2:35:59 PM]


WWW.TESTBENCH.IN - AVM Switch TB

                                                                        begin
          $swrite(diff,"Different data[%0d] values: 0x%h !=
0x%h",i, to.data[i], cmp.data[i]);
          compare = 0;
           avm_report_error("packet",diff);      
          return compare;
      end 
    if (to.parity != cmp.parity) 
        begin
       $swrite(diff,"Different PARITY values: %b != %b", to.parity, cmp.parity);
       compare = 0;
        avm_report_error("packet",diff);      
      
      
       return compare;
   end 
   return 1;
 endfunction

function int unsigned byte_pack(ref logic [7:0] bytes[],
                                                 input int unsigned offset ,
                                                 input int   kind);
byte_pack = 0;
bytes = new[this.len + 4];
bytes[0] = this.da;
bytes[1] = this.sa;
bytes[2] = this.len;
foreach(data[i])
bytes[3+i] = data[i];
bytes[this.len + 3 ] = parity;
byte_pack = this.len + 4;
endfunction    

endclass
`endif

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/AV_07_PACKET.html[9/26/2012 2:35:59 PM]


WWW.TESTBENCH.IN - AVM Switch TB

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PACKET GENERATOR Index


Avm Introduction
SystemVerilog Dut Specification
Verification Use a class to build packet generator. Make an instance of this class. Packet generator Rtl
generator generates packets and sends to driver using gen2drv channel. gen2drv is Top
Constructs used to connect the packet generator and driver. Packet generator generates the Interface
Interface packet and randomizes the packet. Then the packet is put into gen2drv channel. Environment
Always check whether the randomization is sucessful and display a message. Packet
OOPS Packet Generator
Randomization Configuration
CODE: gen.sv Driver
Functional Coverage Reciever
class generator extends avm_verification_component;
Assertion Scoreboard
DPI // define tml interface for communication
tlm_blocking_put_if#(packet) put_port; Report a Bug or Comment
UVM Tutorial on This section - Your
task run; input is what keeps
VMM Tutorial
Testbench.in improving
OVM Tutorial packet pkt; with time!
Easy Labs : SV
for(int i = 0; i < 10; i++)
Easy Labs : UVM begin
Easy Labs : OVM pkt = new();
Easy Labs : VMM if(!pkt.randomize())
AVM Switch TB avm_report_error("genarator"," randomiation failed\n");
else
VMM Ethernet sample avm_report_message("generator"," randomization done\n");
put_port.put(pkt);
end
Verilog endtask
Verification
endclass 
Verilog Switch TB
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/AV_08_PACKET_GENERATOR.html[9/26/2012 2:36:08 PM]


WWW.TESTBENCH.IN - AVM Switch TB

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/AV_08_PACKET_GENERATOR.html[9/26/2012 2:36:08 PM]


WWW.TESTBENCH.IN - AVM Switch TB

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS CONFIGURATION Index


Avm Introduction
SystemVerilog Dut Specification
Verification Confoguration class is inherited from avm_verification_component. This class Rtl
genarates addresses to configure the dut 4 output ports. Top
Constructs Interface
Interface CODE:CFG.SV Environment
Packet
OOPS Packet Generator
`ifndef CFG_CLASS
Randomization `define CFG_CLASS Configuration
class Configuration extends avm_verification_component; Driver
Functional Coverage Reciever
  rand  bit [7:0] da_port [4];
Assertion   string msg; Scoreboard
DPI  
  constraint da_ports Report a Bug or Comment
UVM Tutorial { (da_port[0] != da_port[1])&&(da_port[1] != da_port[2])&&(da_port[2] != da_port[3 on This section - Your
]);} input is what keeps
VMM Tutorial
Testbench.in improving
OVM Tutorial   virtual function void display(string prefix = "Test Configuration"); with time!
Easy Labs : SV     $swrite(msg," addresss %x %x %x %x
\n",da_port[0],da_port[1],da_port[2],da_port[3]);
Easy Labs : UVM     avm_report_message("cfg",msg);
Easy Labs : OVM   endfunction
Easy Labs : VMM   function new(string nm,virtual switch_if intf, avm_named_component p = null);
AVM Switch TB    super.new(nm,p);
   avm_report_message("cfg"," Configuration Created \n");
VMM Ethernet sample   endfunction

task run;
Verilog endtask
Verification   
endclass
Verilog Switch TB `endif  
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/AV_09_CONFIGURATION.html[9/26/2012 2:36:17 PM]


WWW.TESTBENCH.IN - AVM Switch TB

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/AV_09_CONFIGURATION.html[9/26/2012 2:36:17 PM]


WWW.TESTBENCH.IN - AVM Switch TB

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS DRIVER Index


Avm Introduction
SystemVerilog Dut Specification
Verification Driver is a tranctor. It is extension of avm_verification_component. Get the packets Rtl
from gen2drv chennel and drive them on to dut interface. Put the packets in to Top
Constructs drv2sb channel. Interface
Interface Environment
CODE:driver.sv Packet
OOPS Packet Generator
Randomization class driver extends avm_verification_component; Configuration
Driver
Functional Coverage Reciever
  virtual switch_if intf;
Assertion   string msg; Scoreboard
DPI   packet pkt;
  Configuration cfg; Report a Bug or Comment
UVM Tutorial    on This section - Your
   input is what keeps
VMM Tutorial
  tlm_blocking_get_if#(packet) get_port; Testbench.in improving
OVM Tutorial   tlm_blocking_put_if#(packet) put_sb; with time!
Easy Labs : SV
  function new(string nm,Configuration cfg);
Easy Labs : UVM       this.cfg = cfg;
Easy Labs : OVM       
    super.new(nm);
Easy Labs : VMM   endfunction
AVM Switch TB
  function void connect;
VMM Ethernet sample   
  endfunction

Verilog   task run;
Verification
  
Verilog Switch TB   reset_dut();
Basic Constructs   cfg_dut();
  forever
        begin
          get_port.get(pkt);
OpenVera           $display("consumer: sendging %s packet\n", pkt.convert2string);
Constructs           drive(pkt);
Switch TB           avm_report_message("Driver","Puting packet to score board");
          put_sb.put(pkt);
RVM Switch TB           @(negedge intf.clock);
RVM Ethernet sample
        end
  
  endtask
Specman E
Interview Questions
task drive(packet pkt);
logic [7:0] pack[];
int pkt_len;
pkt_len = pkt.byte_pack(pack,0,0);
$swrite(this.msg,"Packed packet length %d \n",pkt_len);
avm_report_message("Driver",this.msg);
@(negedge intf.clock);
for (int i=0;i< pkt_len - 1;i++)
begin
@(negedge intf.clock);

http://testbench.in/AV_10_DRIVER.html[9/26/2012 2:36:24 PM]


WWW.TESTBENCH.IN - AVM Switch TB

intf.data_status <= 1 ;
intf.data_in <= pack[i];
end
@(negedge intf.clock);
intf.data_status <= 0 ;
intf.data_in <= pack[pkt_len -1];
@(negedge intf.clock);
endtask 

task reset_dut();
 avm_report_message("reset_dut"," Starting... reset_dut \n");
  @(negedge intf.clock);
 avm_report_message("reset_dut"," Starting... reset_dut \n");
  intf.data_status  <= 0;
  intf.data_in      <= 0;
  intf.read         <= 0;
  intf.mem_data     <= 0;
  intf.mem_add      <= 0;
  intf.reset        <= 0;
  intf.mem_en       <= 0;
  intf.mem_rd_wr    <= 0; 
  @(negedge intf.clock);
  #2 intf.reset     <= 1;
  @(negedge intf.clock);
  #2 intf.reset     <= 0;
  @(negedge intf.clock);
  @(negedge intf.clock);
 avm_report_message("reset_dut"," Ending...  reset_dut \n");
endtask

task cfg_dut() ;
 avm_report_message("cfg_dut"," Starting... cfg_dut \n");
 for(int i = 0;i<4 ;i++)
 begin
 intf.mem_en    <= 1;
 @(negedge intf.clock);
 intf.mem_rd_wr <= 1;
 @(negedge intf.clock);
 intf.mem_add   <= i;
 intf.mem_data  <= cfg.da_port[i];
 end
 @(negedge intf.clock);
  intf.mem_en    <= 0;
  intf.mem_rd_wr <= 0;
  intf.mem_add   <= 0;
  intf.mem_data  <= 0;

 avm_report_message("cfg_dut"," Ending...  cfg_dut \n");

endtask
endclass 

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/AV_10_DRIVER.html[9/26/2012 2:36:24 PM]


WWW.TESTBENCH.IN - AVM Switch TB

http://testbench.in/AV_10_DRIVER.html[9/26/2012 2:36:24 PM]


WWW.TESTBENCH.IN - AVM Switch TB

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS RECIEVER Index


Avm Introduction
SystemVerilog Dut Specification
Verification Reciever is a tranctor. Start the collection of packet from dut in the run() task and Rtl
send them to score_board through rcv2sb channel. Top
Constructs Interface
Interface CODE:reciever.sv Environment
  Packet
OOPS Packet Generator
class reciever extends avm_verification_component;
Randomization  static tlm_blocking_put_if#(packet) put_sb; Configuration
  virtual switch_if intf; Driver
Functional Coverage Reciever
  int port;
Assertion   string name; Scoreboard
DPI   function new(string nm, int port);
    super.new(nm); Report a Bug or Comment
UVM Tutorial     this.name =nm; on This section - Your
    this.port = port; input is what keeps
VMM Tutorial
  endfunction Testbench.in improving
OVM Tutorial      with time!
Easy Labs : SV   
Easy Labs : UVM   task run;
Easy Labs : OVM      byte received_bytes[$] ;
    packet rcv_pkt,pkt;
Easy Labs : VMM     pkt = new();
AVM Switch TB  
forever
VMM Ethernet sample   begin
      @(posedge (intf.ready[port]));
        while (intf.ready[port]) begin
Verilog              intf.read <= 4'b0001 << port;
Verification              @(negedge intf.clock);
             received_bytes.push_back(intf.data_out[port]);
Verilog Switch TB              end
Basic Constructs              intf.read <= 4'h0;

    pkt.unpack(received_bytes);
    received_bytes = {};
OpenVera     rcv_pkt = new pkt;
Constructs      put_sb.put(rcv_pkt);
Switch TB   end
RVM Switch TB   endtask
RVM Ethernet sample     
endclass 

Specman E
Interview Questions

http://testbench.in/AV_11_RECIEVER.html[9/26/2012 2:36:33 PM]


WWW.TESTBENCH.IN - AVM Switch TB

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/AV_11_RECIEVER.html[9/26/2012 2:36:33 PM]


WWW.TESTBENCH.IN - AVM Switch TB

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS SCOREBOARD Index


Avm Introduction
SystemVerilog Dut Specification
Verification When the packet comes from reciever, the scoreboard gets the expected packet from Rtl
drv2sb channel and compare them. Top
Constructs Interface
Interface Environment
CODE:scoreboard.sv Packet
OOPS Packet Generator
`ifndef SB_CLASS
Randomization `define SB_CLASS Configuration
Driver
Functional Coverage Reciever
class scoreboard extends avm_verification_component;
Assertion Scoreboard
DPI  packet exp_pkt,drv_pkt;
 packet exp_que[$]; Report a Bug or Comment
UVM Tutorial  packet rcv_pkt; on This section - Your
  input is what keeps
VMM Tutorial
 integer no_drv_pkt; Testbench.in improving
OVM Tutorial  integer no_rcv_pkt; with time!
Easy Labs : SV  string msg;
 tlm_blocking_get_if#(packet) drv_port;
Easy Labs : UVM  tlm_blocking_get_if#(packet) rcv_port;
Easy Labs : OVM
function new( );
Easy Labs : VMM super.new("Scoreboard");
AVM Switch TB
 no_drv_pkt = 0;
VMM Ethernet sample  no_rcv_pkt = 0;

avm_report_message("sb","Scoreboard created");
Verilog endfunction
Verification
Verilog Switch TB task run();
Basic Constructs
    avm_report_message("sb"," STARTED main task ");
    fork
    forever
OpenVera     begin
Constructs     drv_port.get(drv_pkt);
Switch TB     this.no_drv_pkt++;
    $swrite(msg,"Recieved packet no from driver %d size of
RVM Switch TB queue%d\n",no_rcv_pkt,exp_que.size());
RVM Ethernet sample         avm_report_message("sb",msg);
    exp_que.push_front(drv_pkt);
    
    
Specman E     end
Interview Questions     join_none
forever 
begin
rcv_port.get(rcv_pkt);
this.no_rcv_pkt++;
exp_pkt = exp_que.pop_back();

$swrite(msg,"Recieved packet no %d\n",no_rcv_pkt);


avm_report_message("sb",msg);
if(rcv_pkt.comp(rcv_pkt,exp_pkt))
avm_report_message("sb"," Packet matched ");

http://testbench.in/AV_12_SCOREBOARD.html[9/26/2012 2:36:42 PM]


WWW.TESTBENCH.IN - AVM Switch TB

else
avm_report_error("sb"," Packet mismatch ");

end 
endtask

endclass

`endif

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/AV_12_SCOREBOARD.html[9/26/2012 2:36:42 PM]


WWW.TESTBENCH.IN - Verilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INTRODUCTION Index


Introduction
SystemVerilog Linear Tb
Verification Test Bench Overview File Io Tb
State Machine Based Tb
Constructs TestBench must verify that the design does everything it is supposed to do and  does Task Based Tb
Interface not do anything it is not supposed to do. There are different styles of writing Self Checking Testbench
testbenchs. These styles are called methodologies. Methodologies states how to verify Verification Flow
OOPS Clock Generator
complex scenarios to what file name you should use also.
Randomization Simulation
Incremental Compilation
Functional Coverage Store And Restore
Assertion Event Cycle Simulation
Time Scale And Precision
DPI Stimulus Generation
UVM Tutorial System Function Random
A Myth
VMM Tutorial Race Condition
OVM Tutorial Checker
Task And Function
Easy Labs : SV
Process Control
Easy Labs : UVM Disableing The Block
Watchdog
Easy Labs : OVM
Compilation N Simulation
Easy Labs : VMM Switchs
AVM Switch TB Debugging
About Code Coverage
VMM Ethernet sample Testing Stratigies
File Handling
Verilog Semaphore
Verilog Finding Testsenarious
Handling Testcase Files
Verification
Terimination
Verilog Switch TB Error Injuction
Register Verification
Basic Constructs
Parameterised Macros
White Gray Black Box
Regression
OpenVera Tips
Constructs
Report a Bug or Comment
Switch TB
on This section - Your
RVM Switch TB input is what keeps
Testbench.in improving
RVM Ethernet sample
with time!

Specman E
Interview Questions

http://testbench.in/TB_01_INTRODUCTION.html[9/26/2012 2:36:52 PM]


WWW.TESTBENCH.IN - Verilog for Verification

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TB_01_INTRODUCTION.html[9/26/2012 2:36:52 PM]


WWW.TESTBENCH.IN - Verilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS LINEAR TB Index


Introduction
SystemVerilog Linear Tb
Verification Linear Testbench: File Io Tb
State Machine Based Tb
Constructs Linear TestBench approach to TestBench creation is especially bad for performance. Task Based Tb
Interface As this is simplest, fastest and easiest way of writing testbenchs, this became novice Self Checking Testbench
verification engineer choice. Small models like simple state machine can be verified Verification Flow
OOPS Clock Generator
with this approach. The following code snippet shows linear testbench. Development
Randomization time increases exponentially as the number of scenarios increases. It is not possible to Simulation
list all possible input combinations if the number input vectors increases  .Just Incremental Compilation
Functional Coverage Store And Restore
imagine how many inputs are needed to test simple 32 bit adder. Usually Outputs are
Assertion checked using waveform viewer. As the number of outputs increases, analysis of all Event Cycle Simulation
the outputs is nightmare. There is no controllability in this method. To test another Time Scale And Precision
DPI Stimulus Generation
scenario like read operation, full test bench need to be coded. The simulator must
UVM Tutorial evaluate and schedule a very large number of events. This reduces simulation System Function Random
performance in proportion to the size of the stimulus process. A Myth
VMM Tutorial Race Condition
OVM Tutorial Linear test bench for a memory model. Checker
Task And Function
Easy Labs : SV
initial  Process Control
Easy Labs : UVM   begin  Disableing The Block
  # 10 read_write = 1; address = 100 ; data = 10;  Watchdog
Easy Labs : OVM
  # 10 read_write = 1; address = 101 ; data = 11;  Compilation N Simulation
Easy Labs : VMM   # 10 read_write = 1; address = 102 ; data = 12;  Switchs
AVM Switch TB   # 10 read_write = 1; address = 103 ; data = 13;  Debugging
  # 10 read_write = 1; address = 104 ; data = 14;  About Code Coverage
VMM Ethernet sample   end  Testing Stratigies
File Handling
Verilog Semaphore
Verilog Finding Testsenarious
Handling Testcase Files
Verification
Terimination
Verilog Switch TB Error Injuction
Register Verification
Basic Constructs
Parameterised Macros
White Gray Black Box
Regression
OpenVera Tips
Constructs
Report a Bug or Comment
Switch TB
on This section - Your
RVM Switch TB input is what keeps
Testbench.in improving
RVM Ethernet sample
with time!

Specman E
Interview Questions

http://testbench.in/TB_02_LINEAR_TB.html[9/26/2012 2:36:59 PM]


WWW.TESTBENCH.IN - Verilog for Verification

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TB_02_LINEAR_TB.html[9/26/2012 2:36:59 PM]


WWW.TESTBENCH.IN - Verilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS FILE IO TB Index


Introduction
SystemVerilog File I/O Based Testbench Linear Tb
Verification File Io Tb
Another way of getting the Stimulus is get the vectors from an external file. The State Machine Based Tb
Constructs external vector file is generally formatted so that each value in the file represents Task Based Tb
Interface either a specific input pattern .Verilog HDL contains the $readmemb or $readmemh Self Checking Testbench
system tasks to do the file read if the file data is formatted in a specific way using Verification Flow
OOPS Clock Generator
either binary or hexadecimal data. TestBench is like just an interface between
Randomization external vector source and DUT. Sometimes outputs are also to written to external Simulation
files. For example, to verify a a dsp algorithm implemented as  DUT, get the input Incremental Compilation
Functional Coverage Store And Restore
vectors from matlab tool and send the outputs to a file and then compare the outputs
Assertion of the matlab for the same algorithm. Event Cycle Simulation
Time Scale And Precision
DPI Stimulus Generation
Fallowing example illustrates how to initialize a memory array from data stored as
UVM Tutorial hexadecimal values in a data file, Simulate this file directly to see the results. System Function Random
Note: The data file must reside in the same directory  as the .v file for the module in A Myth
VMM Tutorial Race Condition
this example.
OVM Tutorial Checker
Task And Function
Easy Labs : SV
EXAMPLE: verilog file Process Control
Easy Labs : UVM module readmemh_demo;  Disableing The Block
Watchdog
Easy Labs : OVM
   reg [31:0] Mem [0:11];  Compilation N Simulation
Easy Labs : VMM    Switchs
AVM Switch TB    initial $readmemh("data.txt",Mem);  Debugging
   About Code Coverage
VMM Ethernet sample    integer k;  Testing Stratigies
   initial begin  File Handling
      #10;  Verilog Semaphore
Verilog       $display("Contents of Mem after reading data file:");  Finding Testsenarious
      for (k=0; k<6; k=k+1) $display("%d:%h",k,Mem[k]);  Handling Testcase Files
Verification
   end  Terimination
Verilog Switch TB Error Injuction
endmodule  Register Verification
Basic Constructs
Parameterised Macros
EXAMPLE: data.txt file White Gray Black Box
   234ac Regression
OpenVera    23ca5 Tips
Constructs    b3c34
   23a4a Report a Bug or Comment
Switch TB
   234ca on This section - Your
RVM Switch TB    b3234 input is what keeps
Testbench.in improving
RVM Ethernet sample
RESULT: with time!

   0:000234ac
Specman E    1:00023ca5
Interview Questions    2:000b3c34
   3:00023a4a
   4:000234ca
   5:000b3234

Reading or writing to files during simulation is costly to performance, because the


simulator must halt and wait while the OS completes each transaction with the file
system. One way to improve performance is to replace ASCII vector files with a
constant table in HDL itself. Do this using Perl script.  

http://testbench.in/TB_03_FILE_IO_TB.html[9/26/2012 2:37:08 PM]


WWW.TESTBENCH.IN - Verilog for Verification

module readmemh_demo; 

   reg [31:0] Mem [0:11]; 
  
   `include "data.v" 
  
   integer k; 
   initial begin 
      #10; 
      $display("Contents of Mem after reading data file:"); 
      for (k=0; k<6; k=k+1) $display("%d:%h",k,Mem[k]); 
   end 

endmodule 

EXAMPLE: data.v file


initial 
   begin 
   Mem[0] = 32'h234ac;  
   Mem[1] = 32'h23ca5;  
   Mem[2] = 32'hb3c34;  
   Mem[3] = 32'h23a4a;  
   Mem[4] = 32'h234ca;  
   Mem[5] = 32'hb3234;  
   end 

RESULT:

   0:000234ac
   1:00023ca5
   2:000b3c34
   3:00023a4a
   4:000234ca
   5:000b3234

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TB_03_FILE_IO_TB.html[9/26/2012 2:37:08 PM]


WWW.TESTBENCH.IN - Verilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS STATE MACHINE BASED TB Index


Introduction
SystemVerilog Linear Tb
Verification By definition, a stat machine TestBench used state machine to generate input vector File Io Tb
and drive it to the I/O ports of the design. One testbench can have multiple state State Machine Based Tb
Constructs machines each handling a different functionality. To achieve the quality of Task Based Tb
Interface verification required by today's complex designs, testbench must be robust. State Self Checking Testbench
machine based verification cannot support todays verification needs. A state machine Verification Flow
OOPS Clock Generator
based testbench is hardly seen nowadays.
Randomization Simulation
always@(posedge clk)  Incremental Compilation
Functional Coverage Store And Restore
case(state) 
Assertion READ  :  if(i < No_of_reads)  Event Cycle Simulation
        begin  Time Scale And Precision
DPI Stimulus Generation
        read_write = 0; 
UVM Tutorial         address = $random;  System Function Random
        i=i+1;  A Myth
VMM Tutorial Race Condition
        end 
OVM Tutorial         else  Checker
        $finish  Task And Function
Easy Labs : SV
WRITE : if(j < no_of_writes)  Process Control
Easy Labs : UVM         begin  Disableing The Block
        read_write = 1;  Watchdog
Easy Labs : OVM
        address = $random;  Compilation N Simulation
Easy Labs : VMM         data = $random;  Switchs
AVM Switch TB         j=j+1;  Debugging
        end  About Code Coverage
VMM Ethernet sample         else  Testing Stratigies
        state = READ ;  File Handling
endcase Verilog Semaphore
Verilog   Finding Testsenarious
Handling Testcase Files
Verification
Terimination
Verilog Switch TB Now lets see how to develop our scenarios: Error Injuction
Only 10 write operations, Register Verification
Basic Constructs
Parameterised Macros
initial  White Gray Black Box
   begin  Regression
OpenVera    No_of_reads = 0;  Tips
Constructs    No_of_writes = 10; 
   end  Report a Bug or Comment
Switch TB
on This section - Your
RVM Switch TB input is what keeps
Testbench.in improving
RVM Ethernet sample Only 10 read operations,
with time!
initial 
   begin 
Specman E    No_of_reads = 10; 
Interview Questions    No_of_writes = 0; 
   end 

With the above style of testbench, the controllability is less and hard to change the
code to add new features like to convert the above code to alternate read and write
operation, its very difficult.

http://testbench.in/TB_04_STATE_MACHINE_BASED_TB.html[9/26/2012 2:37:17 PM]


WWW.TESTBENCH.IN - Verilog for Verification

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TB_04_STATE_MACHINE_BASED_TB.html[9/26/2012 2:37:17 PM]


WWW.TESTBENCH.IN - Verilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS TASK BASED TB Index


Introduction
SystemVerilog Task And Function Based Tb: Linear Tb
Verification File Io Tb
Task based verification is more flexible over all the above approaches. All the State Machine Based Tb
Constructs operations in are done using takes and functions. The task based BFM is extremely Task Based Tb
Interface efficient if the device under test performs many calculations. Each task or function Self Checking Testbench
focuses on one single functionality. Verification of DUT using the task based testbench Verification Flow
OOPS Clock Generator
is faster. Using tasks makes it possible to describe structural testbenchs. These tasks
Randomization can be ported without much effort. Simulation
Incremental Compilation
Functional Coverage Store And Restore
EXAMPLE:
Assertion task write(input integer data,input integer address);  Event Cycle Simulation
begin  Time Scale And Precision
DPI Stimulus Generation
   @(posedge clock); 
UVM Tutorial    read_write = 1;  System Function Random
   address = $random;  A Myth
VMM Tutorial Race Condition
   data = $random;  
OVM Tutorial end  Checker
endtask  Task And Function
Easy Labs : SV
Process Control
Easy Labs : UVM task read(input integer address,output integer data);  Disableing The Block
begin  Watchdog
Easy Labs : OVM
   @(posedge clock);  Compilation N Simulation
Easy Labs : VMM    read_write = 0;  Switchs
AVM Switch TB    address = $random;  Debugging
   // Do some operation to get data About Code Coverage
VMM Ethernet sample end  Testing Stratigies
endtask  File Handling
Verilog Semaphore
Verilog Now lets see how to develop the senarious.  Finding Testsenarious
Handling Testcase Files
Verification
1) 10 write operations. Terimination
Verilog Switch TB Error Injuction
initial  Register Verification
Basic Constructs
   repeat(10)  Parameterised Macros
   write($random,$random);  White Gray Black Box
Regression
OpenVera 2) 10 read operations Tips
Constructs
initial   Report a Bug or Comment
Switch TB
   repeat(10)  on This section - Your
RVM Switch TB    read($random,data);  input is what keeps
Testbench.in improving
RVM Ethernet sample
3) Alternate read and write operations. with time!

initial  
Specman E    repeat(10) 
Interview Questions    begin 
      write($random,$random); 
      read($random,data); 
   end 

4) Do the write and read the same location.

initial 
    begin 
        write(10,20); 
        read (10,data); 

http://testbench.in/TB_05_TASK_BASED_TB.html[9/26/2012 2:37:28 PM]


WWW.TESTBENCH.IN - Verilog for Verification

    end 

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TB_05_TASK_BASED_TB.html[9/26/2012 2:37:28 PM]


WWW.TESTBENCH.IN - Verilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS SELF CHECKING TESTBENCH Index


Introduction
SystemVerilog Linear Tb
Verification Two important aspects of todays functional verification are quality and re usability. File Io Tb
Design engineers have made design reuse to reduce development time and effort in State Machine Based Tb
Constructs designing an ASIC. Significant design blocks are reused from one project to the next. Task Based Tb
Interface The lack of flexible verification environments that allow verification components Self Checking
reuse across ASIC design projects keep the verification cost very high. Considering the Testbench
OOPS Verification Flow
fact that verification consumes more resources than design does , it would be of
Randomization great value to build verification components that are modular and reusable. When a Clock Generator
design is passing all the tests in the verification environment, it has not been possible Simulation
Functional Coverage Incremental Compilation
to know whether the design under verification is correct, and may be safely taped-
Assertion out, or whether the verification environment is just incapable of finding any bugs that Store And Restore
may still remain in DUT. Event Cycle Simulation
DPI Time Scale And Precision
UVM Tutorial ADVANTAGES: Stimulus Generation
Speeds up verification and results in early tape out of the chip. System Function Random
VMM Tutorial A Myth
Less man power is required, by which the over all cost of the project will be low.
OVM Tutorial Environment can be reusable. Race Condition
Easy tracking of verification progress(functional coverage). Checker
Easy Labs : SV
Developing self checking testbench is very interesting. Task And Function
Easy Labs : UVM Process Control
Disableing The Block
Easy Labs : OVM
Todays functional verification flow mainly contains following steps: Watchdog
Easy Labs : VMM Compilation N Simulation
AVM Switch TB Generate the stimulus vectors. Switchs
Send the Stimulus to the DUT. Debugging
VMM Ethernet sample Monitor the response generated by the DUT. About Code Coverage
Verify the response generated. Testing Stratigies
Generate report about the DUT performance. File Handling
Verilog Some kind of feedback to show the quality of testbench. Verilog Semaphore
Finding Testsenarious
Verification
A test-bench is built to functionally verify the design by providing meaningful Handling Testcase Files
Verilog Switch TB scenarios to check that given certain input, the design performs to specification. Test Terimination
bench provides the stimulus to exercise DUT code. A self checking testbench is a Error Injuction
Basic Constructs
intelligent testbench which does some form of output sampling of DUT and compares Register Verification
the sampled output with the expected outputs. A simulation environment is typically Parameterised Macros
composed of several types of components: White Gray Black Box
OpenVera Regression
Constructs Tips
Switch TB
Report a Bug or Comment
RVM Switch TB on This section - Your
input is what keeps
RVM Ethernet sample
Testbench.in improving
with time!

Specman E
Interview Questions

Stimulus Generator:

In order to test the model of some design, a verification engineer must apply test
patterns to the input ports and observe the output ports over time to decide whether

http://testbench.in/TB_06_SELF_CHECKING_TESTBENCH.html[9/26/2012 2:37:37 PM]


WWW.TESTBENCH.IN - Verilog for Verification

the inputs were transformed to the expected outputs. The generator component
generates input vectors. For simple memory stimulus generator generates read, write
operations, address and data to be stored in the address if its write operation.
Modern generators generate random, biased, and valid stimuli. In verilog $random
does this job. The randomness is important to achieve a high distribution over the
huge space of the available input stimuli. To this end, users of these generators
intentionally under-specify the requirements for the generated tests. It is the role of
the generator to randomly fill this gap. This mechanism allows the generator to
create inputs that reveal bugs not being searched for directly by the user. Generators
also bias the stimuli toward design corner cases to further stress the logic. Biasing and
randomness serve different goals and there are tradeoffs between them, hence
different generators have a different mix of these characteristics. Since the input for
the design must be valid and many targets should be maintained, many generators use
the Constraint Satisfaction Problem technique to solve the complex testing
requirements. SystemVerilog, Vera, SystemC and Specman have " constraints " to
specify The legality of the design inputs. In verilog ,to constrain the memory address
to be between 0 to 63, {$random} % 64 is used. The model-based generators use this
model to produce the correct stimuli for the target design. The stimulus generator
should be intelligent and easily controllable.

Bus Functional Models

The Bus Functional Model (BFM) for a device interacts with the DUT by both driving
and sampling the DUT signals. A bus functional model is a model that provides a task
or procedural interface to specify certain bus operations for a defined bus protocol.
For a memory DUT, transactions usually take the form of read and write operations.
Bus functional models are easy to use and provide good performance. It has to follow
the timing protocol of the DUT interface. BFM describes the functionality and provides
a cycle accurate interface to DUT. It models external behavior of the device. For re
usability, the implementation of the BFM functionality should be kept as independent
of the communication to the BFM as it can be.

Driver

Driver is a types of BFM. The drivers translate the stimuli produced by the generator
into the actual inputs for the design under verification. Generators create inputs at a
high level of abstraction; namely, as transactions like read write operation. The
drivers convert this input into actual design inputs which is at a low level like bits ,as
defined in the specification of the designs interface. If the generator generates read
operation, then read task is called, in that, the DUT input pin "read_write" is asserted.

Reciver

Receiver is also a type of BFM. The output of the DUT is collected. The output of the
DUT is available in a low level format. Let<92>s take a packet protocol. The interface
has "start of the packet" and "end of packet" signal to indicate the packet arrival. The
receiver starts collecting the packet looking at the signal "start of packet" and does
this job until "end of the packet".

Protocol Monitor:

Protocol monitor do not drive any signals, monitor the DUT outputs, identifies all the
transactions and report any protocol violations. The monitor converts the state of the
design and its outputs to a transaction abstraction level so it can be stored in a 'score-
boards' database to be checked later on. Again let<92>s take a packet protocol. The
monitor gets the information from the packet like, length of the packet, address of
the packet etc.

Scoreboard:

Scoreboard is sometimes referred as storage structure. The stimulus generator


generated the random vectors. These are derived to the dut. These stimulus are
stored in scoreboard until the output comes out of the DUT. When a write operation is

http://testbench.in/TB_06_SELF_CHECKING_TESTBENCH.html[9/26/2012 2:37:37 PM]


WWW.TESTBENCH.IN - Verilog for Verification

done on a memory with address 101 and data 202,asfter some cycles, if a read is done
at address 101,what should be the data?.The score board recorded the address and
data when write operation is done. Get the data stored at address of 101 in
scoreboard and compare with the output of the DUT in checker. Scoreboard also has
expected logic if needed. Take an 2 input and gate. The expect logic does the " and "
operation on the two inputs and stores the output.

Checker:

Checker is part of score board. The checker validates that the contents of the 'score-
boards' are legal. There are cases where the generator creates expected results, in
addition to the inputs. In these cases, the checker must validate that the actual
results match the expected ones.

Coverage:

Coverages are of two types, Functional coverage and code coverage. Code coverage is
not part of Testbench. Functional Coverage is part of test bench. Functional coverage
cannot be done in Verilog.

Code Coverage:

Code coverage, in short, is all about how thoroughly your tests exercise your code
base. The intent of tests, of course, is to verify that your code does what it's
expected to, but also to document what the code is expected to do. Taken further,
code coverage can be considered as an indirect measure of quality -- indirect because
we're talking about the degree to what our tests cover our code, or simply, the
quality of tests. In other words, code coverage is not about verifying the end product's
quality.

Statement coverage: measures the number of statements executed .


Branch coverage: measures the expressions and case statements that affect the
control flow of the HDL execution
Condition coverage: breaks down the condition on the branch into elements that make
the result true or false
Toggle coverage: counts low-to-high and high-to-low transitions
Finite State Machine: state and state transition coverage

Functional Coverage:

Functional is the metric which shows how much we have verified. It shows how many
possible scenarios are possible and how many are covered. Take a memory. If the
memory address is 64 byte depth, and if the address is generated randomly, we are
not sure that every location is covered. Functional coverages gives report how many
address are possible and how may we have covered.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TB_06_SELF_CHECKING_TESTBENCH.html[9/26/2012 2:37:37 PM]


WWW.TESTBENCH.IN - Verilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS VERIFICATION FLOW Index


Introduction
SystemVerilog Linear Tb
Verification Verification of a design usually follows the flow synopsis below. File Io Tb
State Machine Based Tb
Constructs Planning: Task Based Tb
Interface Self Checking Testbench
After the preliminary design specification is completed, the first verification phase is Verification Flow
OOPS Clock Generator
started Verification planning.
Randomization Simulation
Verification planning consists, following main tasks. Incremental Compilation
Functional Coverage Store And Restore
Assertion 1) Feature extraction from design specification. Event Cycle Simulation
2) Listing out Testcases. Time Scale And Precision
DPI Stimulus Generation
3) Verification Environment Architecture plan.
UVM Tutorial System Function Random
A Myth
VMM Tutorial Race Condition
Feature Extraction:
OVM Tutorial Checker
Extract all the features of the DUT from the design specification. Task And Function
Easy Labs : SV
Mainly the features are configuration, Interface protocol, data processing protocol Process Control
Easy Labs : UVM and status communication. Disableing The Block
Categorizing all this features according to where these features are verified. Watchdog
Easy Labs : OVM
What are the features covered by random stimulus generation? Compilation N Simulation
Easy Labs : VMM What are the features verifiable by writing separate test cases? Switchs
AVM Switch TB What features assertions can catch? Debugging
What features the coverage module contains? About Code Coverage
VMM Ethernet sample Testing Stratigies
File Handling
Verification Environment Architecture Plan: Verilog Semaphore
Verilog Finding Testsenarious
Verification plan contains the structure of the Verification environment. Based on the Handling Testcase Files
Verification
project requirements, following points are considered while Architecture is built. Terimination
Verilog Switch TB Reusability, Is it a verification IP. What blocks the verification language can support. Error Injuction
Controllability of the stimulus generation etc. Register Verification
Basic Constructs
Parameterised Macros
Next phase is to build the Verification environment. White Gray Black Box
Final phase is to verify the DUT using the environment built. Regression
OpenVera Tips
Constructs
Report a Bug or Comment
Switch TB
on This section - Your
RVM Switch TB input is what keeps
Testbench.in improving
RVM Ethernet sample
with time!

Specman E
Interview Questions

http://testbench.in/TB_07_VERIFICATION_FLOW.html[9/26/2012 2:37:44 PM]


WWW.TESTBENCH.IN - Verilog for Verification

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TB_07_VERIFICATION_FLOW.html[9/26/2012 2:37:44 PM]


WWW.TESTBENCH.IN - Verilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS CLOCK GENERATOR Index


Introduction
SystemVerilog Linear Tb
Verification Clocks are the main synchronizing events to which all other signals are referenced. If File Io Tb
the RTL is in verilog, the Clock generator is written in Verilog even if the TestBench is State Machine Based Tb
Constructs written in other languages like Vera, Specman or SystemC. Clock can be generated Task Based Tb
Interface many ways. Some testbenchs need more than one clock generator. So testbench need Self Checking Testbench
clock with different phases some other need clock generator with jitter. The very first Verification Flow
OOPS Clock Generator
transition of clock at time zero may be perceived as a transition because clock has an
Randomization unknown value before time zero and gets assigned to a value at time zero. How this Simulation
time zero clock transition is perceived is simulator dependent, and thus care must be Incremental Compilation
Functional Coverage Store And Restore
taken.
Assertion Fallowing examples show simple clock generators with 50% duty cycles. Event Cycle Simulation
Time Scale And Precision
DPI Stimulus Generation
EXAMPLE:
UVM Tutorial initial clk = 0;  System Function Random
always #10 clk = ~clk;  A Myth
VMM Tutorial Race Condition
OVM Tutorial EXAMPLE: Checker
always   Task And Function
Easy Labs : SV
begin   Process Control
Easy Labs : UVM    clk = 0;  Disableing The Block
   #10;  Watchdog
Easy Labs : OVM
   clk = 1;  Compilation N Simulation
Easy Labs : VMM    #10;  Switchs
AVM Switch TB end   Debugging
About Code Coverage
VMM Ethernet sample EXAMPLE: Testing Stratigies
always   File Handling
begin   Verilog Semaphore
Verilog    clk = 0;  Finding Testsenarious
   forever #10 clk = ~clk;  Handling Testcase Files
Verification
end   Terimination
Verilog Switch TB Error Injuction
Different testbenchs need different clock periods. It is beneficial to use parameters to Register Verification
Basic Constructs
represent the delays, instead of hard coding them. For example, to generate a clock Parameterised Macros
starting with zero that has a 50% duty cycle, the following code can be used: White Gray Black Box
Regression
OpenVera EXAMPLE: Tips
Constructs module Tb(); 
   reg clock;  Report a Bug or Comment
Switch TB
   integer no_of_clocks;  on This section - Your
RVM Switch TB    input is what keeps
Testbench.in improving
RVM Ethernet sample    parameter CLOCK_PERIOD = 5; 
   initial no_of_clocks = 0;  with time!
   initial clock = 1'b0; 
  
Specman E    always #(CLOCK_PERIOD/2) clock = ~clock; 
Interview Questions   
   always@(posedge clock) 
   no_of_clocks = no_of_clocks +1 ; 
  
   initial 
   begin 
      #50000; 
      $display("End of simulation time is %d , total number of clocks seen is %d
expected is %d",$time,no_of_clocks,($time/5)); 
      $finish; 
   end 

http://testbench.in/TB_08_CLOCK_GENERATOR.html[9/26/2012 2:37:54 PM]


WWW.TESTBENCH.IN - Verilog for Verification

endmodule 
RESULTS:

End of simulation time is 50000 , total number of clocks seen is 12500 expected is
10000

Total number of clocks are 12500 and the expected are 1000.There are 25 % of more
clocks than expected. The reason is half clock period is 2 insted of 2.5.
Make sure that CLOCK_PERIOD is evenly divided by two. If CLOCK_PERIOD is odd, the
reminder is truncated the frequency of the clock generated in not what expected. If
integer division is replaced by real division, the result is rounded off according to the
specified resolution.

EXAMPLE:
module Tb(); 
   reg clock; 
   integer no_of_clocks; 
  
   parameter CLOCK_PERIOD = 5; 
  
   initial no_of_clocks = 0; 
   initial clock = 1'b0; 
  
   always #(CLOCK_PERIOD/2.0) clock = ~clock; 
  
   always@(posedge clock) 
      no_of_clocks = no_of_clocks +1 ; 
  
   initial 
   begin 
      #50000; 
      $display("End of simulation time is %d , total number of clocks seen is %d
expected is %d",$time,no_of_clocks,($time/5)); 
      $finish; 
   end 
endmodule 

RESULTS:

End of simulation time is 50000 , total number of clocks seen is 8333 expected is
10000

Look at the result, total number of clock seen are 8333, where the rest of the clocks
have gone? There is some improvement than earlier example. But the results are not
proper. Well that is because of `timeprecision. By default time precision is 1ns/1ns.
Half of the clock period is 2.5 . It is rounded of to 3 . So total time period is 6 and
resulted 8333 clocks( 50000/6) instead of (50000/5). 2.5 can be rounded to 3 or 2 .
LRM is specific about this. So try out this example on your tool. You may see 12500.

Timescale And Precision Enlightment:

Delay unit is specified using 'timescale, which is declared as `timescale time_unit base
/ precision base
--time_unit is the amount of time a delay of 1 represents. The time unit must be 1 10
or 100
--base is the time base for each unit, ranging from seconds to femtoseconds, and
must be: s ms us ns ps or fs
--precision and base represent how many decimal points of precision to use relative
to the time units.

Time precision plays major role in clock generators. For example, to generate a clock
with 30% duty cycle and time period 5 ns ,the following code has some error.

http://testbench.in/TB_08_CLOCK_GENERATOR.html[9/26/2012 2:37:54 PM]


WWW.TESTBENCH.IN - Verilog for Verification

EXAMPLE:
`timescale 1ns/100ps
module Tb(); 
   reg clock; 
   integer no_of_clocks; 

   parameter CLOCK_PERIOD = 5; 
   initial clock = 1'b0; 
   always 
   begin 
       #(CLOCK_PERIOD/3.0) clock = 1'b0; 
       #(CLOCK_PERIOD - CLOCK_PERIOD/3.0) clock = 1'b1; 
   end 
  
   initial no_of_clocks = 0; 
  
   always@(posedge clock) 
       no_of_clocks = no_of_clocks +1 ; 
  
   initial 
   begin 
       #50000; 
       $display(" End of simulation time is %d , total number of clocks seen is %d
expected is %d",$time,no_of_clocks,($time/5)); 
       $finish; 
   end 
endmodule 
RESULTS:

End of simulation time is 50000 , total number of clocks seen is 9999 expected is
10000

Now CLOCK_PERIOD/3.0 is 5/3 which is 1.666. As the time unit is 1.0ns, the delay is
1.666ns. But the precision is 100ps. So 1.666ns is rounded to 1.700ns only.
and when (CLOCK_PERIOD - CLOCK_PERIOD/3.0) is done, the delay is 3.300ns instead
of 3.333.The over all time period is 5.If the clock generated is implemented without
taking proper care, this will be the biggest BUG in testbench.

All the above clock generators have hard coded duty cycle. The following example
shows the clock generation with parameterizable duty cycle. By changing the
duty_cycle parameter, different clocks can be generated. It is beneficial to use
parameters to represent the delays, instead of hard coding them. In a single
testbench, if more than one clock is needed with different duty cycle, passing duty
cycle values to the instances of clock generators is easy than hard coding them.  

NOTE: Simulation with `timescale 1ns/1ns is faster than `timescale 1ns/10ps


A simulation using a `timescale 10ns/10ns and with `timescale 1ns/1ns  will take
same time.

EXAMPLE:
   parameter CLK_PERIOD  = 10;  
   parameter DUTY_CYCLE  = 60; //60% duty cycle
   parameter TCLK_HI = (CLK_PERIOD*DUTY_CYCLE/100); 
   parameter TCLK_LO = (CLK_PERIOD-TCLK_HI); 
  
   reg clk; 

   initial 
      clk = 0; 

   always 
   begin 
      #TCLK_LO; 
      clk = 1'b1; 
      #TCLK_HI; 
      clk = 1'b0; 
   end  

http://testbench.in/TB_08_CLOCK_GENERATOR.html[9/26/2012 2:37:54 PM]


WWW.TESTBENCH.IN - Verilog for Verification

Make sure that parameter values are properly dividable. The following example
demonstrates how the parameter calculations results. A is 3 and when it is divided by
2,the result is 1.If integer division is replaced by real division, the result is rounded
off according to the specified resolution. In the following example is result of real
number division.

EXAMPLE:
    module Tb(); 

    parameter A = 3; 
    parameter B = A/2; 
    parameter C = A/2.0; 

    initial 
    begin 
        $display(" A is %e ,B is %e ,C is %e ",A,B,C); 
    end 

    endmodule 
RESULTS:

A is 3.000000e+00 ,B is 1.000000e+00 ,C is 1.500000e+00  

Often clockgenerators are required to generate clock with jitter.The following is


simple way to generate clock with jitter.

EXAMPLE:
   initial clock = 1'b0; 
  
   always clock = #1 ~clock; 
   jitter = $random() % range; 
  
   assign jittered_clock = #(jitter) clock; 
  

With the above approace,over all clock period is increased. A better approach for
clock divider is as follows

EXAMPLE:
    parameter DELAY = TIMEPERIOD/2.0 - range/2.0; 
    initial clock = 1'b0; 
    
    always 
    begin 
       jitter = $dist_uniform(seed,0,jitter_range); 
       #(DELAY + jitter) clock = ~clock; 
    end 

Clock dividers and multipliers are needed when more than one clock is needed to be
generated from base clock and it should be deterministic. Clock multipliers are simple
to design. A simple counter does this job. Clock division is little bit tricky. TO design a
lock divider i.e a frequency multiplier, first the time period has to be captured and
then it is used to generate another clock. With the following approach, the jitter in
the base clock is carried to derived clock.

EXAMPLE:Clock multipler with N times multiplication


   initial i = 0; 
  
   always @( base_clock ) begin 
       i = i % N; 
       if (i == 0) derived_clock = ~derived_clock; 
       i = i + 1; 
   end 

EXAMPLE:Clock division with N times division


    initial begin 
        derived_clock = 1'b0; 
        period = 10; // for initial clock  
        forever derived_clock = #(period/(2N)) ~ derived_clock; 
    end  

http://testbench.in/TB_08_CLOCK_GENERATOR.html[9/26/2012 2:37:54 PM]


WWW.TESTBENCH.IN - Verilog for Verification

    
    always@(posedge base_clock)  
    begin 
        T2 = $realtime; 
        period = T2 - T1; 
        T1 = T2; 
    end 

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TB_08_CLOCK_GENERATOR.html[9/26/2012 2:37:54 PM]


WWW.TESTBENCH.IN - Verilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS SIMULATION Index


Introduction
SystemVerilog Simulation Steps: Linear Tb
Verification File Io Tb
Simulation is defined as the process of creating a model (i.e., an abstract State Machine Based Tb
Constructs representation) of a system  in order to identify and understand those factors which Task Based Tb
Interface control the system and/or to predict (forecast) the future behavior of the Self Checking Testbench
system.  The simulation model need not reflect any understanding of the underlying Verification Flow
OOPS Clock Generator
technology, and the simulator need not know that the design is intended for any
Randomization specific technology. Simulation
Incremental Compilation
Functional Coverage Store And Restore
The underlying purpose of simulation is to shed light on the underlying mechanisms
Assertion that control the behavior of a system. More practically, simulation can be used to Event Cycle Simulation
predict (forecast) the future behavior of a system, and determine what you can do to Time Scale And Precision
DPI Stimulus Generation
influence that future behavior. That is, simulation can be used to predict the way in
UVM Tutorial which the system will evolve and respond to its surroundings, so that you can identify System Function Random
any necessary changes that will help make the system perform the way that you want A Myth
VMM Tutorial Race Condition
it to.
OVM Tutorial Checker
Task And Function
Easy Labs : SV
Simulation Eliminates the time-consuming need for constant physical Process Control
Easy Labs : UVM prototyping.  Simulation should be performed during ALL stages of ASIC design. Disableing The Block
Watchdog
Easy Labs : OVM
Compilation N Simulation
Easy Labs : VMM Macro Preprocessing: Switchs
AVM Switch TB Debugging
The macro preprocessing step performs textual substitutions of macros defined with About Code Coverage
VMM Ethernet sample `define statements, textual inclusion with `include statements, and conditional Testing Stratigies
compilation by `ifdef and `ifndef statements. File Handling
Verilog Semaphore
Verilog Finding Testsenarious
Compilation (Analyzer) Handling Testcase Files
Verification
Terimination
Verilog Switch TB Checks source code to check  syntax and semantic rules. If a syntax or semantic error Error Injuction
occurs, then the compiler gives error message. If there are no errors , compilation Register Verification
Basic Constructs
produces an internal representation for each HDL design unit. Parameterised Macros
White Gray Black Box
Regression
OpenVera Elaboration Tips
Constructs
The elaboration process constructs a design hierarchy based on the instantiation and Report a Bug or Comment
Switch TB
configuration information in the design, establishes signal connectivity . Memory on This section - Your
RVM Switch TB storage is allocated for the required signals. The elaboration process creates a input is what keeps
Testbench.in improving
RVM Ethernet sample hierarchy of module instances that ends with primitive gates and statements.
with time!

Optimization:
Specman E
Interview Questions Some tools support optimization at this level. This is optional step.

Initialization :

Initial values preset in the declarations statement are assigned to signals / variables.

Execution

Every process is executed until it suspends. Signal values are updated only after the

http://testbench.in/TB_09_SIMULATION.html[9/26/2012 2:38:03 PM]


WWW.TESTBENCH.IN - Verilog for Verification

process suspends. Simulator accepts simulation commands like (run, assign, watch),
which control the simulation of the system and specify the desired simulator
output.  Simulation ends  when all signals have been updated and new values have
been assigned to signals. This design hierarchy is stored in a simulation snapshot. The
snapshot is the representation of your design that the simulator uses to run the
simulation.

Simulation Process :

When Simulation time is incremented, On receiving Simulation commands, a signal is


updated. All processes sensitive to that signal are placed on a ¿Process Execution¿
queue. Each resumed process is executed until it suspends. Effects of the logic
changes that have occurred as a result of process execution are evaluated. Simulation
time is set to the next event in queue, or halted if simulation time is exhausted.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TB_09_SIMULATION.html[9/26/2012 2:38:03 PM]


WWW.TESTBENCH.IN - Verilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INCREMENTAL COMPILATION Index


Introduction
SystemVerilog Linear Tb
Verification Incremental compilation means that the compiler inspects your code, determines File Io Tb
which parts of the application are affected by your changes, and only recompiles the State Machine Based Tb
Constructs newer files. Incremental compilation can help reduce compile time on small Task Based Tb
Interface applications, but you achieve the biggest gains on larger applications. The default Self Checking Testbench
value of the incremental compiler option is true for most tools. Verification Flow
OOPS Clock Generator
Randomization Simulation
While recompiling , Incremental compilation does less work than full recompile. The Incremental
Functional Coverage Compilation
simulation doesn't show any difference , only the compilation time is
Assertion reduced.  Imagine you are working with hundreds of files and U just changed one file, Store And Restore
During full recompilation , all the files are recompiled, where in incremental Event Cycle Simulation
DPI Time Scale And Precision
compilation , only the file which is changed and the files which are dependent on
UVM Tutorial changed files are compiled and linked to the already compiled database. Stimulus Generation
System Function Random
VMM Tutorial A Myth
OVM Tutorial Race Condition
Checker
Easy Labs : SV
Task And Function
Easy Labs : UVM Process Control
Disableing The Block
Easy Labs : OVM
Watchdog
Easy Labs : VMM Compilation N Simulation
AVM Switch TB Switchs
Debugging
VMM Ethernet sample About Code Coverage
Testing Stratigies
File Handling
Verilog Verilog Semaphore
Finding Testsenarious
Verification
Handling Testcase Files
Verilog Switch TB Terimination
Error Injuction
Basic Constructs
Register Verification
Parameterised Macros
White Gray Black Box
OpenVera Regression
Constructs Tips
Switch TB
Report a Bug or Comment
RVM Switch TB on This section - Your
input is what keeps
RVM Ethernet sample
Testbench.in improving
with time!

Specman E
Interview Questions

http://testbench.in/TB_10_INCREMENTAL_COMPILATION.html[9/26/2012 2:38:12 PM]


WWW.TESTBENCH.IN - Verilog for Verification

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TB_10_INCREMENTAL_COMPILATION.html[9/26/2012 2:38:12 PM]


WWW.TESTBENCH.IN - Verilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS STORE AND RESTORE Index


Introduction
SystemVerilog Incremental compilation means that the compiler inspects your code, determines Linear Tb
Verification which parts of the application are affected by your changes, and only recompiles the File Io Tb
newer files. Incremental compilation can help reduce compile time on small State Machine Based Tb
Constructs applications, but you achieve the biggest gains on larger applications. The default Task Based Tb
Interface value of the incremental compiler option is true for most tools. Self Checking Testbench
Verification Flow
OOPS Clock Generator
Randomization While recompiling , Incremental compilation does less work than full recompile. The Simulation
simulation doesn't show any difference , only the compilation time is Incremental Compilation
Functional Coverage Store And Restore
reduced.  Imagine you are working with hundreds of files and U just changed one file,
Assertion During full recompilation , all the files are recompiled, where in incremental Event Cycle Simulation
compilation , only the file which is changed and the files which are dependent on Time Scale And Precision
DPI Stimulus Generation
changed files are compiled and linked to the already compiled database.
UVM Tutorial System Function Random
Save and Restore saves the complete state of the simulator to a file that can be used A Myth
VMM Tutorial Race Condition
to restart simulation at the point of the save.
OVM Tutorial Checker
Task And Function
Easy Labs : SV
If multiple simulation, have same property for several hours of simulation, then the Process Control
Easy Labs : UVM simulation state can be shared across all the simulation. For example, In System Level Disableing The Block
verification, it takes more than a day for operating system to boot in RTL, then the Watchdog
Easy Labs : OVM
testing scenarios starts. This boot operations in RTL can be saved to a state. Using Compilation N Simulation
Easy Labs : VMM this saved state, user can directly start simulation from the saved point. Typically, Switchs
AVM Switch TB once a bug is discovered, perhaps hours or days into a simulation, the simulation Debugging
would need to be repeated for hours or days to verify the bug fix. In Verilog, the About Code Coverage
VMM Ethernet sample simulation state can be saved at any time and restored, to skips hours or days into a Testing Stratigies
simulation and validate a bug fix. This feature not only allows quick verification of File Handling
bug fixes, but enables much longer simulations by not rerunning previously validated Verilog Semaphore
Verilog code. Finding Testsenarious
Handling Testcase Files
Verification
Three system tasks $save, $restart, and $incsave work in conjunction with one Terimination
Verilog Switch TB another to save the complete state of simulation into a permanent file such that the Error Injuction
simulation state can be reloaded at a later time and processing can continue where it Register Verification
Basic Constructs
left off. Parameterised Macros
White Gray Black Box
Regression
OpenVera Tips
Constructs EXAMPLE:
Report a Bug or Comment
Switch TB
$save("file_name"); on This section - Your
RVM Switch TB $restart("file_name"); input is what keeps
Testbench.in improving
RVM Ethernet sample $incsave("incremental_file_name");
with time!

All three system tasks take a file name as a parameter. The file name has to be
Specman E supplied as a string enclosed in quotation marks.
Interview Questions
The $save system task saves the complete state into the host operating system file
specified as a parameter.

The $incsave system task saves only what has changed since the last invocation of
$save. It is not possible to do an incremental save on any file other than the one
produced by the last $save.

The $restart system task restores a previously saved state from a specified file.

Restarting from an incremental save is similar to restarting from a full save, except

http://testbench.in/TB_11_STORE_AND_RESTORE.html[9/26/2012 2:38:22 PM]


WWW.TESTBENCH.IN - Verilog for Verification

that the name of the incremental save file is specified in the restart command. The
full save file that the incremental save file was based upon shall still be present, as it
is required for a successful restart. If the full save file has been changed in any way
since the incremental save was performed, errors will result.

Take care while using Pli application . Since PLI application may have some other form
of simulation snapshot storage, the simulation tool doesn't have the control on them.
$save system task, creates a checkpoint file and PLI tr routines are there to save the
PLI snapshot.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TB_11_STORE_AND_RESTORE.html[9/26/2012 2:38:22 PM]


WWW.TESTBENCH.IN - Verilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS EVENT CYCLE SIMULATION Index


Introduction
SystemVerilog Event Based Simulation Linear Tb
Verification File Io Tb
Event simulation typically traces every signal transition and continues this until stable State Machine Based Tb
Constructs state is reached. Simulation based on events in logic, which means, whenever there is Task Based Tb
Interface change in a input event, the output is evaluated. Means both timing and functional Self Checking Testbench
information is available. With this glitches in signal changes can be observed. Event Verification Flow
OOPS Clock Generator
based simulators are slow when compared with cycle based simulators.
Randomization Simulation
Incremental Compilation
Functional Coverage Store And Restore
Cycle Based Simulation
Assertion Event Cycle Simulation
Cycles based simulator takes the advantage of the fact that most digital circuits are Time Scale And Precision
DPI Stimulus Generation
synchronous in nature.  Cycle simulation typically re-evaluates the state of the circuit
UVM Tutorial as a whole, once upon each external trigger, usually without evaluating any System Function Random
intermediate node states. Cycle based simulator is very fast compared to event based A Myth
VMM Tutorial Race Condition
simulator. Disadvantage of cycle based simulator are it cannot detect glitches and
OVM Tutorial setup and hold checks cannot be done. In cycle based simulators, delays cannot be Checker
specified. Task And Function
Easy Labs : SV
Process Control
Easy Labs : UVM Disableing The Block
Watchdog
Easy Labs : OVM
Compilation N Simulation
Easy Labs : VMM Switchs
AVM Switch TB Debugging
About Code Coverage
VMM Ethernet sample Testing Stratigies
File Handling
Verilog Semaphore
Verilog Finding Testsenarious
Handling Testcase Files
Verification
Terimination
Verilog Switch TB Error Injuction
Register Verification
Basic Constructs
Parameterised Macros
White Gray Black Box
Regression
OpenVera Tips
Constructs
Report a Bug or Comment
Switch TB
on This section - Your
RVM Switch TB input is what keeps
Testbench.in improving
RVM Ethernet sample
with time!

Specman E
Interview Questions

http://testbench.in/TB_12_EVENT_CYCLE_SIMULATION.html[9/26/2012 2:38:29 PM]


WWW.TESTBENCH.IN - Verilog for Verification

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TB_12_EVENT_CYCLE_SIMULATION.html[9/26/2012 2:38:29 PM]


WWW.TESTBENCH.IN - Verilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS TIME SCALE AND PRECISION Index


Introduction
SystemVerilog Time Scale And Time Precision: Linear Tb
Verification File Io Tb
RECAP:  State Machine Based Tb
Constructs Task Based Tb
Interface Delay unit is specified using 'timescale, which is declared as `timescale time_unit base Self Checking Testbench
/ precision base Verification Flow
OOPS Clock Generator
--time_unit is the amount of time a delay of #1 represents. The time unit must be 1
Randomization 10 or 100 Simulation
--base is the time base for each unit, ranging from seconds to femtoseconds, and Incremental Compilation
Functional Coverage Store And Restore
must be: s ms us ns ps or fs
Assertion --precision and base represent how many decimal points of precision to use relative Event Cycle Simulation
to the time units. Time Scale And
DPI Precision
UVM Tutorial For example : `timescale 1 ns / 100 ps means Stimulus Generation
time values to be read as ns and to be rounded to the nearest 100 ps. System Function Random
VMM Tutorial A Myth
OVM Tutorial If timescale is omitted, there is a default time scale. Race Condition
Checker
Easy Labs : SV
The following examples demonstrate how the time scale and time precision effect Task And Function
Easy Labs : UVM $stime, #delay and toggling in waveform. Process Control
Disableing The Block
Easy Labs : OVM
EXAMPLE: Watchdog
Easy Labs : VMM    `timescale 10ns/10ns Compilation N Simulation
AVM Switch TB    Switchs
   module tim();  Debugging
VMM Ethernet sample       reg i;  About Code Coverage
Testing Stratigies
      initial  File Handling
Verilog       begin  Verilog Semaphore
         i=0;  Finding Testsenarious
Verification
         #7.7212;  Handling Testcase Files
Verilog Switch TB          i=1;  Terimination
         $display("STATEMENT 1 :: time is ",$stime);  Error Injuction
Basic Constructs
         #7.123;  Register Verification
         $finish;  Parameterised Macros
      end  White Gray Black Box
OpenVera        Regression
Constructs    endmodule  Tips
Switch TB    module try; 
       Report a Bug or Comment
RVM Switch TB       time delay_time = 7.721;  on This section - Your
input is what keeps
RVM Ethernet sample
      initial begin  Testbench.in improving
      $display("STATEMENT 2 :: delay for %0t",delay_time     );  with time!
      end 
Specman E    endmodule 
Interview Questions   
RESULTS:

STATEMENT 1 :: time is 8
STATEMENT 2 :: delay for 8

reg i toggled at 80 in waveform debugger

EXAMPLE:
`timescale 10ns/1ns
module tim(); 

http://testbench.in/TB_13_TIME_SCALE_AND_PRECISION.html[9/26/2012 2:38:38 PM]


WWW.TESTBENCH.IN - Verilog for Verification

    reg i; 
    initial 
    begin 
        i=0; 
        #7.7212; 
        i=1; 
        $display("STATEMENT 1 :: time is ",$stime); 
        #7.123; 
        $finish; 
    end 
    
endmodule 

module try; 

   time delay_time = 7.721; 
   initial begin 
      $display("STATEMENT 2 :: delay for %0t",delay_time     ); 
   end 
endmodule 
RESULTS:

STATEMENT 1 :: time is 8
STATEMENT 2 :: delay for 80

reg i toggled at 77 waveform debugger

EXAMPLE:
`timescale 10ns/1ps
module tim(); 
    reg i; 

    initial 
    begin 
        i=0; 
        #7.7212; 
        i=1; 
        $display("STATEMENT 1 :: time is ",$stime); 
        #7.123; 
        $finish; 
    end 
    
endmodule 
module try; 

    time delay_time = 7.721; 
    initial begin 
        $display("STATEMENT 2 :: delay for %0t",delay_time     ); 
    end 
endmodule 

RESULTS:

STATEMENT 1 :: time is 8
STATEMENT 2 :: delay for 80000

reg i toggled at 77.212 in waveform debugger

In the timescale statement, the first value is the time unit and the second is the
precision for the simulation. So with the time unit, when the simulator displays a
value, you just have to multiply the value by this time unit to get the real time. With
a 10ns time unit, when a delay of #7.7212, that means that it is 77.212ns delay.

http://testbench.in/TB_13_TIME_SCALE_AND_PRECISION.html[9/26/2012 2:38:38 PM]


WWW.TESTBENCH.IN - Verilog for Verification

Now the second one (time precision) specify with which precision time values are
rounded. Asking for a 77.212ns delay is possible only with a 1ps precision. That's what
you can see with reg i. It toggles at 77ns with a 1ns precision and 77.212 with a 1ps
precision.

For the STATEMENT 1, $stime returns an integer scaled to timesale unit, that's why
results are always 8 which is 7.7212 rounded up to 8.

Now for STATEMENT 2, the way %t is printed depends on $timeformat. It seems that in
this case, 7.7212 is first rounded to an integer => 8 and then printed according to your
time precision.
Im not sure of this topic. If some one finds mistake in my understanding, please mail
me at gopi@testbench.in

Each module can have separate time scale. The smallest time_precision argument of
all the timescale compiler directives in the design determines the precision of the
time unit of the simulation.

Lets take an example. There are two modules. Module_1 is instance od Module_2.
Module_1 has timescale of 1 ns/1ps. Module_2 has time scale of 1ns / 10ps. The
smallest resolution is 1ps. This is taken as simulator resolution but each module
evaluates according to its precision mentioned.  

Lets take another example. There are two modules. Module_1 is instance of
Module_2. Module_1 does not have any time scale. Module_2 is having time scale of
1ns/100 ps. As there is no time scale for Module_1 ,the simulator takes precision and
time unit of 100 ps i.e `timescale 100 ps/100 ps.

$Time Vs $Realtime

$time round offs the time to nearby integer where as $realtime does not. So when
you are using real valued delays, then use $realtime instead of $time , else there may
be a misunderstanding during debugging.

System Task Printtimescale

The $printtimescale system task displays the time unit and precision for a particular
module. When no argument is specified, $printtimescale displays the time unit and
precision of the module that is the current scope. When an argument is specified,
$printtimescale displays the time unit and precision of the module passed to it.

EXAMPLE:
`timescale 1 ms / 1 us
module a_dat; 
   initial 
      $printtimescale(b_dat.c1); 
endmodule 

`timescale 10 fs / 1 fs
module b_dat; 
   c_dat c1 (); 
endmodule 

`timescale 1 ns / 1 ns
module c_dat; 

endmodule 

RESULTS:

Time scale of (b_dat.c1) is 1ns / 1ns

System Task Timeformat

The $timeformat system task performs the following two functions:


1)It specifies how the %t format specification reports time information for the $write,
$display,$strobe, $monitor, $fwrite, $fdisplay, $fstrobe, and $fmonitor group of
system tasks.

http://testbench.in/TB_13_TIME_SCALE_AND_PRECISION.html[9/26/2012 2:38:38 PM]


WWW.TESTBENCH.IN - Verilog for Verification

2)It specifies the time unit for delays entered interactively.

The units number argument shall be an integer in the range from 0 to -15. This
argument represents the time
unit as shown in table

Unit number Time unit Unit number Time unit


    0        1 s        -8         10 ns
   -1        100 ms     -9         1 ns
   -2        10 ms      -10        100 ps
   -3        1 ms       -11        10 ps
   -4        100 us     -12        1 ps
   -5        10 us      -13        100 fs
   -6        1 us       -14        10 fs
   -7        100 ns     -15        1 fs

Syntax : $timeformat(time unit, precision number, suffix string, and minimum field
width);

EXAMPLE:
`timescale 1 ms / 1 ns
module cntrl; 
    initial 
    $timeformat(-9, 5, " ns", 10); 
endmodule 

`timescale 1 fs / 1 fs
module a1_dat; 
    reg in1; 
    integer file; 

    buf #10000000 (o1,in1); 

    initial begin 
        file = $fopen("a1.dat"); 
        #00000000 $fmonitor(file,"%m: %t in1=%d o1=%h", $realtime,in1,o1); 
        #10000000 in1 = 0; 
        #10000000 in1 = 1; 
    end 
endmodule 

RESULTS:

a1_dat: 0.00000 ns in1= x o1=x


a1_dat: 10.00000 ns in1= 0 o1=x
a1_dat: 20.00000 ns in1= 1 o1=0
a1_dat: 30.00000 ns in1= 1 o1=1

EXAMPLE:
`timescale 1 ms / 1 ns
module cntrl; 
   initial 
     $timeformat(-9, 5, " ns", 10); 
endmodule 

`timescale 1 ps / 1 ps
module a2_dat; 
    reg in2; 
    integer file2; 

    buf #10000 (o2,in2); 

    initial begin 
        file2=$fopen("a2.dat"); 
        #00000 $fmonitor(file2,"%m: %t in2=%d o2=%h",$realtime,in2,o2); 
        #10000 in2 = 0; 
        #10000 in2 = 1; 
    end 
endmodule 

RESULTS:

http://testbench.in/TB_13_TIME_SCALE_AND_PRECISION.html[9/26/2012 2:38:38 PM]


WWW.TESTBENCH.IN - Verilog for Verification

a2_dat: 0.00000 ns in2=x o2=x


a2_dat: 10.00000 ns in2=0 o2=x
a2_dat: 20.00000 ns in2=1 o2=0
a2_dat: 30.00000 ns in2=1 o2=1

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TB_13_TIME_SCALE_AND_PRECISION.html[9/26/2012 2:38:38 PM]


WWW.TESTBENCH.IN - Verilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS STIMULUS GENERATION Index


Introduction
SystemVerilog Linear Tb
Verification   Verilog test benches range from simple descriptions signal values to descriptions that File Io Tb
test vector files and high level controllable descriptions that use functions or tasks State Machine Based Tb
Constructs .There are many ways to create input test vectors to test DUT. Hardcoded value is Task Based Tb
Interface simplest way of creating a test vectors. This I used to do when I was in schooling. As Self Checking Testbench
the number of inputs are less, this is comfortable to use.   Verification Flow
OOPS Clock Generator
Randomization Simulation
EXAMPLE: Incremental Compilation
Functional Coverage Store And Restore
module Tb_mem(); 
Assertion     reg clock;  Event Cycle Simulation
    reg read_write;  Time Scale And Precision
DPI Stimulus Generation
    reg [31:0] data; 
UVM Tutorial     reg [31:0] address;  System Function Random
     A Myth
VMM Tutorial Race Condition
    initial 
OVM Tutorial     begin  Checker
        clock = 0;  Task And Function
Easy Labs : SV
        forever   Process Control
Easy Labs : UVM            #10 clock = ~clock;  Disableing The Block
    end  Watchdog
Easy Labs : OVM
     Compilation N Simulation
Easy Labs : VMM     initial  Switchs
AVM Switch TB     begin  Debugging
        @(negedge clock)  read_write = 1 ; data = 4;address = 1;  About Code Coverage
VMM Ethernet sample         @(negedge clock)  read_write = 1 ; data = 5;address = 2;  Testing Stratigies
        @(negedge clock)  read_write = 1 ; data = 6;address = 3;  File Handling
        @(negedge clock)  read_write = 1 ; data = 7;address = 4;  Verilog Semaphore
Verilog         @(negedge clock)  read_write = 1 ; data = 8;address = 5;  Finding Testsenarious
        $finish;  Handling Testcase Files
Verification
    end  Terimination
Verilog Switch TB      Error Injuction
    initial  Register Verification
Basic Constructs
        $monitor($time,"read_write = %d ; data = %d ; address = Parameterised Macros
%d;",read_write,data,address);  White Gray Black Box
     Regression
OpenVera endmodule  Tips
Constructs
RESULT: Report a Bug or Comment
Switch TB
on This section - Your
RVM Switch TB  20read_write = 1 ; data = 4 ; address = 1; input is what keeps
Testbench.in improving
RVM Ethernet sample  40read_write = 1 ; data = 5 ; address = 2;
 60read_write = 1 ; data = 6 ; address = 3; with time!
 80read_write = 1 ; data = 7 ; address = 4;
Specman E
Interview Questions
Another way of getting the Stimulus is get the vectors from an external file. The
external vector file is generally formatted so that each value in the file represents
either a specific input pattern .Verilog HDL contains the $readmemb or $readmemh
system tasks to do the file read if the file data is formatted in a specific way using
either binary or hexadecimal data.

Fallowing example illustrates how to initialize a memory array from data stored as
hexadecimal values in a data file, Simulate this file directly to see the results.
Note: The data file must reside in the same directory  as the .v file for the module in
this example.

http://testbench.in/TB_14_STIMULUS_GENERATION.html[9/26/2012 2:38:47 PM]


WWW.TESTBENCH.IN - Verilog for Verification

EXAMPLE: verilog file


module readmemh_demo; 

   reg [31:0] Mem [0:11]; 
  
   initial $readmemh("data.txt",Mem); 
  
   integer k; 

   initial begin 
       #10; 
       $display("Contents of Mem after reading data file:"); 
       for (k=0; k<6; k=k+1) $display("%d:%h",k,Mem[k]); 
   end 
  
endmodule 

EXAMPLE: data.txt file


234ac
23ca5
b3c34
23a4a
234ca
b3234

RESULT:

0:000234ac
1:00023ca5
2:000b3c34
3:00023a4a
4:000234ca
5:000b3234

With the above approach,its not possible to list all the combinations manually if the
number of vectors get increases.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TB_14_STIMULUS_GENERATION.html[9/26/2012 2:38:47 PM]


WWW.TESTBENCH.IN - Verilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS SYSTEM FUNCTION RANDOM A MYTH Index


Introduction
SystemVerilog Linear Tb
Verification Verilog has system function $random ,which can be used to generate random input File Io Tb
vectors. With this approach, we can generate values which we wouldn't have got, if State Machine Based Tb
Constructs listed manually. In this topic I would like to discuss what natural things happening Task Based Tb
Interface behind $random and how we use it in different manners. Self Checking Testbench
Verification Flow
OOPS Clock Generator
Randomization EXAMPLE: Simulation
module Tb_mem();  Incremental Compilation
Functional Coverage Store And Restore
    reg clock; 
Assertion     reg read_write;  Event Cycle Simulation
    reg [31:0] data;  Time Scale And Precision
DPI Stimulus Generation
    reg [31:0] address; 
UVM Tutorial      System Function
    initial  Random A Myth
VMM Tutorial Race Condition
    begin 
OVM Tutorial         clock = 0;  Checker
        forever   Task And Function
Easy Labs : SV
           #10 clock = ~clock;  Process Control
Easy Labs : UVM     end  Disableing The Block
     Watchdog
Easy Labs : OVM
    initial  Compilation N Simulation
Easy Labs : VMM     begin  Switchs
AVM Switch TB         repeat(5)@(negedge clock)   Debugging
        begin read_write = $random ; data = $random;address = $random; end  About Code Coverage
VMM Ethernet sample         $finish;  Testing Stratigies
    end  File Handling
     Verilog Semaphore
Verilog     initial  Finding Testsenarious
        $monitor($time,"read_write = %d ; data = %d ; address = Handling Testcase Files
Verification
%d;",read_write,data,address);  Terimination
Verilog Switch TB      Error Injuction
endmodule  Register Verification
Basic Constructs
Parameterised Macros
RESULT: White Gray Black Box
Regression
OpenVera                  20read_write = 0 ; data = 3230228097 ; address = 2223298057; Tips
Constructs                  40read_write = 1 ; data = 112818957 ; address = 1189058957;
                 60read_write = 1 ; data = Report a Bug or Comment
2302104082 ; address = 15983361;
Switch TB
                 80read_write = 1 ; data = on This section - Your
992211318 ; address = 512609597;
RVM Switch TB input is what keeps
Testbench.in improving
RVM Ethernet sample
$random()  system function returns a new 32-bit random number each time it is with time!
called. The random number is a signed integer; it can be positive or negative. The
following example demonstrates random generation of signed numbers.
Specman E
Interview Questions
EXAMPLE:
module Tb(); 
    integer address; 
    
    initial 
    begin 
        repeat(5) 
        #1 address = $random; 
    end 
    

http://testbench.in/TB_15_SYSTEM_FUNCTION_RANDOM_A_MYTH.html[9/26/2012 2:38:57 PM]


WWW.TESTBENCH.IN - Verilog for Verification

    initial 
        $monitor("address = %d;",address); 
    
endmodule 

RESULT:

address = 303379748;
address = -1064739199;
address = -2071669239;
address = -1309649309;
address = 112818957;

We have seen how to generate random numbers. But the numbers range from - (2**32
-1) to 2 **32. Most of the time, the requirement don't need this range. For example,
take a memory. The address starts from 0 to some 1k or 1m.Generating a random
address which DUT is not supporting is meaningless. In verilog there are no constructs
to constraint randomization. Fallowing example demonstrated how to generate
random number between 0 to 10.Using % operation, the remainder of any number is
always between 0 to 10.

EXAMPLE:
module Tb(); 
    integer add_1; 

    initial 
    begin 
        repeat(5) 
        begin 
            #1; 
            add_1 = $random % 10; 
        end 
    end 
    
    initial 
        $monitor("add_1 = %d",add_1); 

endmodule 

RESULT:

add_1 = 8;
add_1 = 4294967287;
add_1 = 4294967295;
add_1 = 9;
add_1 = 9;

OOPS!...... The results are not what is expected. The reason is $random generates
negative numbers also. The following example demonstrates proper way of generating
a random number between 0 to 10. Concatenation operator returns only bit vector.
Bit vectors are unsigned, so the results are correct as we expected. Verilog also has
$unsigned systemtask to convert signed numbers to signed number. This can also be
used to meet the requirements. The following example shows the usage of
concatenation operator and $unsigned.

EXAMPLE:
module Tb(); 
     integer add_2; 
     reg [31:0] add_1; 

http://testbench.in/TB_15_SYSTEM_FUNCTION_RANDOM_A_MYTH.html[9/26/2012 2:38:57 PM]


WWW.TESTBENCH.IN - Verilog for Verification

     integer add_3; 
    
     initial 
     begin 
         repeat(5) 
         begin 
             #1; 
             add_1 = $random % 10; 
             add_2 = {$random} %10 ; 
             add_3 = $unsigned($random) %10 ; 
         end 
     end 
    
     initial 
     $monitor("add_3 = %d;add_2 = %d;add_1 = %d",add_3,add_2,add_1); 

endmodule 

RESULT:

add_3 = 7;add_2 = 7;add_1 = 8


add_3 = 7;add_2 = 7;add_1 = 4294967287
add_3 = 1;add_2 = 2;add_1 = 4294967295
add_3 = 7;add_2 = 8;add_1 = 9
add_3 = 9;add_2 = 2;add_1 = 9

The above example shows the generation of numbers from 0 to N.Some specification
require the range to start from non Zero number. MIN + {$random} % (MAX - MIN ) will
generate random numbers between MIN and MAX.

EXAMPLE:
module Tb(); 
    integer add; 
    
    initial 
    begin 
        repeat(5) 
        begin 
            #1; 
            add = 40 + {$random} % (50 - 40) ; 
            $display("add = %d",add); 
        end 
    end 
endmodule 

RESULT:

add = 48
add = 47
add = 47
add = 47
add = 47

Now  how to generate a random number between two ranges? The number should be
between MIN1 and MAX1 or MIN2 and MAX2.The following example show how to
generate this specification.

EXAMPLE:
module Tb(); 
    integer add; 
    
    initial 
    begin 
        repeat(5) 
        begin 
            #1; 
            if($random % 2) 
                add = 40 + {$random} % (50 - 40) ; 
            else 
                add = 90 + {$random} % (100 - 90) ; 

http://testbench.in/TB_15_SYSTEM_FUNCTION_RANDOM_A_MYTH.html[9/26/2012 2:38:57 PM]


WWW.TESTBENCH.IN - Verilog for Verification

            $display("add = %d",add); 
        end 
    end 
endmodule 

RESULT:

add = 97
add = 47
add = 47
add = 42
add = 49

All the random number generates above generate numbers of 32 vector. Not always
the requirements are 32 bit .For example, to generate a 5 bit and 45 bit vector
random number, the following method can be used.

EXAMPLE:
module Tb(); 
    reg [4:0]  add_1; 
    reg [44:0] add_2; 

    initial 
    begin 
        repeat(5) 
        begin 
            add_1 = $random ; 
            add_2 = {$random,$random}; 
            $display("add_1 = %b,add_2 = %b ",add_1,add_2); 
        end 
    end 
endmodule 

RESULTS:

add_1 = 00100,add_2 = 111101000000110000100100001001101011000001001  


add_1 = 00011,add_2 = 110110000110101000110110111111001100110001101  
add_1 = 00101,add_2 = 100100001001000000000111100111110001100000001  
add_1 = 01101,add_2 = 100010111011000011110100011011100110100111101  
add_1 = 01101,add_2 = 101111000110001111100111111011110100111111001  

Some protocols require a random number which is multiple some number. For
example, Ethernet packet is always in multiples of 8bits,and PCIExpress packets are
multiples of 4byts .Look at the following example. It generates a random number
which is multiple of 3 and 5.

EXAMPLE:
module Tb(); 
    integer num_1,num_2,tmp; 

    initial 
    begin 
        repeat(5) 
        begin 
            #1; 
            tmp = {$random} / 3; 
            num_1 = (tmp) * 3; 
            tmp = {$random} / 3; 
            num_2 = (tmp) * 5; 
            $display("num_1 = %d,num_2 = %d",num_1,num_2); 
        end 
    end 
endmodule 

RESULT:

   num_1 = 303379746,num_2 = -1064739195


   num_1 = -2071669239,num_2 = -1309649305
   num_1 = 112818957,num_2 = 1189058955

http://testbench.in/TB_15_SYSTEM_FUNCTION_RANDOM_A_MYTH.html[9/26/2012 2:38:57 PM]


WWW.TESTBENCH.IN - Verilog for Verification

   num_1 = -1295874969,num_2 = -1992863210


   num_1 = 15983361,num_2 = 114806025

All the above example show that the random numbers are integers only. In verilog
there is not special construct to generate a random real number. The following
method shows the generation of random real number.

EXAMPLE:
module Tb(); 

integer num_1,num_2,num_3; 
real r_num; 

   initial 
   begin 
       repeat(5) 
       begin 
           #1; 
           num_1 = $random; 
           num_2 = $random; 
           num_3 = $random; 
           r_num = num_1 + ((10)**(-(num_2)))*(num_3); 
           $display("r_num = %e",r_num); 
       end 
   end 
endmodule 

RESULT:

    r_num = -2.071669e+03
    r_num = 2641.189059e+013
    r_num = 976361.598336e+01
    r_num = 57645.126096e+02
    r_num = 24589.097015e+0

To generate random real number , system function $bitstoreal can also be used.

EXAMPLE:
module Tb(); 

   real r_num; 

   initial 
   begin 
       repeat(5) 
       begin 
          #1; 
          r_num = $bitstoreal({$random,$random}); 
          $display("r_num = %e",r_num); 
       end 
   end 
endmodule 

RESULTS:

   r_num = 1.466745e-221
   r_num = -6.841798e-287
   r_num = 2.874848e-276
   r_num = -3.516622e-64
   r_num = 4.531144e-304

If you want more control over randomizing real numbers in terms of sign, exponential
and mantissa, use $bitstoreal() as shown in example below. For positive numbers, use
sgn = 0 etc.

EXAMPLE:
module Tb(); 
    reg  sgn; 

http://testbench.in/TB_15_SYSTEM_FUNCTION_RANDOM_A_MYTH.html[9/26/2012 2:38:57 PM]


WWW.TESTBENCH.IN - Verilog for Verification

    reg [10:0] exp; 
    reg [51:0] man;  
    real r_num; 

    initial 
    begin 
        repeat(5) 
        begin 
            sgn = $random; 
            exp = $random; 
            man = $random; 
            r_num = $bitstoreal({sgn,exp,man}); 
            $display("r_num = %e",r_num); 
        end 
    end 
endmodule 
RESULTS:

   r_num = 3.649952e+193
   r_num = -1.414950e-73
   r_num = -3.910319e-149
   r_num = -4.280878e-196
   r_num = -4.327791e+273

Sometimes it is required to generate random numbers without repetition. The random


numbers should be unique. For example, to generate 10 random numbers b/w 0 to 9
without repetition, the following logic can be used.

EXAMPLE:
module Tb(); 
   integer num,i,j,index; 
   integer arr[9:0]; 
   reg ind[9:0]; 
   reg got; 
  
   initial 
   begin 
      index=0; 
      for(i=0;i<10;i=i+1) 
      begin 
         arr[i] = i; 
         ind[i] = 1; 
      end 

      for(j = 0;j<10 ;j=j+1) 
      begin 
         got = 0; 
         while(got == 0) 
         begin 
             index = { $random() } % 10; 
             if(ind[index] == 1) 
             begin 
                 ind[index] = 0; 
                 got = 1; 
                 num = arr[index]; 
             end 
         end 
         $write("| num=%2d |",num); 
      end 

   end 
endmodule 

RESULT:

| num= 8 || num= 7 || num= 5 || num= 2 || num= 1 || num= 9 || num= 6 || num= 4


|| num= 0 || num= 3 |

http://testbench.in/TB_15_SYSTEM_FUNCTION_RANDOM_A_MYTH.html[9/26/2012 2:38:57 PM]


WWW.TESTBENCH.IN - Verilog for Verification

Random number system function has a argument called seed. The seed parameter
controls the numbers that $random returns such that different seeds generate
different random streams. The seed parameter shall be either a reg, an integer, or a
time variable. The seed value should be assigned to this variable prior to calling
$random. For each system function, the seed parameter is an in-out parameter; that
is, a value is passed to the function
and a different value is returned.  

EXAMPLE:
module Tb(); 
   integer num,seed,i,j; 

   initial 
   begin 
       for(j = 0;j<4 ;j=j+1) 
       begin 
           seed = j; 
           $display(" seed is %d",seed); 
           for(i = 0;i < 10; i=i+1) 
           begin 
               num = { $random(seed) } % 10; 
               $write("| num=%2d |",num); 
           end 
           $display(" "); 
       end 
   end 
endmodule 

RESULT:

seed is 0
| num= 8 || num= 7 || num= 7 || num= 7 || num= 7 || num= 7 || num= 5 || num= 2
|| num= 1 || num= 9 |  
seed is 1
| num= 8 || num= 8 || num= 2 || num= 2 || num= 6 || num= 3 || num= 8 || num= 5
|| num= 5 || num= 5 |  
seed is 2
| num= 8 || num= 1 || num= 0 || num= 5 || num= 0 || num= 8 || num= 6 || num= 7
|| num= 1 || num= 6 |  
seed is 3
| num= 8 || num= 2 || num= 2 || num= 3 || num= 8 || num= 6 || num= 1 || num= 4
|| num= 3 || num= 9 |

The $random function has its own implicit variable as seed when the used is not giving
explicitly giving seed. The following example shows that seed = 0 and implicit seed
are having same sequence. It means that the implicitly taken seed is also 0.

EXAMPLE:
module Tb(); 
     integer num,seed,i,j; 

     initial 
     begin 
         seed = 0; 

         for(j = 0;j<2 ;j=j+1) 


         begin 
             if(j ==0) 
                 $display(" seed is %d",seed); 
             else 
                 $display(" No seed is given "); 

             for(i = 0;i < 10; i=i+1) 


             begin 
                 if( j == 0) 
                     num = { $random(seed) } % 10; 
                 else 
                     num = { $random() } % 10; 
                 $write("| num=%2d |",num); 
             end 

http://testbench.in/TB_15_SYSTEM_FUNCTION_RANDOM_A_MYTH.html[9/26/2012 2:38:57 PM]


WWW.TESTBENCH.IN - Verilog for Verification

             $display(" "); 


         end 
     end 
endmodule 

RESULT:

seed is 0
| num= 8 || num= 7 || num= 7 || num= 7 || num= 7 || num= 7 || num= 5 || num= 2
|| num= 1 || num= 9 |  
No seed is given  
| num= 8 || num= 7 || num= 7 || num= 7 || num= 7 || num= 7 || num= 5 || num= 2
|| num= 1 || num= 9 |  

The system functions shall always return the same value given the same seed. This
facilitates debugging by making the operation of the system repeatable. The argument
for the seed parameter should be an integer variable that is initialized by the user and
only updated by the system function. This ensures the desired distribution is achieved.

EXAMPLE:
module Tb(); 
    integer num,seed,i,j; 

    initial 
    begin 
        for(j = 0;j<4 ;j=j+1) 
        begin 
            seed = 2; 
            $display(" seed is %d",seed); 
            for(i = 0;i < 10; i=i+1) 
            begin 
                num = { $random(seed) } % 10; 
                $write("| num=%2d |",num); 
            end 
            $display(" "); 
        end 
    end 
endmodule 

RESULT:

seed is 2
| num= 8 || num= 1 || num= 0 || num= 5 || num= 0 || num= 8 || num= 6 || num= 7
|| num= 1 || num= 6 |  
seed is 2
| num= 8 || num= 1 || num= 0 || num= 5 || num= 0 || num= 8 || num= 6 || num= 7
|| num= 1 || num= 6 |  
seed is 2
| num= 8 || num= 1 || num= 0 || num= 5 || num= 0 || num= 8 || num= 6 || num= 7
|| num= 1 || num= 6 |  
seed is 2
| num= 8 || num= 1 || num= 0 || num= 5 || num= 0 || num= 8 || num= 6 || num= 7
|| num= 1 || num= 6 |

Seed is inout port. Random number system function  returns a random number and
also returns a random number to seed inout argument also. The results of the
following example demonstrates how the seed value is getting changed.

EXAMPLE:
module Tb(); 
    integer num,seed,i,j; 
    
    initial 
    begin 
        seed = 0; 
        for(j = 0;j<10 ;j=j+1) 
        begin 
            num = { $random(seed) } % 10; 
            $write("| num=%2d |",num); 
            $display(" seed is %d ",seed); 
        end 

http://testbench.in/TB_15_SYSTEM_FUNCTION_RANDOM_A_MYTH.html[9/26/2012 2:38:57 PM]


WWW.TESTBENCH.IN - Verilog for Verification

    end 
endmodule 

RESULT:

| num= 8 | seed is -1844104698  


| num= 7 | seed is 1082744015  
| num= 7 | seed is 75814084  
| num= 7 | seed is 837833973  
| num= 7 | seed is -2034665166  
| num= 7 | seed is -958425333  
| num= 5 | seed is 851608272  
| num= 2 | seed is 154620049  
| num= 1 | seed is -2131500770  
| num= 9 | seed is -2032678137

From the above results we can make a table of seed values and return values of
$random. If a seed is taken from the table, then rest of the sequence has to follow
sequence in table.  

Table is as falows for initial seed 0;

| num= 8 | seed is -1844104698  


| num= 7 | seed is 1082744015  
| num= 7 | seed is 75814084  
| num= 7 | seed is 837833973  
| num= 7 | seed is -2034665166  
| num= 7 | seed is -958425333  
| num= 5 | seed is 851608272  
| num= 2 | seed is 154620049  
| num= 1 | seed is -2131500770  
| num= 9 | seed is -2032678137
.
.
.
.
.
table goes on........

In the following example, the seed is 837833973, which is the 4 th seed from the
above table.

EXAMPLE:
module Tb(); 
    integer num,seed,i,j; 
    
    initial 
    begin 
        seed = 837833973; 
        for(j = 0;j<10 ;j=j+1) 
        begin 
            num = { $random(seed) } % 10; 
            $write("| num=%2d |",num); 
            $display(" seed is %d ",seed); 
        end 
    end 
endmodule 

RESULTS:

| num= 7 | seed is -2034665166  


| num= 7 | seed is -958425333  
| num= 5 | seed is 851608272  
| num= 2 | seed is 154620049  
| num= 1 | seed is -2131500770  
| num= 9 | seed is -2032678137  
| num= 8 | seed is -1155272804  
| num= 7 | seed is -1634874387  
| num= 9 | seed is -153856566  

http://testbench.in/TB_15_SYSTEM_FUNCTION_RANDOM_A_MYTH.html[9/26/2012 2:38:57 PM]


WWW.TESTBENCH.IN - Verilog for Verification

| num= 2 | seed is -970066749  

From the above example we can come to conclusion that $random is not giving a
random number. It is randomizing seed and returning corresponding number for that
seed.

Total possible seed values are 4294967295. Is it possible for $random to generate all
the seeds? . Lets say ,if the seed gets repeated after 10 iterations, then after the 10
iterations, same values are repeated. So $random is circulating inside a chain of 10
numbers.  

The following example demonstrates how $random misses many seeds. I tried to
display the seeds between 0 to 20 in the chain formed by initial seed of 0. Results
show that total possible seeds are 4294967295 , and number of seeds possible in seed
chain are 4030768279 , so we are missing some seeds. Look at the seeds between 0 to
20. Seed == 1 is missing.

EXAMPLE:
 
module Tb(); 
     integer num,seed,j; 
     reg [0:31] i; 
    
     initial 
     begin 
         i = 0; 
         seed = 1; 
         while (seed != 0) 
         begin 
             if(i == 0) 
                 seed = 0; 
             i = i + 1; 
             num = $random(seed); 
             if(seed < 20 && seed > 0) 
                 $display(" seed is %d after values %d ",seed,i); 
         end 
         $display(" seed is one after this number of random numbers %0d  total numbers
available are %d",i,{32'hffff_ffff}); 
     end 
endmodule 

RESULTS:

seed is 10 after values 93137101  


seed is 17 after values 307298440  
seed is 2 after values 410139893  
seed is 12 after values 483530075  
seed is 19 after values 592243262  
seed is 3 after values 720224974  
seed is 11 after values 1342230278  
seed is 15 after values 2032553666  
seed is 7 after values 2266624778  
seed is 13 after values 2362534380  
seed is 5 after values 2512466932  
seed is 9 after values 2575033104  
seed is 16 after values 2988686279  
seed is 4 after values 3173376451  
seed is 6 after values 3483433473  
seed is 8 after values 3547878575  
seed is 14 after values 3663208793  
seed is 18 after values 3930700709  
seed is zero after this number of random numbers 4030768279  total numbers
available are 4294967295

Now I tried to simulate with seed== 1 . Its interesting to know that some how the
sequence is able to enter this chain which is formed with seed==0 and there is no seed
value 1 in this chain and my simulation hanged. So aborted the simulation and parter
results show that the initial seed = 1 with enter the chain formed by seed 0.

http://testbench.in/TB_15_SYSTEM_FUNCTION_RANDOM_A_MYTH.html[9/26/2012 2:38:57 PM]


WWW.TESTBENCH.IN - Verilog for Verification

EXAMPLE:
module Tb(); 
    integer num,seed,j; 
    reg [0:31] i; 
    
    initial 
    begin 
        i = 0; 
        seed = 0; 
        while (seed != 1) 
        begin 
            if(i == 0) 
                seed = 1; 
            i = i + 1; 
            num = $random(seed); 
            if(seed < 20 && seed > 0) 
                $display(" seed is %d after values %d ",seed,i); 
        end 
        $display(" seed is one after this number of random numbers %0d  total numbers
available are %d",i,{32'hffff_ffff}); 
    end 
endmodule 

RESULTS:

seed is 10 after values 357336117  


seed is 17 after values 571497456  
seed is 2 after values 674338909  
seed is 12 after values 747729091  
seed is 19 after values 856442278  
seed is 3 after values 984423990  
seed is 11 after values 1606429294  
seed is 15 after values 2296752682  
seed is 7 after values 2530823794  
seed is 13 after values 2626733396  
seed is 5 after values 2776665948  
seed is 9 after values 2839232120  
seed is 16 after values 3252885295  
seed is 4 after values 3437575467  
seed is 6 after values 3747632489  
seed is 8 after values 3812077591  
seed is 14 after values 3927407809  
seed is 18 after values 4194899725  
seed is 10 after values 357336117  
seed is 17 after values 571497456  
seed is 2 after values 674338909  
seed is 12 after values 747729091  
seed is 19 after values 856442278  
seed is 3 after values 984423990  

Verilog also has other system functions to generate random numbers. Each of these
functions returns a pseudo-random number whose characteristics are described by the
function name.
Following are the Verilog random number generator system functions:

      $random 
      $dist_chi_square 
      $dist_erlang  
      $dist_exponential  
      $dist_normal 
      $dist_poisson  
      $dist_t 
      $dist_uniform  

All parameters to the system functions are integer values. For the exponential ,
Poisson , chi-square , t , and erlang  functions, the parameters mean, degree of
freedom, and k_stage must be greater than 0 .

$dist_uniform(seed, min, max) is similar to min + {$random(seed)}%(max-min+1),the


difference is that in $dist_uniform,the distribution is uniform. $dist_uniform returns a
number between min and max. In the $dist_uniform function, the start and end
parameters are integer inputs that bound the values returned. The start value should

http://testbench.in/TB_15_SYSTEM_FUNCTION_RANDOM_A_MYTH.html[9/26/2012 2:38:57 PM]


WWW.TESTBENCH.IN - Verilog for Verification

be smaller than the end value.

The mean parameter, used by $dist_normal, $dist_exponential, $dist_poisson, and


$dist_erlang, is an integer input that causes the average value returned by the
function to approach the value specified. The standard deviation parameter used with
the $dist_normal function is an integer input that helps determine the shape of the
density function. Larger numbers for standard deviation spread the returned values
over a wider range.

The degree of freedom parameter used with the $dist_chi_square and $dist_t
functions is an integer input that helps determine the shape of the density function.
Larger numbers spread the returned values over a wider range.

EXAMPLE:
module Tb(); 
    integer num_1,num_2,seed; 
    
    initial 
    begin 
        seed = 10; 
        repeat(5) 
        begin 
            #1; 
            num_1 = $dist_uniform(seed,20,25); 
            num_2 = $dist_uniform(seed,50,55); 
            $display("num_1 = %d,num_2 = %d",num_1,num_2); 
        end 
    end 
endmodule 

RESULTS:

num_1 = 20,num_2 = 50
num_1 = 23,num_2 = 55
num_1 = 22,num_2 = 54
num_1 = 25,num_2 = 51
num_1 = 23,num_2 = 55

As I discussed $random changes its seed , Lets see whether $dist_uniform is also doing
the same.

EXAMPLE:

module Tb(); 
    integer num_1,num_2,seedd,seedr; 
    
    initial 
    begin 
        seedd = 10; 
        seedr = 10; 
        repeat(5) 
        begin 
            #1; 
            num_1 = $dist_uniform(seedd,20,25); 
            num_2 = 20 + ({$random(seedr)} % 6); 
            $display("num_1 = %d,num_2 = %d,seedd = %d seedr =
%d",num_1,num_2,seedd,seedr); 
        end 
    end 
endmodule 
RESULTS:

num_1 = 20,num_2 = 22,seedd = 690691 seedr = 690691


num_1 = 20,num_2 = 20,seedd = 460696424 seedr = 460696424
num_1 = 23,num_2 = 22,seedd = -1571386807 seedr = -1571386807
num_1 = 25,num_2 = 21,seedd = -291802762 seedr = -291802762
num_1 = 22,num_2 = 23,seedd = 1756551551 seedr = 1756551551

Look at the results... Its interesting to note that $random and $dist_uniform have

http://testbench.in/TB_15_SYSTEM_FUNCTION_RANDOM_A_MYTH.html[9/26/2012 2:38:57 PM]


WWW.TESTBENCH.IN - Verilog for Verification

same seed sequence flow also.

As I mentioned ,$dist_uniform(seed, min, max) is similar to min +


{$random(seed)}%(max-min+1). "similar" means they have some common functionality.
$dist_uniform is having uniform distribution, $random for that range, is also uniformly
distributed. Fallowing example ,demonstrates that $dist_uniform and $random are
uniformly distributed.

EXAMPLE:
module Tb(); 
     integer num,seed; 
     integer num_20,num_21,num_22,num_23,num_24,num_25; 
    
     initial 
     begin 
         seed = 10; 
         num_20 = 0;num_21 = 0;num_22 = 0;num_23 = 0;num_24 = 0;num_25 =0; 
        
         repeat(6000) 
         begin 
        
             num = $dist_uniform(seed,20,25); 
             if(num == 20 ) 
                 num_20 = num_20 + 1; 
             if(num == 21) 
                 num_21 = num_21 + 1; 
             if(num == 22) 
                 num_22 = num_22 + 1; 
             if(num == 23) 
                 num_23 = num_23 + 1; 
             if(num == 24) 
                 num_24 = num_24 + 1; 
             if(num == 25) 
                 num_25 = num_25 + 1; 
        
         end 
         $display("num_20 = %0d;num_21 = %0d;num_22 = %0d;num_23 = %0d;num_24 =
%0d;num_25 = %0d",num_20,num_21,num_22,num_23,num_24,num_25); 
     end 
endmodule 

RESULTS:

num_20 = 1014;num_21 = 983;num_22 = 946;num_23 = 1023;num_24 = 1014;num_25 =


1020

EXAMPLE:
module Tb(); 
    integer num; 
    integer num_20,num_21,num_22,num_23,num_24,num_25; 
    
    initial 
    begin 
        seed = 10; 
        num_20 = 0;num_21 = 0;num_22 = 0;num_23 = 0;num_24 = 0;num_25 =0; 
        
        repeat(6000) 
        begin 
        
             num = 20 +( {$random() } %6 ); 
             if(num == 20 ) 
                 num_20 = num_20 + 1; 
             if(num == 21) 
                 num_21 = num_21 + 1; 
             if(num == 22) 
                 num_22 = num_22 + 1; 
             if(num == 23) 
                 num_23 = num_23 + 1; 
             if(num == 24) 
                 num_24 = num_24 + 1; 

http://testbench.in/TB_15_SYSTEM_FUNCTION_RANDOM_A_MYTH.html[9/26/2012 2:38:57 PM]


WWW.TESTBENCH.IN - Verilog for Verification

             if(num == 25) 
                 num_25 = num_25 + 1; 
            
        end 
        $display("num_20 = %0d;num_21 = %0d;num_22 = %0d;num_23 = %0d;num_24 =
%0d;num_25 = %0d",num_20,num_21,num_22,num_23,num_24,num_25); 
    end 
endmodule 
RESULTS:

num_20 = 996;num_21 = 999;num_22 = 959;num_23 = 996;num_24 = 1002;num_25 =


1048

As I mentioned ,$dist_uniform(seed, min, max) is similar to min +


{$random(seed)}%(max-min+1). "similar" means they have some difference. The
difference is that they generate different sequence.  

EXAMPLE:
module Tb(); 
    integer num_1,num_2,seedd,seedr; 
    
    initial 
    begin 
        seedd = 10; 
        seedr = 10; 
        repeat(5) 
        begin 
            #1; 
            num_1 = $dist_uniform(seedd,20,25); 
            num_2 = 20 + ({$random(seedr)} % 6); 
            $display("num_1 = %d,num_2 = %d",num_1,num_2); 
        end 
    end 
endmodule 
RESULTS:

num_1 = 20,num_2 = 22
num_1 = 20,num_2 = 20
num_1 = 23,num_2 = 22
num_1 = 25,num_2 = 21
num_1 = 22,num_2 = 23

Till now what we have seen is $random has uniform distribution over integer values. It
means that distribution should be uniform across all the bits in 32 bit vector also. The
following example shows that bits positions 2,3,4,11,12,13 have equal probability of
getting 0. For demonstration I showed some indexes only. Try out rest of them and
see that results is same for all the bis.

EXAMPLE:
module Tb(); 
    integer num; 
    integer num_2,num_3,num_4,num_11,num_12,num_13; 
    
    initial 
    begin 
        seed = 10; 
        num_2 = 0;num_3 = 0;num_4 = 0;num_11 = 0;num_12 = 0;num_13 =0; 
        
        repeat(6000) 
        begin 
        
            num = $random(); 
            if(num[2] == 0 ) 
                num_2 = num_2 + 1; 
            if(num[3] == 0) 
                num_3 = num_3 + 1; 
            if(num[4] == 0) 
                num_4 = num_4 + 1; 
            if(num[11] == 0) 
                num_11 = num_11 + 1; 

http://testbench.in/TB_15_SYSTEM_FUNCTION_RANDOM_A_MYTH.html[9/26/2012 2:38:57 PM]


WWW.TESTBENCH.IN - Verilog for Verification

            if(num[12] == 0) 
                num_12 = num_12 + 1; 
            if(num[13] == 1) 
                num_13 = num_13 + 1; 
        
        end 
        $display("num_2 = %0d;num_3 = %0d;num_4 = %0d;num_11 = %0d;num_12 =
%0d;num_13 = %0d",num_2,num_3,num_4,num_11,num_12,num_13); 
    end 
endmodule 

RESULTS:

num_2 = 3012;num_3 = 2964;num_4 = 3065;num_11 = 3001;num_12 = 2964;num_13 =


3025

The distribution is uniform for system function $random. Suppose if the requirement
is to generate random numbers for more than one variable, and all the variables
should have uniform distribution, then use different seeds for each variable.
Otherwise distribution is distributed on all the variables as overall. But for lower bits,
the distribution is same as shown in example.

EXAMPLE:
module Tb(); 
    integer seed; 
    reg [1:0] var_1,var_2,var3,var4; 
    integer num_2,num_3,num_1,num_0; 
    integer cou_2,cou_3,cou_1,cou_0; 
    
    initial 
    begin 
        seed = 10; 
        num_2 = 0;num_3= 0;num_1= 0;num_0= 0; 
        cou_2= 0;cou_3= 0;cou_1= 0;cou_0= 0; 
        
        
        repeat(40000) 
        begin 
        
            var_1 = $random(); 
            var3 = $random(); 
            var4 = $random(); 
            var_2 = $random();  
            if(var_1 == 0 ) 
               num_0 = num_0 + 1; 
            if(var_1 == 1 ) 
               num_1 = num_1 + 1; 
            if(var_1 == 2 ) 
               num_2 = num_2 + 1; 
            if(var_1 == 3 ) 
               num_3 = num_3 + 1; 
            
            if(var_2 == 0 ) 
               cou_0 = cou_0 + 1; 
            if(var_2 == 1 ) 
               cou_1 = cou_1 + 1; 
            if(var_2 == 2 ) 
               cou_2 = cou_2 + 1; 
            if(var_2 == 3 ) 
               cou_3 = cou_3 + 1; 
        end 
        $display("num_2 = %0d;num_3= %0d;num_1= %0d;num_0=
%0d;",num_2,num_3,num_1,num_0); 
        $display("cou_2= %0d;cou_3= %0d;cou_1= %0d;cou_0=
%0d;",cou_2,cou_3,cou_1,cou_0); 
     end 
endmodule 

RESULTS:

num_2 = 9984;num_3= 10059;num_1= 10002;num_0= 9955;

http://testbench.in/TB_15_SYSTEM_FUNCTION_RANDOM_A_MYTH.html[9/26/2012 2:38:57 PM]


WWW.TESTBENCH.IN - Verilog for Verification

cou_2= 10060;cou_3= 9934;cou_1= 10072;cou_0= 9934;

Use system time as seed, so the same TB simulated at different times have different
random sequences and there is more probability of finding bugs. The following is c
code useful in PLI to get system time in to verilog.

    #include <stdio.h>
    #include <time.h>
    char *get_time_string(int mode24);
    int get_systime() {
    time_t seconds;
    seconds = time (NULL);
    return seconds;
    }

Verilog 1995, every simulator has its own random number generation algorithm.
Verilog 2001 , The standard made that every simulator has to follow same algorithm.
So the same random number sequence can seen on different simulators for same
seed.

Don't expect that the same sequence is generated on all the simulators. They are only
following same algorithm. The reason is, race condition. Look at the following
example, both the statements num_1 and num_2 are scheduled to execute at same
simulation time. The order of execution is not known. Some simulators take num_1 as
the first statement to execute and some other num_2 .If the TB is built without any
race condition to $random function calls, then the same random sequence can be
generated on different simulators.  

EXAMPLE:
  initial 
  # 10  num_1 = $random; 

  initial 
  #10  num_2 = $random; 

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TB_15_SYSTEM_FUNCTION_RANDOM_A_MYTH.html[9/26/2012 2:38:57 PM]


WWW.TESTBENCH.IN - Verilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS RACE CONDITION Index


Introduction
SystemVerilog Verilog is easy to learn because its gives quick results. Although many users are Linear Tb
Verification telling that their work is free from race condition. But the fact is race condition is File Io Tb
easy to create, to understand, to document but difficult to find. Here we will discuss State Machine Based Tb
Constructs regarding events which creates the race condition & solution for that.  Task Based Tb
Interface Self Checking Testbench
What Is Race Condition? Verification Flow
OOPS Clock Generator
Randomization When two expressions are scheduled to execute at same time, and if the order of the Simulation
execution is not determined, then race condition occurs. Incremental Compilation
Functional Coverage Store And Restore
Assertion EXAMPLE Event Cycle Simulation
module race();  Time Scale And Precision
DPI Stimulus Generation
    wire p;
UVM Tutorial     reg q;  System Function Random
    assign p = q;  A Myth
VMM Tutorial Race Condition
OVM Tutorial     initial begin  Checker
        q = 1;  Task And Function
Easy Labs : SV
        #1 q = 0;  Process Control
Easy Labs : UVM         $display(p);  Disableing The Block
    end  Watchdog
Easy Labs : OVM
endmodule  Compilation N Simulation
Easy Labs : VMM Switchs
AVM Switch TB Debugging
The simulator is correct in displaying either a 1 or a 0. The assignment of 0 to q About Code Coverage
VMM Ethernet sample enables an update event for p. The simulator may either continue or execute the Testing Stratigies
$display system task or execute the update for p, followed by the $display task. File Handling
Then guess what can the value of p ? Verilog Semaphore
Verilog Simulate the above code in your simulator. Then simulate the following code . Finding Testsenarious
Statement "assign p = q;" is changed to end of the module. Handling Testcase Files
Verification
Terimination
Verilog Switch TB Error Injuction
EXAMPLE Register Verification
Basic Constructs
module race();  Parameterised Macros
    wire p; White Gray Black Box
    reg q;  Regression
OpenVera Tips
Constructs    assign p = q; 
Report a Bug or Comment
Switch TB
   initial begin  on This section - Your
RVM Switch TB       q = 1;  input is what keeps
Testbench.in improving
RVM Ethernet sample       #1 q = 0; 
      $display(p);  with time!
   end 
endmodule 
Specman E
Interview Questions
Analyze the effect if I change the order of the assign statement.

Why Race Condition?

To describe the behavior of electronics hardware at varying levels of abstraction,


Verilog HDL has to be a parallel programming language and Verilog simulator and
language itself are standard of IEEE, even though there are some nondeterministic
events which is not mentioned in IEEE LRM and left it to the simulator algorithm,
which causes the race condition. So it is impossible to avoid the race conditions from

http://testbench.in/TB_16_RACE_CONDITION.html[9/26/2012 2:39:08 PM]


WWW.TESTBENCH.IN - Verilog for Verification

the language but we can avoid from coding styles.

Look at following code. Is there any race condition?

EXAMPLE:
initial 
begin 
   in = 1; 
   out <= in; 
end 

Now if you swap these two lines:

EXAMPLE
initial 
begin 
   out <= in; 
   in = 1; 
end 

Think, is there any race condition created?


Here first statement will schedule a non-blocking update for "out" to whatever "in"
was set to previously, and then "in" will be set to 1 by the blocking assignment. Any
statement whether it is blocking or nonblocking statements in a sequential block (i.e.
begin-end block) are guaranteed to execute in the order they appear. So there is no
race condition in the above code also. Since it is easy to make the "ordering mistake",
one of Verilog coding guidelines is: "Do not mix blocking and nonblocking assignments
in the same always block". This creates unnecessary doubt of race condition.

When Race Is Visible?

Sometimes unexpected output gives clue to search for race. Even if race condition is
existing in code, and if the output is correct, then one may not realize that there
exists race condition in their code. This type of hidden race conditions may come out
during the following situation.

When different simulators are used to run the same code.


Some times when the new release of the simulator is used.
Adding more code to previous code might pop out the previously hidden race.
If the order of the files is changed.
When using some tool specific options.
If the order of the concurrent blocks or concurrent statements is changed.(One
example is already discussed in the previous topics)

Some simulators have special options which reports where exactly the race condition
is exists. Linting tools can also catch race condition.

How To Prevent Race Condition?

There are many details which is unspecified between simulators. The problem will be
realized when you are using different simulators. If you are limited to design
guidelines then there is less chance for race condition but if you are using Verilog
with all features for Testbench, then it is impossible to avoid. Moreover the language
which you are using is parallel but the processor is sequential. So you cant prevent
race condition.

Types Of Race Condition

Here we will see race condition closely.

http://testbench.in/TB_16_RACE_CONDITION.html[9/26/2012 2:39:08 PM]


WWW.TESTBENCH.IN - Verilog for Verification

Types of race condition

Write-Write Race:

it occurs when same register is written in both the blocks.

EXAMPLE:
always @(posedge clk) 
    a = 1; 
always @(posedge clk) 
    a = 5; 

Here you are seeing that one block is updating value of a while another also. Now
which always block should go first. This is nondeterministic in IEEE standard and left
that work to the simulator algorithm.

Read-Write Race:

it occurs when same register is read in one block and writes in another.

EXAMPLE:
always @(posedge clk) 
    a = 1; 
always @(posedge clk) 
    b = a; 

Here you are seeing that in one always block value is assign to a while simultaneously
its value is assign to b means a is writing and read parallel. This type of race
condition can easily solved by using nonblocking assignment.

EXAMPLE
always @(posedge clk) 
    a <= 1; 
always @(posedge clk) 
    b <= a; 

More Race Example:

1) Function calls

EXAMPLE:
function incri(); 
begin 
   pkt_num = pkt_num + 1; 
end 
endfunction 

always @(...) 
   sent_pkt_num = incri(); 

always @(...) 
   sent_pkt_num_onemore = incri(); 

2) Fork join

EXAMPLE:
fork 
  a =0; 
  b = a; 
join 

3) $random

EXAMPLE:
always @(...) 
   $display("first Random number is %d",$random()); 
always @(...) 

http://testbench.in/TB_16_RACE_CONDITION.html[9/26/2012 2:39:08 PM]


WWW.TESTBENCH.IN - Verilog for Verification

   $display("second Random number is %d",$random()); 

4) Clock race

EXAMPLE
initial 
    clk = 0; 
always 
    clk = #5 ~clk; 

If your clock generator is always showing "X" then there is a race condition. There is
one more point to be noted in above example. Initial and always starts executes at
time zero.

5) Declaration and initial

EXAMPLE:
reg a = 0; 
initial 
   a = 1; 

6)Testbench DUT race condition.

In test bench , if driving is done at posedge and reading in DUT is done at the same
time , then there is race. To avoid this, write from the Testbench at negedge or
before the posedge of clock. This makes sure that the DUT samples the signal without
any race.

EXAMPLE:
module DUT(); 
    input d; 
    input clock; 
    output q; 
    
    always @(posedge clock) 
    q = d; 

endmodule 

module testbench(); 

     DUT dut_i(d,clk,q); 

     initial 
     begin 
        @(posedge clk) 
        d = 1; 
        @(posedge clock) 
        d = 0; 
     end 
endmodule 

The above example has write read race condition. 

Event Terminology:

Every change in value of a net or variable in the circuit being simulated, as well as
the named event, is considered an update event. Processes are sensitive to update
events. When an update event is executed, all the processes that are sensitive to that
event are evaluated in an arbitrary order. The evaluation of a process is also an
event, known as an evaluation event.

In addition to events, another key aspect of a simulator is time. The term simulation
time is used to refer to the time value maintained by the simulator to model the
actual time it would take for the circuit being simulated. The term time is used
interchangeably with simulation time in this section. Events can occur at different
times. In order to keep track of the events and to make sure they are processed in the
correct order, the events are kept on an event queue, ordered by simulation time.
Putting an event on the queue is called scheduling an event.

http://testbench.in/TB_16_RACE_CONDITION.html[9/26/2012 2:39:08 PM]


WWW.TESTBENCH.IN - Verilog for Verification

The Stratified Event Queue

The Verilog event queue is logically segmented into five different regions. Events are
added to any of the five regions but are only removed from the active region.

1) Events that occur at the current simulation time and can be processed in any order.
These are the
active events.
1.1 evaluation of blocking assignment.
1.2 evaluation of RHS of nonblocking assignment.
1.3 evaluation of continuous assignment.
1.4 evaluation of primitives I/Os
1.5 evaluation of $display or $write

2) Events that occur at the current simulation time, but that shall be processed after
all the active events are processed. These are the inactive events.
#0 delay statement.

3) Events that have been evaluated during some previous simulation time, but that
shall be assigned at this simulation time after all the active and inactive events are
processed. These are the nonblocking assign update events.

4) Events that shall be processed after all the active, inactive, and non blocking
assign update events are processed. These are the monitor events.
$strobe and $monitor

5) Events that occur at some future simulation time. These are the future events.
Future events are divided into future inactive events, and future non blocking
assignment update events.

Example : PLI tasks

The processing of all the active events is called a simulation cycle.

Determinism

This standard guarantees a certain scheduling order.

1) Statements within a begin-end block shall be executed in the order in which they
appear in that begin-end block. Execution of statements in a particular begin-end
block can be suspended in favor of other processes in the model; however, in no case
shall the statements in a begin-end block be executed in any order other than that in
which they appear in the source.

2) Non blocking assignments shall be performed in the order the statements were
executed.

Consider the following example:

initial begin 
    a <= 0; 
    a <= 1; 
end 

When this block is executed, there will be two events added to the non blocking
assign update queue. The previous rule requires that they be entered on the queue in
source order; this rule requires that they be taken from the queue and performed in
source order as well. Hence, at the end of time step 1, the variable a will be assigned
0 and then 1.

Nondeterminism

One source of nondeterminism is the fact that active events can be taken off the
queue and processed in any order. Another source of nondeterminism is that
statements without time-control constructs in behavioral blocks do not have to be
executed as one event. Time control statements are the # expression and @
expression constructs. At any time while evaluating a behavioral statement, the
simulator may suspend execution and place the partially completed event as a
pending active event on the event queue. The effect of this is to allow the
interleaving of process execution. Note that the order of interleaved execution is
nondeterministic and not under control of the user.

http://testbench.in/TB_16_RACE_CONDITION.html[9/26/2012 2:39:08 PM]


WWW.TESTBENCH.IN - Verilog for Verification

Guideline To Avoid Race Condition

(A). Do not mix blocking and nonblocking statements in same block.


(B). Do not read and write using blocking statement on same variable.( avoids read
write race)
(C). Do not initialize at time zero.
(D). Do not assign a variable in more than one block.( avoids write-write race)
(E). Use assign statement for inout types of ports & do not mix blocking and
nonblocking styles of declaration in same block. It is disallow variables assigned in a
blocking assignment of a clocked always block being used outside that block and
disallow cyclical references that don't go through a non-blocking assignment. It is
require all non-blocking assignments to be in a clocked always block.  
(F). Use blocking statements for combinational design and nonblocking for sequential
design. If you want gated outputs from the flops, you put them in continuous
assignments or an always block with no clock.

Avoid Race Between Testbench And Dut

Race condition may occurs between DUT and testbench. Sometimes verification
engineers are not allowed to see the DUT, Sometimes they don't even have DUT to
verify. Consider the following example. Suppose a testbench is required to wait for a
specific response from its DUT. Once it receives the response, at the same simulation
time it needs to send a set of stimuli back to the DUT.

Most Synchronous DUT works on the posedge of clock. If the Testbench is also taking
the same reference, then we may unconditionally end in race condition. So it<92>s
better to choose some other event than exactly posedge of cock. Signals are stable
after the some delay of posedge of clock. Sampling race condition would be proper if
it is done after some delay of posedge of clock. Driving race condition can be avoided
if the signal is driven before the posedge of clock, so at posedge of clock ,the DUT
samples the stable signal.  So engineers prefer to sample and drive on negedge of
clock, this is simple and easy to debug in waveform debugger also.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TB_16_RACE_CONDITION.html[9/26/2012 2:39:08 PM]


WWW.TESTBENCH.IN - Verilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS CHECKER Index


Introduction
SystemVerilog Protocol Checker Linear Tb
Verification File Io Tb
Protocol checking is the mechanism we use to verify IO buses functionality. Protocol State Machine Based Tb
Constructs checkers are created to validate whether or not the DUT is compliant with the bus Task Based Tb
Interface protocol. It does this by checking the clock-by-clock state of the bus interface, Self Checking Testbench
verifying that the DUT drives the bus in accordance to the rules and specifications of Verification Flow
OOPS Clock Generator
the bus protocol. Protocol checker verifies that DUT adheres to the interface protocol
Randomization and also verifies that the assumptions about the temporal behavior of your inputs is Simulation
correct. Incremental Compilation
Functional Coverage Store And Restore
Assertion The  Protocol checker is responsible for extracting signal information from the DUT Event Cycle Simulation
and translating it into meaningful events and status information. This information is Time Scale And Precision
DPI Stimulus Generation
available to other components. It also supplies information needed for functional
UVM Tutorial coverage. The  Protocol checker should never rely on information collected by other System Function Random
components such as the BFM. A Myth
VMM Tutorial Race Condition
OVM Tutorial  Typically, the buses that are checked are external buses and may be industry Checker
standard buses such as PCI, DDR, I2C or proprietary buses . Protocol checking may Task And Function
Easy Labs : SV
occur at a transaction or wire level.  Protocol checker does not considered the data, Process Control
Easy Labs : UVM as data has nothing to do with interface. The data processing protocol checking is Disableing The Block
done in data checker which is generally in scoreboard( or tracker) . Watchdog
Easy Labs : OVM
Compilation N Simulation
Easy Labs : VMM Protocol checks can be divided mainly into 3 categories: Switchs
AVM Switch TB 1) Duration checks Debugging
2) Condition checks About Code Coverage
VMM Ethernet sample 3) Temporal or Sequence Checks. Testing Stratigies
File Handling
Duration checks are the simplest since they involve a single signal. For example, the Verilog Semaphore
Verilog "req signal should be high for at least 3 clocks". Finding Testsenarious
Handling Testcase Files
Verification
Data_checker Terimination
Verilog Switch TB Error Injuction
Data checker verifies the correctness of the device output. Data checking is based on Register Verification
Basic Constructs
comparing the output with the input. The data processing protocol checking is done in Parameterised Macros
data checker which is generally in scoreboard( or tracker) . To do that you must: White Gray Black Box
Regression
OpenVera --Collect the output data from the DUT and parse it. Tips
Constructs --Match the output to its corresponding input.
--Forecast the DUT output by calculating the expected output. Report a Bug or Comment
Switch TB
--Compare the output to the input and to the expected results. on This section - Your
RVM Switch TB input is what keeps
Testbench.in improving
RVM Ethernet sample
Modularization with time!

One of the ways to reduce the amount of work is the ability to leverage components
Specman E from one environment to the next. The concept of modularization is to break up a
Interview Questions complex problem into manageable pieces, which has many benefits including
increasing the quality, maintainability, and reusability of the environment.

In order to reuse components of one environment to another, it is important to


separate functionality into specific entities. This separation allows the work to be
distributed to multiple people. Task separation is very similar to and goes hand in
hand with modularization. Another benefit of task separation is having different
people understanding the functionality.

http://testbench.in/TB_17_CHECKER.html[9/26/2012 2:39:17 PM]


WWW.TESTBENCH.IN - Verilog for Verification

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TB_17_CHECKER.html[9/26/2012 2:39:17 PM]


WWW.TESTBENCH.IN - Verilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS TASK AND FUNCTION Index


Introduction
SystemVerilog Linear Tb
Verification File Io Tb
Tasks and functions can bu used to in much the same manner but there are some State Machine Based Tb
Constructs important differences that must be noted. Task Based Tb
Interface Self Checking Testbench
Verification Flow
OOPS Clock Generator
Functions
Randomization Simulation
A function is unable to enable a task however functions can enable other functions. Incremental Compilation
Functional Coverage Store And Restore
A function will carry out its required duty in zero simulation time.  
Assertion Within a function, no event, delay or timing control statements are permitted. Event Cycle Simulation
In the invocation of a function there must be at least one argument to be passed. Time Scale And Precision
DPI
Functions will only return a single value and cannot use either output or inout Stimulus Generation
UVM Tutorial statements. System Function Random
Functions are synthesysable. A Myth
VMM Tutorial Race Condition
Disable statements cannot be used.
OVM Tutorial Function cannot have nonblocking statements. Checker
Task And Function
Easy Labs : SV
EXAMPLE:function Process Control
Easy Labs : UVM Disableing The Block
module  function_calling(a, b,c);  Watchdog
Easy Labs : OVM
                   Compilation N Simulation
Easy Labs : VMM     input a, b ;  Switchs
AVM Switch TB     output c;  Debugging
    wire c;  About Code Coverage
VMM Ethernet sample          Testing Stratigies
    function  myfunction;  File Handling
    input a, b;  Verilog Semaphore
Verilog     begin  Finding Testsenarious
        myfunction = (a+b);  Handling Testcase Files
Verification
    end  Terimination
Verilog Switch TB     endfunction  Error Injuction
     Register Verification
Basic Constructs
    assign c =  myfunction (a,b);  Parameterised Macros
           White Gray Black Box
endmodule  Regression
OpenVera Tips
Constructs
Report a Bug or Comment
Switch TB
Task on This section - Your
RVM Switch TB input is what keeps
Testbench.in improving
RVM Ethernet sample Tasks are capable of enabling a function as well as enabling other versions of a Task
Tasks also run with a zero simulation however they can if required be executed in a with time!
non zero simulation time.
Tasks are allowed to contain any of these statements.
Specman E A task is allowed to use zero or more arguments which are of type output, input or
Interview Questions inout.
A Task is unable to return a value but has the facility to pass multiple values via the
output and inout statements.
Tasks are not synthesisable.
Disable statements can be used.

EXAMPLE:task
module traffic_lights; 
    reg clock, red, amber, green; 
    parameter on = 1, off = 0, red_tics = 350, 
    amber_tics = 30, green_tics = 200; 

http://testbench.in/TB_18_TASK_AND_FUNCTION.html[9/26/2012 2:39:27 PM]


WWW.TESTBENCH.IN - Verilog for Verification

    initial red = off; 
    initial amber = off; 
    initial green = off; 

    always begin // sequence to control the lights.


        red = on; // turn red light on
        light(red, red_tics); // and wait.
        green = on; // turn green light on
        light(green, green_tics); // and wait.
        amber = on; // turn amber light on
        light(amber, amber_tics); // and wait.
    end 
    // task to wait for tics positive edge clocks
    // before turning color light off.
    task light; 
    output color; 
    input [31:0] tics; 
    begin 
        repeat (tics) @ (posedge clock); 
        color = off; // turn light off.
    end 
    endtask 

    always begin // waveform for the clock.


        #100 clock = 0; 
        #100 clock = 1; 
    end 
endmodule // traffic_lights.

Task And Function Queries:

Why a function cannot call a task?


As functions does not consume time, it can do any operation which does not consume
time. Mostly tasks are written which consumes time. So a task call inside a function
blocks the further execution of function utile it finished. But it<92>s not true. A
function can call task if the task call consumes zero time, but the IEEE LRM doesn't
allow.

Why tasks are not synthesized?


Wrong question! Tasks can be synthesized if it doesn't consume time.

Why a function should return a value?


There is no strong reason for this in Verilog. This restriction is removed in
SystemVerilog.

Why a function should have at least one input?


There is no strong reason for this in verilog. I think this restriction is not removed fin
SystemVerilog. Some requirements where the inputs are taken from the global signal,
those functions don<92>t need any input. A work around is to use a dummy input. If
you have a better reason, just mail me at gopi@testbench.in

Why a task cannot return a value?


If tasks can return values, then Lets take a look at the following example.

A=f1(B)+f2(C);
and f1 and f2 had delays of say 5 and 10? When would B and C be sampled, or global
inside f1 and f2 be sampled? How long does then entire statement block? This is going
to put programmers in a bad situation. So languages gurus made that tasks can't
return .

Why a function cannot have delays?

http://testbench.in/TB_18_TASK_AND_FUNCTION.html[9/26/2012 2:39:27 PM]


WWW.TESTBENCH.IN - Verilog for Verification

The answer is same as above. But in Open Vera, delays are allowed in function. A
function returns a value and therefore can be used as a part of any expression. This
does not allow any delay in the function.  

Why disable statements are not allowed in functions?


If disable statement is used in function, it invalids the function and its return value.
So disable statements are not allowed in function.

Constant Function:

Constant function calls are used to support the building of complex calculations of
values at elaboration time. A constant function call shall be a function invocation of a
constant function local to the calling module where the arguments to the function are
constant expressions.

EXAMPLE:constant function.
module ram_model (address, write, chip_select, data); 
     parameter data_width = 8; 
     parameter ram_depth = 256; 
     localparam adder_width = clogb2(ram_depth); 
     input [adder_width - 1:0] address; 
     input write, chip_select; 
     inout [data_width - 1:0] data; 

     //define the clogb2 function


     function integer clogb2; 
     input depth; 
     integer i,result; 
     begin 
        for (i = 0; 2 ** i < depth; i = i + 1) 
        result = i + 1; 
        clogb2 = result; 
     end 
endfunction 

Reentrant Tasks And Functions:

Tasks and functions without the optional keyword automatic are static , with all
declared items being statically allocated. These items shall be shared across all uses
of the task and functions executing concurrently. Task and functions with the optional
keyword automatic are automatic tasks and functions. All items declared inside
automatic tasks and functions  are allocated dynamically for each invocation.
Automatic task items and function items cannot be accessed by hierarchical
references.

EXAMPLE:

module auto_task(); 
 
task automatic disp; 
   input integer a; 
   input integer d; 
   begin 
       #(d) $display("%t d is %d a is %d", $time,d,a); 
   end 
endtask 
 
initial  
#10 disp(10,14); 
  
initial  
#14 disp(23,18); 

initial  
#4 disp(11,14); 
 

initial 
#100  $finish; 
 
endmodule 

http://testbench.in/TB_18_TASK_AND_FUNCTION.html[9/26/2012 2:39:27 PM]


WWW.TESTBENCH.IN - Verilog for Verification

RESULTS:

18 d is 14 a is 11
24 d is 14 a is 10
32 d is 18 a is 23

EXAMPLE:
module tryfact; 
     // define the function
     function automatic integer factorial; 
         input [31:0] operand; 
         integer i; 
         if (operand >= 2) 
             factorial = factorial (operand - 1) * operand; 
         else 
             factorial = 1; 
     endfunction 
     // test the function
     integer result; 
     integer n; 
     initial begin 
         for (n = 0; n <= 7; n = n+1) begin 
             result = factorial(n); 
             $display("%0d factorial=%0d", n, result); 
         end 
     end 
endmodule // tryfact

RESULTS:

0 factorial=1
1 factorial=1
2 factorial=2
3 factorial=6
4 factorial=24
5 factorial=120
6 factorial=720
7 factorial=5040

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TB_18_TASK_AND_FUNCTION.html[9/26/2012 2:39:27 PM]


WWW.TESTBENCH.IN - Verilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PROCESS CONTROL Index


Introduction
SystemVerilog Nonblocking Task Linear Tb
Verification File Io Tb
If there is a delay in a task and when it is called, it blocks the execution flow. Many State Machine Based Tb
Constructs times in verification it requires to start a process and continue with the rest of the Task Based Tb
Interface flow. The following example demonstrated how the task block the execution flow. Self Checking Testbench
Verification Flow
OOPS Clock Generator
EXAMPLE:
Randomization module tb();  Simulation
     Incremental Compilation
Functional Coverage Store And Restore
    initial 
Assertion     begin  Event Cycle Simulation
        blocking_task();  Time Scale And Precision
DPI Stimulus Generation
        #5 $display(" Statement after blocking_task at %t ",$time); 
UVM Tutorial     end  System Function Random
     A Myth
VMM Tutorial Race Condition
    task blocking_task(); 
OVM Tutorial     begin  Checker
       #10;  Task And Function
Easy Labs : SV
       $display(" statement inside blocking task at %t",$time);  Process Control
Easy Labs : UVM     end  Disableing The Block
    endtask  Watchdog
Easy Labs : OVM
endmodule  Compilation N Simulation
Easy Labs : VMM RESULTS: Switchs
AVM Switch TB Debugging
statement inside blocking task at                   10 About Code Coverage
VMM Ethernet sample Statement after blocking_task at                   15   Testing Stratigies
File Handling
Verilog Semaphore
Verilog Finding Testsenarious
To make the task call does not block the flow, use events as follows. The event Handling Testcase Files
Verification
triggers the always block and the task is started. This does not block the flow. Terimination
Verilog Switch TB Error Injuction
Register Verification
Basic Constructs
EXAMPLE: Parameterised Macros
module tb();  White Gray Black Box
    event e;  Regression
OpenVera     initial  Tips
Constructs     begin 
        #1 ->e;  Report a Bug or Comment
Switch TB
        #5 $display(" Statement after blocking_task at %t ",$time);  on This section - Your
RVM Switch TB         #20 $finish;  input is what keeps
Testbench.in improving
RVM Ethernet sample     end 
     with time!
    always@(e) 
    begin 
Specman E         blocking_task(); 
Interview Questions     end 
    
    task blocking_task(); 
    begin 
        #10; 
        $display(" statement inside blocking task at %t",$time); 
    end 
    endtask 
endmodule 
RESULTS

http://testbench.in/TB_19_PROCESS_CONTROL.html[9/26/2012 2:39:37 PM]


WWW.TESTBENCH.IN - Verilog for Verification

Statement after blocking_task at                   6  


statement inside blocking task at                  11

Fork/Join Recap:

Fork/join is a parallel block. Statements shall execute concurrently. Delay values for
each statement shall be considered relative to the simulation time of entering the
block. Delay control can be used to provide time-ordering for assignments Control
shall pass out of the block when the last time-ordered statement executes. The timing
controls in a fork-join block do not have to be ordered sequentially in time.

EXAMPLE:

module fork_join(); 
   integer r ; 
  
   initial 
   fork 
      #50 r = 35; 
      #100 r = 24; 
      #150 r = 00; 
      #200 r = 7; 
      #250 $finish; 
   join 
  
   initial 
      $monitor("%t , r is %d",$time,r); 
  
endmodule 

RESULTS:

                 50 , r is 35
                100 , r is 24
                150 , r is 0
                200 , r is 7

As the statements are parallel running, there is race condition between some
statements. In the following example, first statement after delay of 50 + 100, r is 24
and in second statement at 150 r is 00. But only the statement which is executed last
overrides previous value.

EXAMPLE:
module fork_join(); 
    integer r ; 
    
    initial 
    fork 
       begin 
           #50 r = 35; 
           #100 r = 24; 
       end 
       #150 r = 00; 
       #200 r = 7; 
       #250 $finish; 
    join 
    
    initial 
       $monitor("%t , r is %d",$time,r); 

http://testbench.in/TB_19_PROCESS_CONTROL.html[9/26/2012 2:39:37 PM]


WWW.TESTBENCH.IN - Verilog for Verification

    
endmodule 

RESULTS:

                 50 , r is 35
                150 , r is 24
                200 , r is 7

Fork/Join None

In the fork join, the parent process continues to execute after all the fork/join
processes are completed. To continue the parent process concurrently with all the
processes spawned by the fork use this trick. This is as simple as above nonblocking
task example. Just use fork/join the always block as shown below.

EXAMPLE:
module tb(); 
    event e; 

    initial 
    begin 
        #1 ->e; 
        #5 $display(" Statement after blocking_task at %t ",$time); 
        #40 $finish; 
    end 
    
    always@(e) 
    begin 
        fork 
            blocking_task_1(); 
            blocking_task_2(); 
        join 
    end 
    
    task blocking_task_1(); 
    begin 
        #10; 
        $display(" statement inside blocking task_1 at %t",$time); 
    end 
    endtask 
    
    task blocking_task_2(); 
    begin 
        #20; 
        $display(" statement inside blocking task_2 at %t",$time); 
    end 
    endtask 
    

endmodule 
RESULTS

Statement after blocking_task at                   6  


statement inside blocking task_1 at                  11
statement inside blocking task_2 at                  21

Fork/Join Any

If you want to continue the parent process after finishing any of the child process,
then block the parent process until an event if triggered by the forked threads.

EXAMPLE:
module tb(); 
    event e,ee; 

    initial 
    begin 
        #1 ->e; 
        @(ee); 

http://testbench.in/TB_19_PROCESS_CONTROL.html[9/26/2012 2:39:37 PM]


WWW.TESTBENCH.IN - Verilog for Verification

        $display(" Statement after blocking_task at %t ",$time); 


        #40 $finish; 
    end 
    
    always@(e) 
    begin 
        fork 
        begin blocking_task_1(); -> ee;end 
        begin blocking_task_2(); -> ee;end 
        join 
    end 
    
    task blocking_task_1(); 
    begin 
        #10; 
        $display(" statement inside blocking task_1 at %t",$time); 
    end 
    endtask 
    
    task blocking_task_2(); 
    begin 
        #20; 
        $display(" statement inside blocking task_2 at %t",$time); 
    end 
    endtask 
endmodule 
RESULTS

statement inside blocking task_1 at                  11


Statement after blocking_task at                   11  
statement inside blocking task_2 at                  21

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TB_19_PROCESS_CONTROL.html[9/26/2012 2:39:37 PM]


WWW.TESTBENCH.IN - Verilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS DISABLEING THE BLOCK Index


Introduction
SystemVerilog Disable Linear Tb
Verification File Io Tb
The disable statement stops the execution of a labeled block and skips to the end of State Machine Based Tb
Constructs the block. Blocks can be named by adding : block_name after the keyword begin or Task Based Tb
Interface fork. Named block can only be disabled using disable statement. Self Checking Testbench
Verification Flow
OOPS Clock Generator
This example illustrates how a block disables itself.
Randomization Simulation
EXAMPLE: Incremental Compilation
Functional Coverage Store And Restore
begin : block_name
Assertion    rega = regb;  Event Cycle Simulation
disable block_name;  Time Scale And Precision
DPI Stimulus Generation
   regc = rega; // this assignment will never execute
UVM Tutorial end  System Function Random
A Myth
VMM Tutorial Race Condition
OVM Tutorial This example shows the disable statement being used as an early return from a task. Checker
However, a task disabling itself using a disable statement is not a short-hand for the Task And Function
Easy Labs : SV
return statement found in programming languages. Process Control
Easy Labs : UVM Disableing The Block
Watchdog
Easy Labs : OVM
EXAMPLE: Compilation N Simulation
Easy Labs : VMM task abc();  Switchs
AVM Switch TB begin : name  Debugging
   :  About Code Coverage
VMM Ethernet sample    :  Testing Stratigies
   :  File Handling
   if( something happened)  Verilog Semaphore
Verilog    disable name;  Finding Testsenarious
   :  Handling Testcase Files
Verification
   :  Terimination
Verilog Switch TB    :  Error Injuction
end  Register Verification
Basic Constructs
endtask  Parameterised Macros
White Gray Black Box
Goto Regression
OpenVera Tips
Constructs Verilog does not have a goto, but the effect of a forward goto can be acheived as
shown: Report a Bug or Comment
Switch TB
on This section - Your
RVM Switch TB EXAMPLE: input is what keeps
Testbench.in improving
RVM Ethernet sample begin: name 
    ...  with time!
    if (a) 
    disable name; 
Specman E     ... 
Interview Questions end 

Execution will continue with the next statement after the end statement when the
disable is executed.  

Break

The break statement as in C can be emulated with disable as shown in the following
example:

EXAMPLE:

http://testbench.in/TB_20_DISABLEING_THE_BLOCK.html[9/26/2012 2:39:47 PM]


WWW.TESTBENCH.IN - Verilog for Verification

begin: break 
    for (i=0; i<16; i=i+1) begin 
        ... 
        if (exit)  
        disable break; 
        ... 
    end 
end  

Continue

The continue statement in C causes the current iteration of a loop to be terminated,


with execution continuing with the next iteration. To do the same thing in Verilog,
you can do this:

EXAMPLE:
for (i=0; i<16; i=i+1) begin: name 
    ... 
    if (abort) 
    disable name; 
    ... 
end 

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TB_20_DISABLEING_THE_BLOCK.html[9/26/2012 2:39:47 PM]


WWW.TESTBENCH.IN - Verilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS WATCHDOG Index


Introduction
SystemVerilog Linear Tb
Verification File Io Tb
State Machine Based Tb
Constructs Task Based Tb
Interface Self Checking Testbench
Verification Flow
OOPS Clock Generator
Randomization Simulation
Incremental Compilation
Functional Coverage Store And Restore
Assertion Event Cycle Simulation
Time Scale And Precision
DPI Stimulus Generation
UVM Tutorial System Function Random
A watchdog timer is a piece of code, that can take appropriate action when it judges
A Myth
VMM Tutorial that a system is no longer executing the correct sequence of code. In this topic ,I will
Race Condition
discuss exactly the sort of scenarios a watch dog can detect, and the decision that
OVM Tutorial Checker
must be made by watchdog. Generally speaking, a watchdog timer is based on a
Task And Function
Easy Labs : SV counter that counts down from some initial value to zero. If the counter reaches,
Process Control
then the appropriate action is take. If the required functionality is archived, watchdog
Easy Labs : UVM Disableing The Block
can be disabled.  
Watchdog
Easy Labs : OVM
Compilation N Simulation
Easy Labs : VMM
In software world, in watchdog articles you will see various terms like strobing,
Switchs
stroking etc. In this topic I will use more visual metaphor of man kicking the dog
AVM Switch TB Debugging
periodically-with apologies to animal lovers. If the man stops kicking the dog, the dog
About Code Coverage
VMM Ethernet sample will take advantage of hesitation and bite the man. The man has to take a proper Testing Stratigies
decision for the dog bite. The process of restarting the watchdog timer's counter is
File Handling
sometimes called "kicking the dog.".Bugs in DUT can cause the testbench to hang, if
Verilog Semaphore
they lead to an infinite loop and creating a deadlock condition. A properly designed
Verilog Finding Testsenarious
watchdog should catch events that hang the testbench.  
Handling Testcase Files
Verification
Terimination
Once your watchdog has bitten ,you have to decide what action to be taken. The
Verilog Switch TB Error Injuction
testbench will usually assert the error message, other actions are also possible like
Register Verification
Basic Constructs directly stop simulation or just give a warning in performance tests.
Parameterised Macros
White Gray Black Box
Regression
OpenVera In the following example, I have taken a DUT model so its easy to understand than a
Tips
RTL to demonstrate watchdog.
Constructs
DUT PROTOCOL: Report a Bug or Comment
Switch TB
DUT has 3 signals.Clock a,b; on This section - Your
RVM Switch TB output b should be 1 within 4 clock cycles after output a became 1. input is what keeps
Testbench.in improving
RVM Ethernet sample
There are two scenarios I generated in DUT. one is following the above protocol and with time!
the other violated the above rule. The testbench watchdog shows how it caught there
two scenarios.
Specman E
Interview Questions
EXAMPLE:
module DUT(clock,a,b); 
    output a; 
    output b; 
    input clock; 
    reg a,b; 
    
    initial 
    begin 
        repeat(10)@(posedge clock) a = 0;b = 0; 

http://testbench.in/TB_21_WATCHDOG.html[9/26/2012 2:39:57 PM]


WWW.TESTBENCH.IN - Verilog for Verification

        @(posedge clock) a = 1;b = 0; 


        @(posedge clock) a = 0;b = 0; 
        @(posedge clock) a = 0;b = 0; 
        @(posedge clock) a = 0;b = 1; 
        repeat(10)@(posedge clock) a = 0;b = 0; 
        @(posedge clock) a = 1;b = 0; 
        @(posedge clock) a = 0;b = 0; 
    end 
endmodule 

module TB(); 
     wire aa,bb; 
     reg clk; 
    
     DUT dut(clk,aa,bb); 
    
     always  
     #5 clk = ~clk; 
    
     initial 
     #400 $finish; 
    
     initial 
     begin 
         clk = 0; 
         $display(" TESTBENCH STARTED"); 
         wait(aa == 1) ; 
         watchdog(); 
         wait( aa == 1); 
         watchdog(); 
     end 
    
     task watchdog(); 
     begin 
         $display(" WATCHDOG : started at %0d ",$time); 
         fork : watch_dog
             begin 
                 wait( bb == 1); 
                 $display(" bb is asserted time:%0d",$time); 
                 $display(" KICKING THE WATCHDOG "); 
                 disable watch_dog; 
             end 
             begin 
                 repeat(4)@(negedge clk); 
                 $display(" bb is not asserted time:%0d",$time); 
                 $display(" WARNING::WATCHDOG BITED "); 
                 disable watch_dog; 
             end 
         join 
     end 
     endtask 

endmodule 

RESULTS:

TESTBENCH STARTED
WATCHDOG : started at 105  
bb is asserted time:135
KICKING THE WATCHDOG  
WATCHDOG : started at 245  
bb is not asserted time:280
WARNING::WATCHDOG BITED

http://testbench.in/TB_21_WATCHDOG.html[9/26/2012 2:39:57 PM]


WWW.TESTBENCH.IN - Verilog for Verification

Statement " disable watch_dog " is the trick hear. If that statement is not there, the
statement " wait(b == 1) " is waiting and the simulation goes hang. This watchdog is
just giving a warning about bite. You can also assert a ERROR message and call $finish
to stop simulation.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TB_21_WATCHDOG.html[9/26/2012 2:39:57 PM]


WWW.TESTBENCH.IN - Verilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS COMPILATION N SIMULATION SWITCHS Index


Introduction
SystemVerilog Compilation And Simulation Directives: Linear Tb
Verification File Io Tb
State Machine Based Tb
Constructs Conditional Compilation directive switches vs Simulation directive switches Task Based Tb
Interface Self Checking Testbench
Verilog has following conditional compiler directives. Verification Flow
OOPS Clock Generator
Randomization `ifdef   Simulation
`else   Incremental Compilation
Functional Coverage Store And Restore
`elsif  
Assertion `endif   Event Cycle Simulation
`ifndef   Time Scale And Precision
DPI Stimulus Generation
UVM Tutorial The `ifdef compiler directive checks for the definition of a text_macro_name. If the System Function Random
text_macro_name is defined, then the lines following the `ifdef directive are A Myth
VMM Tutorial Race Condition
included. If the text_macro_name is not defined and an `else directive exists, then
OVM Tutorial this source is Checker
compiled. The `ifndef compiler directive checks for the definition of a Task And Function
Easy Labs : SV
text_macro_name. If the text_macro_name is not defined, then the lines following Process Control
Easy Labs : UVM the `ifndef directive are included. If the text_macro_name is defined and an `else Disableing The Block
directive exists, then this source is compiled. If the `elsif directive exists (instead of Watchdog
Easy Labs : OVM
the `else) the compiler checks for the definition of the text_macro_name. If the name Compilation N
Easy Labs : VMM exists the lines following the `elsif directive are included. The `elsif directive is Simulation Switchs
AVM Switch TB equivalent to the compiler directive sequence `else `ifdef ... `endif. This directive Debugging
does not need a corresponding `endif directive. This directive must be preceded by an About Code Coverage
VMM Ethernet sample `ifdef or `ifndef directive. Testing Stratigies
File Handling
Verilog Semaphore
Verilog EXAMPLE: Finding Testsenarious
module switches();  Handling Testcase Files
Verification
Terimination
Verilog Switch TB initial  Error Injuction
begin  Register Verification
Basic Constructs
`ifdef TYPE_1  Parameterised Macros
$display(" TYPE_1 message ");  White Gray Black Box
`else  Regression
OpenVera   `ifdef TYPE_2  Tips
Constructs   $display(" TYPE_2 message "); 
   `endif  Report a Bug or Comment
Switch TB
`endif  on This section - Your
RVM Switch TB end  input is what keeps
Testbench.in improving
RVM Ethernet sample endmodule 
with time!

Compile with    +define+TYPE_1  
Specman E Then simulate,result is
Interview Questions
RESULT:

TYPE_1 message  

Compile with    +define+TYPE_2
Then simulate,result is

RESULT:

http://testbench.in/TB_22_COMPILATION_N_SIMULATION_SWITCHS.html[9/26/2012 2:40:04 PM]


WWW.TESTBENCH.IN - Verilog for Verification

TYPE_2 message

TYPE_1 and TYPE_2 are called switches.

In the above example, When TYPE_1 switch is given, statement " $display(" TYPE_1
message "); " is only compile and statement " $display(" TYPE_2 message "); " is not
compiled.
Similarly for TYPE_2 switch. It wont take much time to compile this small example.
Compilation time is not small for real time verification environment. Compiler takes
time for each change of conditional compilation switches.  

Simulation directives are simple. This is archived by `define macros. The following
example demonstrated the same functionality as the above example.

EXAMPLE:

module switches(); 

initial 
begin 
if($test$plusargs("TYPE_1")) 
$display(" TYPE_1 message "); 
else 
  if($test$plusargs("TYPE_2")) 
   $display(" TYPE_2 message "); 
end 
endmodule 

No need to give +define+TYPE_1  or   +define+TYPE_2 during compilation

Simulate with +TYPE_1

RESULT:

TYPE_1 message  

Simulate with   +TYPE_2


Then simulate,result is

RESULT:

TYPE_2 message

With the above style of programing,we can save recompilation times.

This system function searches the list of plusargs (like the $test$plusargs system
function) for a user specified plusarg string. The string is specified in the first
argument to the system function as either a string or a register which is interpreted
as a string. If the string is found, the remainder of the string is converted to the type
specified in the user_string and the resulting value stored in the variable provided. If
a string is found, the function returns a non-zero integer. If no string is found
matching, the function returns the integer value zero and the variable provided is not
modified.

%d decimal conversion
%o octal conversion

http://testbench.in/TB_22_COMPILATION_N_SIMULATION_SWITCHS.html[9/26/2012 2:40:04 PM]


WWW.TESTBENCH.IN - Verilog for Verification

%h hexadecimal conversion
%b binary conversion
%e real exponential conversion
%f real decimal conversion
%g real decimal or exponential conversion
%s string (no conversion)

The first string, from the list of plusargs provided to the simuator, which matches the
plusarg_string portion of the user_string specified shall be the plusarg string available
for conversion. The remainder string of the matching plusarg (the remainder is the
part of the plusarg string after the portion which matches the users plusarg_string)
shall be converted from a string into the format indicated by the format string and
stored in the variable provided. If there is no remaining string, the value stored into
the variable shall either be a zero (0) or an empty string value.

Example

module valuetest();
  
   integer i;
   real r;
   reg [11:0] v;
   reg [128:0] s;
  
   initial
   begin
       if($value$plusargs("STRING=%s",s))
           $display(" GOT STRING ");
       if($value$plusargs("INTG=%d",i))
           $display(" GOT INTEGER ");
       if($value$plusargs("REAL=%f",r))
           $display(" GOT REAL ");
       if($value$plusargs("VECTOR=%b",v))
           $display(" GOT VECTOR ");
      
       $display( " String is %s ",s);
       $display(" Integer is %d ",i);
       $display(" Realnum is %f ",r);
       $display(" Vector  is %b ",v);
   end
  
endmodule

Compilation : 
command filename.v
Simulation :
command  +STRING=rrf +INTG=123 +REAL=1.32 +VECTOR=10101

RESULTS:

 GOT STRING
 GOT INTEGER
 GOT REAL
 GOT VECTOR
 String is               rrf
 Integer is 123
 Realnum is 1.320000e+00
 Vector  is 000000010101

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/TB_22_COMPILATION_N_SIMULATION_SWITCHS.html[9/26/2012 2:40:04 PM]


WWW.TESTBENCH.IN - Verilog for Verification

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TB_22_COMPILATION_N_SIMULATION_SWITCHS.html[9/26/2012 2:40:04 PM]


WWW.TESTBENCH.IN - Verilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS DEBUGGING Index


Introduction
SystemVerilog Linear Tb
Verification Debugging is a methodical process of finding and reducing the number of bugs. When File Io Tb
a the outputs are of the DUT are not what expected, then a bug may be in DUT or State Machine Based Tb
Constructs sometimes it may be in testbench. Debuggers are software tools which enable the Task Based Tb
Interface verification and design engineers to monitor the execution of a program, stop it, re- Self Checking Testbench
start it, run it in interactive mode. Verification Flow
OOPS Clock Generator
Randomization The basic steps in debugging are: Simulation
Incremental Compilation
Functional Coverage Store And Restore
--- Recognize that a bug exists
Assertion --- Isolate the source of the bug Event Cycle Simulation
--- Identify the cause of the bug Time Scale And Precision
DPI Stimulus Generation
--- Determine a fix for the bug
UVM Tutorial --- Apply the fix and test it System Function Random
A Myth
VMM Tutorial Race Condition
OVM Tutorial Checker
Pass Or Fail Task And Function
Easy Labs : SV
Process Control
Easy Labs : UVM At the end of simulation of every test, TEST FAILED or TEST PASSED report should be Disableing The Block
generated. This is called self checking. Log files and Waveform viewer can help for Watchdog
Easy Labs : OVM
further debugging if test failed.   Compilation N Simulation
Easy Labs : VMM Switchs
AVM Switch TB An error count should be maintained to keep track of number of errors occurred. Debugging
Simplest way to increment an error counter is using named event.   About Code Coverage
VMM Ethernet sample Testing Stratigies
File Handling
EXAMPLE: Verilog Semaphore
Verilog module top();  Finding Testsenarious
    integer error;  Handling Testcase Files
Verification
    event err;  Terimination
Verilog Switch TB     //ur testbench logic Error Injuction
    initial   Register Verification
Basic Constructs
    begin  Parameterised Macros
        #10;  White Gray Black Box
        if("There is error ")  Regression
OpenVera            -> error;  Tips
Constructs         #10 
        if("There is error ")  Report a Bug or Comment
Switch TB
           -> error;  on This section - Your
RVM Switch TB         #10  input is what keeps
Testbench.in improving
RVM Ethernet sample         if("There is error ") 
           -> error;  with time!
        // call final block to finish simulation
        
Specman E     end 
Interview Questions     
    //Initilize error to 0
    initial 
        error = 0; 
    // count number of errors
    always@(err) 
        error = error +1 ; 
    
    // final block--to end simulation
    task finish(); 
    begin 

http://testbench.in/TB_23_DEBUGGING.html[9/26/2012 2:40:13 PM]


WWW.TESTBENCH.IN - Verilog for Verification

        #10; // so delay to make sure that counter increments for the last triggered
error.
        if( error == 0) 
            $dsplay("************ TEST PASSED ***************"); 
        else 
            $dsplay("************ TEST FAILED ***************"); 
        
    end 
    endtask 
    
endmodule 

Waveform Viewer:

For post process debug, Waveform viewer needs VCD(value change dump) file. A value
change dump (VCD) file contains information about value changes on selected
variables in the design stored by value change dump system tasks. Two types of VCD
files exist:

a) Four state: to represent variable changes in 0, 1, x, and z with no strength


information.
b) Extended: to represent variable changes in all states and strength information.

This clause describes how to generate both types of VCD files and their format.

The steps involved in creating the four state VCD file are listed below .
a) Insert the VCD system tasks in the Verilog source file to define the dump file name
and to specify the variables to be dumped.
b) Run the simulation.

A VCD file is an ASCII file which contains header information, variable definitions, and
the value changes for all variables specified in the task calls. Several system tasks can
be inserted in the source description to create and control the VCD file.

The $dumpfile task shall be used to specify the name of the VCD file.

EXAMPLE:

initial  
$dumpfile ("my_dump_file"); 

$dumpvar //Dump all the variables


// Alternately instead of $dumpvar, one could use
$dumpvar(1, top) //Dump variables in the top module.
$dumpvar(2, top) //Dumps all the variables in module top and 1 level below.

Executing the $dumpvars  task causes the value change dumping to start at the end of
the current simulation time unit. To suspend the dump, the $dumpoff  task may be
invoked. To resume the dump, the $dumpon  task may be invoked.  

Due to dumping the value changes to a file,there is simulation over head. Not all the
time the dumping is required. So controlling mechanism to dump VCD files needs to
be implemented.

EXAMPLE:
`ifdef DUMP_ON 
  $dumpon; 
`endif 

http://testbench.in/TB_23_DEBUGGING.html[9/26/2012 2:40:13 PM]


WWW.TESTBENCH.IN - Verilog for Verification

Log File:

Log file keeps track of the operation in text format. Using Display system tasks,
proper information can be sent to log files. The display group of system tasks are
divided into three categories: the display and write tasks, strobed monitoring tasks,
and continuous monitoring tasks.

These are the main system task routines for displaying information. The two sets of
tasks are identical except that $display automatically adds a newline character to the
end of its output, whereas the $write task does not.

The system task $strobe provides the ability to display simulation data at a selected
time. That time is the
end of the current simulation time, when all the simulation events that have occurred
for that simulation
time, just before simulation time is advanced.

$monitor displays when any of the arguments values change.

Message Control System:

Sending message to log file is useful for debugging. But what messages are useful to
send and not. Sometimes only few messages are required to send to log file, other
times very detailed messages. If the number of messages are more, the simulation
time is more. So messaging should be controllable.

EXAMPLE:
always@(error) 
begin 
`ifdef DEBUG 
$display(" ERROR : at %d ",$time); 
`endif 
end 

With the above approach only one level of controlling is achieved. Messages can be
conveyed with wide range of severity levels. Following is the message controlling
system I used in my projects. This has 3 levels of controllability and 3 severity levels.

Message Severity Levels:

Following are the 4 severity levels of messaging:

INFO: 
The messages is used to convey simple information. 
WARNING: 
This message conveys that some this is bad but doesn't stop the simulation. 
ERROR: 
This messages indicate that some error has occurred. Simulation can be terminated. 
DEBUG: 
These messages are for debugging purpose. 
NOTE: %m prints hierarchy path. 
EXAMPLE:

$display(" INFO : %t : UR MESSAGE GOES HEAR",$time); 


$display(" WARN : %t : UR MESSAGE GOES HEAR",$time); 
$display(" EROR : %t : UR MESSAGE GOES HEAR",$time); 
$display(" DBUG : %t : UR MESSAGE GOES HEAR",$time); 

Message Controlling Levels

By default ,messages INFO, WARN and EROR are logged. When a special switch is
used, Debug messages are logged. This example also removes lot of manly coding.

EXAMPLE:
`ifndef DEBUG 
`define SHOW 0 
`else 
 `define SHOW 1 
`endif 

`define INFO $write("INFO : %5t :%m:",$time); $display 

http://testbench.in/TB_23_DEBUGGING.html[9/26/2012 2:40:13 PM]


WWW.TESTBENCH.IN - Verilog for Verification

`define WARN $write("WARN : %5t :%m:",$time); $display 


`define EROR $write("EROR : %5t :%m:",$time); $display 
`define DBUG if(`SHOW == 1) $write("DBUG : %t
:%m:",$time); if(`SHOW == 1) $display 

module msg(); 

initial 
begin 
#10; 
`INFO("UR MESSAGE GOES HEAR"); 
`WARN("UR MESSAGE GOES HEAR"); 
`EROR("UR MESSAGE GOES HEAR"); 
`DBUG("UR MESSAGE GOES HEAR"); 
end 
endmodule 

When compilation is done without +define+DEBUG 


RESULTS:

INFO :    10 :msg:UR MESSAGE GOES HEAR


WARN :    10 :msg:UR MESSAGE GOES HEAR
EROR :    10 :msg:UR MESSAGE GOES HEAR

When compilation is done with +define+DEBUG 


RESULTS:

INFO :    10 :msg:UR MESSAGE GOES HEAR


WARN :    10 :msg:UR MESSAGE GOES HEAR
EROR :    10 :msg:UR MESSAGE GOES HEAR
DBUG :    10 :msg:UR MESSAGE GOES HEAR

The above results show that DEBUG messages can be disable if not needed.

With the above approach, the controllability is at compilation level. If the


controllability is at simulation level, compilation time can be saved. The following
message controlling system has controllability at simulation level.

EXAMPLE:

`define INFO $write("INFO : %0t :%m:",$time); $display 


`define WARN $write("WARN : %0t :%m:",$time); $display 
`define EROR $write("EROR : %0t :%m:",$time); $display 
`define DBUG if(top.debug == 1) $write("DBUG : %0t :%m:",$time); if(top.debug
== 1) $display 

module top(); 
    reg debug = 0; 
    
    initial 
        if($test$plusargs("DEBUG")) 
            #0 debug = 1; 
    
    initial 
    begin 
        #10; 
        `INFO("UR MESSAGE GOES HEAR"); 
        `WARN("UR MESSAGE GOES HEAR"); 
        `EROR("UR MESSAGE GOES HEAR"); 
        `DBUG("UR MESSAGE GOES HEAR"); 
    end 
endmodule 
When simulation is done without +DEBUG 
RESULTS:

INFO :    10 :top:UR MESSAGE GOES HEAR


WARN :    10 :top:UR MESSAGE GOES HEAR
EROR :    10 :top:UR MESSAGE GOES HEAR

http://testbench.in/TB_23_DEBUGGING.html[9/26/2012 2:40:13 PM]


WWW.TESTBENCH.IN - Verilog for Verification

When simulation is done with +DEBUG 


RESULTS:

INFO :    10 :top:UR MESSAGE GOES HEAR


WARN :    10 :top:UR MESSAGE GOES HEAR
EROR :    10 :top:UR MESSAGE GOES HEAR
DBUG :    10 :top:UR MESSAGE GOES HEAR

Passing Comments To Waveform Debugger

This is simple trick and very useful. By passing some comments to waveform,
debugging becomes easy. Just declare a string and keep updating the comments.
There is no slandered way to pass comments to waveform debugger but some tools
have their own methods to do this job.

EXAMPLE:
module pass_comments(); 
    reg [79 : 0] Comment; // holds 10 characters.
    
    reg [7:0] status; 
    
    initial 
    begin 
        #10 status = 8'b10101010; 
        comment = Preambel; 
        #10 status = 8'b10101011; 
        comment = Startofpkt; 
    end 
endmodule 

The reg " Comment " holds string. This strings can be viewed in waveform debugger.

$Display N $Strobe

According to scheduling semantics of verilog, $display executes before the


nonblocking statements update LHS. Therefore if $display contains LHS variable of
nonblocking assignment, the results are not proper. The $strobe command shows
updated values at the end of the time step after all other commands, including
nonblocking assignments, have completed.

EXAMPLE:
module disp_stro; 
    reg a; 
    
    initial begin 
        a = 0; 
        a <= 1; 
        $display(" $display a=%b", a); 
        $strobe (" $strobe a=%b", a); 
        #1 $display("#1 $display a=%b", a); 
        #1 $finish; 
    end 
endmodule 
RESULTS:

$display a=0
$strobe a=1
#1 $display a=1

Who Should Do The Rtl Debugging?

One of the important question in debugging is who should do the RTL debugging?
Verification engineer or the RTL designer?
I personally like to debug the RTL as verification engineer. This is a great opportunity
to know RTL methodology. This also improves my understanding ability of RTL.
Sometimes test fails because of the Verification environment, before I go and ask RTL
designer, I am sure that there is no bug in my environment. By debugging RTL, the bug
report is more isolated and designer can fix it sooner. Designer is fast enough to catch

http://testbench.in/TB_23_DEBUGGING.html[9/26/2012 2:40:13 PM]


WWW.TESTBENCH.IN - Verilog for Verification

cause of the bug, as he knows more about the RTL then verification engineer.
Verification and Designer should sit together and debug the issue, if the bug is in RTL,
verification engineer can file the bug, if it is in Testbench, no need to file it.
 

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TB_23_DEBUGGING.html[9/26/2012 2:40:13 PM]


WWW.TESTBENCH.IN - Verilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS ABOUT CODE COVERAGE Index


Introduction
SystemVerilog Linear Tb
Verification To check whether the Testbench has satisfactory exercised the design or not? File Io Tb
Coverage is used. It will measure the efficiency of your verification implementation. State Machine Based Tb
Constructs Code coverage answers the questions like   Task Based Tb
Interface Have all the lines of the DUT has been exercised? Self Checking Testbench
Have all the states in the FSM has been entered? Verification Flow
OOPS Clock Generator
Have all the paths within a block have been exercised?
Randomization Have all the branches in Case have been entered? Simulation
Have all the conditions in an if statement is simulated? Incremental Compilation
Functional Coverage Store And Restore
Assertion With the above information, verification engineer can plan for more test cases and Event Cycle Simulation
excursive uncovered areas to find bugs.   Time Scale And Precision
DPI Stimulus Generation
UVM Tutorial By default, every tool disables the code coverage. If user enables then only code System Function Random
coverage is done. By enabling the code coverage there is overhead on the simulation A Myth
VMM Tutorial Race Condition
and the simulation takes more time. So it is recommended not to enable the code
OVM Tutorial coverage always. Enabling the code coverage during the regression saves user time a Checker
lot. Task And Function
Easy Labs : SV
Process Control
Easy Labs : UVM Disableing The Block
Types Of Coverage Watchdog
Easy Labs : OVM
Compilation N Simulation
Easy Labs : VMM Implementation of Testbench can be separated by following types of coverage Switchs
AVM Switch TB hierarchy. Debugging
About Code Coverage
VMM Ethernet sample Testing Stratigies
Code Coverage: File Handling
Verilog Semaphore
Verilog It specifies that how much deep level the design is checked. There are sub parts of Finding Testsenarious
the code coverage that will be discussed bellow. Handling Testcase Files
Verification
Terimination
Verilog Switch TB Error Injuction
Statement Coverage /Line Coverage: Register Verification
Basic Constructs
Parameterised Macros
This is the easiest understandable type of coverage. This is required to be 100% for White Gray Black Box
every project.  From N lines of code and according to the applied stimulus how many Regression
OpenVera statements (lines) are covered in the simulation is measured by statement coverage. Tips
Constructs Lines like module, endmodule, comments, timescale etc are not covered.  
Report a Bug or Comment
Switch TB
always @(posedge clk)   on This section - Your
RVM Switch TB begin  input is what keeps
Testbench.in improving
RVM Ethernet sample     if (a > b) statement 1 
    begin  with time!
       y = a and b; statement 2 
       z = a or b; statement 3 
Specman E     end 
Interview Questions     if (a < b) 
    begin 
       y = a xor b; 
       z = a xnor b; 
    end 
    if (a == b) 
    begin 
        y = not b; 
        z = a % b; 
    end 
end 

http://testbench.in/TB_24_ABOUT_CODE_COVERAGE.html[9/26/2012 2:40:22 PM]


WWW.TESTBENCH.IN - Verilog for Verification

As seen in example those statements only will execute whose condition is satisfied.
Statement coverage will only consider those statements.

Block/Segment Coverage:

The nature of the statement and block coverage looks somewhat same. The
difference is that block which is covered by begin-end, if-else or always, those group
of statements which is called block counted by the block coverage.

Branch / Decision / Conditional Coverage:

Branch coverage will report the true or false of the branch like if-else, case and the
ternary operator (? :) statements. In bellow branch of casez, sequences of statements
are given. Their execution is depending upon the implementation of stimulus. The
default branch in case statement in RTL is not exercised mostly because the Design
guidelines insist to mention all the branches of the case statement.

case (state) 
idle : casez (bus_req) 
4'b0000 : next = idle; 
4'b1??? : next = grant1; 
4'b01?? : next = grant2; 
4'b001? : next = grant3; 
4'b0001 : next = grant4; 

http://testbench.in/TB_24_ABOUT_CODE_COVERAGE.html[9/26/2012 2:40:22 PM]


WWW.TESTBENCH.IN - Verilog for Verification

default : next = idle; 
endcase 

As per the case selectivity list it will check all the statements are reached or not?

Path Coverage:

Due to conditional statements like if-else, case in the design different path is created
which diverts the flow of stimulus to the specific path.

Path coverage is considered to be more complete than branch coverage because it


can detect the errors related to the sequence of operations. As mentioned in the
above figure path will be decided according to the if-else statement According to the
applied stimulus the condition which is satisfied only under those expressions will
execute, the path will be diverted according to that. Path coverage is possible in
always and function blocks only in RTL. Path created by more than one block is not
covered.  Analysis of path coverage report is not so easy task.

Expression Coverage:

It is the ratio of no. of cases checked to the total no. of cases present. Suppose one
expression having Boolean expression like AND or OR, so entries which is given to that
expression to the total possibilities is called expression coverage.

y = (a xor b) + (c xor d); 

http://testbench.in/TB_24_ABOUT_CODE_COVERAGE.html[9/26/2012 2:40:22 PM]


WWW.TESTBENCH.IN - Verilog for Verification

In above example it analyzes the right and side of the expression and counts how
many times it executed. The expression which involves the Boolean expression for
that expression coverage will make its truth table with number of times it executed.
If any expression is uncovered then table will come with plane line.

Toggle Coverage:

It makes assures that how many time reg, net and bus toggled? Toggle coverage could
be as simple as the ratio of nodes toggled to the total number of nodes.

X or Z --> 1 or H
X or Z --> 0 or L
1 or H --> X or Z
0 or L --> X or Z

Above example shows the signal changes from one level to another. Toggle coverage
will show which signal did not change the state. Toggle coverage will not consider
zero-delay glitches.  All types of transitions mentioned above are not interested. Only
1->0 and 0->1 are much important. This is very useful in gate level simulation.

Variable Coverage:

After the one step of toggle coverage variable coverage comes. Both the coverage
looks same but there is a minor different between them is toggle coverage works on
gate level but it fail on large quantity. For entity like bus we use variable coverage.

Triggering / Event Coverage:

Events are typically associated with the change of a signal. Event coverage checks the
process whenever the individual signal inside the sensitivity list changes.

EXAMPLE:
always @(a or b or c) 
if ((a & b) | c) 
x = 1'b 1; 
else 
x = 1'b 0; 

As per the change in above sensitivity list whether the process is triggered or not.

Parameter Coverage:

It works on the specification which is defined in the design process. If you have
implemented 30bit design instead of 32bit, here code coverage check for the
functionality while if your design is parameterized then parameter coverage will give
error which shows size mismatch.

Functional Coverage:

It works on the functional part of the stimuli's implementation. Functional coverage


will check the overall functionality of the implementation. Verilog does not support

http://testbench.in/TB_24_ABOUT_CODE_COVERAGE.html[9/26/2012 2:40:22 PM]


WWW.TESTBENCH.IN - Verilog for Verification

functional coverage. To do functional coverage, Hardware verification languages like


SystemVerilog, Specman E or Vera are needed.

Fsm Coverage :

It is the most complex type of coverage, because it works on the behavior of the
design. In this coverage we look for how many times states are visited, transited and
how many sequence are covered. Thats the duty of FSM coverage.  

State Coverage:

It gives the coverage of no. of states visited over the total no. of states. Suppose you
have N number of states and state machines transecting is in between only N-2 states
then coverage will give alert that some states are uncovered. It is advised that all the
states must be covered.

Transition Coverage:

It will count the no. of transition  from one state to another and it will compare it
with other total no. of transition. Total no. of transition is nothing but all possible no.
of transition which is present in the finite state machine. Possible transition = no. of
states * no. of inputs.

Sequence Coverage:

suppose your finite state machine detects the particular sequences. So there is more
than 1 possibilities of sequences through which your desired output can be achieved.
So here sequence coverage will check which sequence is covered and which is missed?
This is a small and corner problem but stimulus should be such a way that all the
possibilities must be covered.

Tool Support:

Coverage tool should have following features:


Capability to merge reports generated by different test cases.
Capability to disable specified block,statement,module,signal.
A GUI report for easy analysis.
Capability to enable or disable any type of coverage.
User options for default branch in case statement coverage.

Limitation Of Code Coverage:

Coverage does not know anything about what design supposed to do. There is no way
to find what is missing in the code. It can only tell quality of the implementation.
Sometime we get the bug because of the incorrectly written RTL code. If we found
that all the lines of the code are used, it doesn't mean that we have tasted all the
lines. Sometimes we want the 2nd input of the mux but due to mistake in stimulus if
it has taken 1st during that cycle. So whether we got he correct data or not? This
cannot tell by coverage. Thats depend on us weather we are feeding correct stimulus
or not?

http://testbench.in/TB_24_ABOUT_CODE_COVERAGE.html[9/26/2012 2:40:22 PM]


WWW.TESTBENCH.IN - Verilog for Verification

        so remember "VERIFICATION IS NOT COMPLETED EVEN AFTER 100% CODE


COVERAGE"  

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TB_24_ABOUT_CODE_COVERAGE.html[9/26/2012 2:40:22 PM]


WWW.TESTBENCH.IN - Verilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS TESTING STRATIGIES Index


Introduction
SystemVerilog Linear Tb
Verification Function verification approaches can be divided into two categories. Bottom-up and File Io Tb
flat approaches. State Machine Based Tb
Constructs Task Based Tb
Interface Self Checking Testbench
Bottom-Up Verification Flow
OOPS Clock Generator
Randomization Bottom-up approach can be done at 4 levels. Simulation
1)Unit (Module-level) Level Incremental Compilation
Functional Coverage Store And Restore
2)Sub-ASIC (Functional Blocks) Level
Assertion 3)ASIC Level Event Cycle Simulation
4)System Level Time Scale And Precision
DPI Stimulus Generation
UVM Tutorial System Function Random
Unit Level A Myth
VMM Tutorial Race Condition
OVM Tutorial In unit level verification, a module is verified in its own test environment to prove Checker
that the logic, control, and data paths are functionally correct. The goal of module Task And Function
Easy Labs : SV
level verification is to ensure that the component/unit  being tested conforms to its Process Control
Easy Labs : UVM specifications and is ready to be integrated with other subcomponents of the product. Disableing The Block
In unit level verification good coverage percentage is expected. Watchdog
Easy Labs : OVM
Compilation N Simulation
Easy Labs : VMM Switchs
AVM Switch TB Sub-Asic Level Debugging
About Code Coverage
VMM Ethernet sample In sub-asic level ,the goal is to ensure that the interfaces among the units  are Testing Stratigies
correct & the units work together to execute the functionality correctly. Sometimes File Handling
this level can be skipped. Verilog Semaphore
Verilog Finding Testsenarious
Asic Level Handling Testcase Files
Verification
Terimination
Verilog Switch TB Asic level verification is the process of verifying the ASIC to see that it meets its Error Injuction
specified requirements. ASIC level verification must concentrate on ensuring the use Register Verification
Basic Constructs
and interaction of ASIC rather than on checking the details of its implementations .   Parameterised Macros
White Gray Black Box
System Level Regression
OpenVera Tips
Constructs
Report a Bug or Comment
Switch TB
Flat on This section - Your
RVM Switch TB input is what keeps
Testbench.in improving
RVM Ethernet sample In this ,verification approaches by combining interface models and transaction
streams to test the Complete ASIC. with time!

Specman E
Interview Questions

http://testbench.in/TB_25_TESTING_STRATIGIES.html[9/26/2012 2:40:32 PM]


WWW.TESTBENCH.IN - Verilog for Verification

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TB_25_TESTING_STRATIGIES.html[9/26/2012 2:40:32 PM]


WWW.TESTBENCH.IN - Verilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS FILE HANDLING Index


Introduction
SystemVerilog Linear Tb
Verification The system tasks and functions for file-based operations are divided into three File Io Tb
categories: State Machine Based Tb
Constructs Task Based Tb
Interface Functions and tasks that open and close files Self Checking Testbench
Verification Flow
OOPS Tasks that output values into files Clock Generator
Tasks that output values into variables Simulation
Randomization
Tasks and functions that read values from files and load into variables or memories Incremental Compilation
Functional Coverage Store And Restore
Assertion Event Cycle Simulation
Fopen And Fclose Time Scale And Precision
DPI Stimulus Generation
UVM Tutorial System Function Random
$fopen and $fclose A Myth
VMM Tutorial Race Condition
OVM Tutorial The function $fopen opens the file specified as the filename argument and returns Checker
either a 32 bit multi channel descriptor, or a 32 bit file descriptor, determined by the Task And Function
Easy Labs : SV absence or presence of the type argument. Filename is a character string, or a reg Process Control
Easy Labs : UVM containing a character string that names the file to be opened. Disableing The Block
The multi channel descriptor mcd is a 32 bit reg in which a single bit is set indicating Watchdog
Easy Labs : OVM which file is opened. The least significant bit (bit 0) of a mcd always refers to the Compilation N Simulation
Easy Labs : VMM standard output. Output is directed to two or more files opened with multi channel Switchs
descriptors by bitwise oring together their mcds and writing to the resultant value. Debugging
AVM Switch TB The most significant bit (bit 32) of a multi channel descriptor is reserved, and shall About Code Coverage
VMM Ethernet sample always be cleared, limiting an implementation to at most 31 files opened for output Testing Stratigies
via multi channel descriptors. The file descriptor fd is a 32 bit value. The most File Handling
significant bit (bit 32) of a fd is reserved, and shall always be set; this allows Verilog Semaphore
implementations of the file input and output functions to determine how the file was Finding Testsenarious
Verilog
opened. The remaining bits hold a small number indicating what file is opened. Handling Testcase Files
Verification
Terimination
Verilog Switch TB EXAMPLE Error Injuction
// file open close example Register Verification
Basic Constructs module fopenclose(); Parameterised Macros
   integer mcd,number; White Gray Black Box
   initial Regression
OpenVera    begin Tips
Constructs        mcd = $fopen("xyz.txt"); // opening the file
       repeat(7) Report a Bug or Comment
Switch TB        begin on This section - Your
RVM Switch TB            number = $random ; input is what keeps
           $fdisplay(mcd, " Number is ", number); Testbench.in improving
RVM Ethernet sample        end
with time!
       $fclose(mcd); // closing the file
   end
Specman E endmodule
Interview Questions After simulating the above code, file name called "xyz.txt" will be opened in the same
directory. In above example you show that file is getting open and closing, so
according to that there will be change in value of mcd.

EXAMPLE
// Display mcd value before and after the opening the file.
module fopenclose();
    integer mcd,number;
    initial
    begin
        $display("value of mcd before opening the file %b " , mcd);

http://testbench.in/TB_26_FILE_HANDLING.html[9/26/2012 2:40:40 PM]


WWW.TESTBENCH.IN - Verilog for Verification

        mcd = $fopen("xyz.txt"); // opening the file


        $display("value of mcd after opening the file %b " , mcd);
        repeat(7)
        begin
            number = $random ;
            $fdisplay(mcd, " Number is ", number);
        end
        $fclose(mcd); // closing the file
    end
endmodule
RESULT

value of mcd before opening the file xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx


value of mcd after opening the file 00000000000000000000000000000010

Then how can we check that file is closed or not??


In above example its clear that mcd value is changed as file is opened, if we dont
close the file than it will be remain in stack. But how will we come to
know that file is closed?? That will come after following examples.

Fdisplay

$fdisplay, $fdisplayb, $fdisplayo, $fdisplayh

$display has its own counterparts. Those are $fdisplay, $fdisplayb, $fdisplayo,
$fdisplayh. Instead of writing on screen they are writing on the specific file with is
pointed by the mcd. $fdisplay write in decimal format, $fdisplay in binary, $fdisplay
in octal and $fdisplayh in hex format. so no need to put %d-b-o-h.

EXAMPLE
// file open close example with all $fdisplay

module fopenclose();
    integer mcd,number;
    initial
    begin
        mcd = $fopen("temp.txt"); // mcd = multi_channel_descriptor
        repeat(7)
        begin
            number = $random;
            $fdisplay(mcd, "Number is ", number);
        end
        $fclose(mcd);
    end
endmodule
RESULT

Number is 303379748
Number is -1064739199
Number is -2071669239
Number is -1309649309
Number is 112818957
Number is 1189058957
Number is -1295874971

EXAMPLE $displayb
module fopenclose();
    integer mcd,number;
    initial
    begin

http://testbench.in/TB_26_FILE_HANDLING.html[9/26/2012 2:40:40 PM]


WWW.TESTBENCH.IN - Verilog for Verification

        mcd = $fopen("temp.txt"); // mcd = multi_channel_descriptor


        repeat(7)
        begin
            number = $random;
            $fdisplayb(mcd, "Number is ", number);
        end
        $fclose(mcd);
    end
endmodule
RESULT

Number is 00010010000101010011010100100100
Number is 11000000100010010101111010000001
Number is 10000100100001001101011000001001
Number is 10110001111100000101011001100011
Number is 00000110101110010111101100001101
Number is 01000110110111111001100110001101
Number is 10110010110000101000010001100101

EXAMPLE c. $displayo
module fopenclose();
    integer mcd,number;
    initial
    begin
        mcd = $fopen("temp.txt"); // mcd = multi_channel_descriptor
        repeat(7)
        begin
            number = $random;
            $fdisplayo(mcd, "Number is ", number);
        end
        $fclose(mcd);
    end
endmodule
RESULT

Number is 02205232444
Number is 30042257201
Number is 20441153011
Number is 26174053143
Number is 00656275415
Number is 10667714615
Number is 26260502145

EXAMPLE. $displayh
module fopenclose();
     integer mcd,number;
     initial
     begin
         mcd = $fopen("temp.txt"); // mcd = multi_channel_descriptor
         repeat(7)
         begin
             number = $random;
             $fdisplayh(mcd, "Number is ", number);
         end
         $fclose(mcd);
     end
endmodule
RESULT

Number is 12153524
Number is c0895e81
Number is 8484d609
Number is b1f05663
Number is 06b97b0d
Number is 46df998d
Number is b2c28465

In below example we will see that how we will come to know that file is closed or
not?? so even after closing the file I will try to write in that file, for that it should
give error.

http://testbench.in/TB_26_FILE_HANDLING.html[9/26/2012 2:40:40 PM]


WWW.TESTBENCH.IN - Verilog for Verification

EXAMPLE
module fopenclose();
     integer mcd,number;
     initial
     begin
         $display("value of mcd before opening the file %b " , mcd);
         mcd = $fopen("xyz.txt");
         $display("value of mcd after opening the file %b " , mcd);
         repeat(7)
         begin
             number = $random ;
             $fdisplay(mcd, " Number is ", number);
         end
         $fclose(mcd);
         $fdisplay("value of mcd after closing the file %b ",
         mcd);
     end
endmodule
RESULT

Error during elaboration.

Fmonitor

$fmonitor, $fmonitorb, $fmonitoro, $fmonitorh, $fstrobe, $fstrobeb,$fstrobeo,


$fstrobeh

Like $display; $monitor and $strobe also have counterparts. They also write in
decimal, binary, octal and hexadecimal.

EXAMPLE
// file open close example with $fmonitor
module monitortask();
     integer mcd,number;
     initial
     begin
        #0;
        mcd = $fopen("abc.txt");
        $monitoron;
        repeat(7)
        begin
           #1 number = $random ;
        end
        $monitoroff;
        $fclose(mcd);
     end

     initial
        $fmonitorh(mcd, " Number is ", number);
endmodule
RESULT

Number is 12153524
Number is c0895e81
Number is 8484d609
Number is b1f05663
Number is 06b97b0d
Number is 46df998d

Due to initial-initial race condition we have to put the #0 delay in first initial block
and $monitoron-$monitoroff system task, otherwise it is not able to
cache the updated value of integer "number" because "number" is updated in
active(1st) event while monitor in system task(3rd) event in the event queue.

Fwrite

$fwrite, $fwriteb, $fwriteo, $fwriteh

Like $display; $write also have counterparts. They also write in decimal,binary, octal

http://testbench.in/TB_26_FILE_HANDLING.html[9/26/2012 2:40:40 PM]


WWW.TESTBENCH.IN - Verilog for Verification

and hexadecimal.

EXAMPLE
// file open close example with $fwrite
module writetask();
    integer mcd1,mcd2,number,pointer;
    initial
    begin
        $display("value of mcd1 before opening the file %b " , mcd1);
        $display("value of mcd2 before opening the file %b " , mcd2);
        mcd1 = $fopen("xyz.txt");
        mcd2 = $fopen("pqr.txt");
        $display("value of mcd1 after opening the file %b " , mcd1);
        $display("value of mcd2 after opening the file %b " , mcd2);
        repeat(7)
        begin
             pointer = $random;
             number = $random % 10;
             $fwriteo(mcd1, " Number is ", number);
             $fwriteh(mcd2, " Pointer is ", pointer);
        end
        $fclose(mcd1);
        $fclose(mcd2);
    end
endmodule

One of the reasons behind writing this example is to show how the integers are
getting different value as per the number of files are opened.

RESULT

value of mcd1 before opening the file xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx


value of mcd2 before opening the file xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
value of mcd1 after opening the file 00000000000000000000000000000010
value of mcd2 after opening the file 00000000000000000000000000000100
in file pqr.txt
Pointer is 12153524 Pointer is 8484d609 Pointer is 06b97b0d
Pointer is b2c28465 Pointer is 00f3e301 Pointer is 3b23f176
Pointer is 76d457ed

In file xyz.txt

Number is 37777777767 Number is 37777777767 Number is


00000000007 Number is 37777777774 Number is 00000000011 Number
is 00000000007 Number is 00000000002

Mcd

Simultaneously writing same data to two different file. This example shows how to
set up multi channel descriptors. In this example, two different channels are opened
using the $fopen function. The two multi channel descriptors that are returned by the
function are then combined in a bit-wise or operation and assigned to the integer
variable "broadcast". The "broadcast" variable can then be used as the first parameter
in a file output task to direct output to all two channels at once.

EXAMPLE
module writetask();
     integer mcd1,mcd2,broadcast,number;
     initial
     begin
         mcd1 = $fopen("lsbbit1.txt");
         mcd2 = $fopen("lsbbit2.txt");
         broadcast = mcd1 |mcd2 ;
         repeat(7)
         begin
             number = $random;
             $fdisplayh(broadcast," Number is ", number);
         end
         $fclose(mcd1);
         $fclose(mcd2);
     end
endmodule

http://testbench.in/TB_26_FILE_HANDLING.html[9/26/2012 2:40:40 PM]


WWW.TESTBENCH.IN - Verilog for Verification

RESULT
In lsbbit1.txt

Number is 12153524
Number is c0895e81
Number is 8484d609
Number is b1f05663
Number is 06b97b0d
Number is 46df998d
Number is b2c28465

In lsbbit2.txt

Number is 12153524
Number is c0895e81
Number is 8484d609
Number is b1f05663
Number is 06b97b0d
Number is 46df998d
Number is b2c28465

To create a descriptor that directs output to the standard output that is monitor
screen as well as both the files, the "broadcast" variable is a bit-wise
logical or with the constant 1, which effectively writes to both files as well as monitor
screen.

EXAMPLE
module writetask();
     integer mcd1,mcd2,broadcast,number;
     initial
     begin
         mcd1 = $fopen("lsbbit1.txt");
         mcd2 = $fopen("lsbbit2.txt");
         broadcast = 1 | mcd1 | mcd2 ;
         repeat(7)
         begin
             number = $random;
             $fdisplayh(broadcast," Number is ", number);
         end
         $fclose(mcd1);
         $fclose(mcd2);
     end
     endmodule
endmodule
RESULT

Number is 12153524
Number is c0895e81
Number is 8484d609
Number is b1f05663
Number is 06b97b0d
Number is 46df998d
Number is b2c28465

Formating Data To String

The $swrite family of tasks are based on the $fwrite family of tasks, and accept the
same type of arguments as the tasks upon which they are based, with one exception:
The first parameter to $swrite shall be a reg variable to which the resulting string
shall be written, instead of a variable specifying the file to which to write the
resulting string.

The system task $sformat is similar to the system task $swrite, with a one major
difference. Unlike the display and write family of output system tasks, $sformat
always interprets its second argument, and only its second argument as a format
string. This format argument can be a static string, such as "data is %d" , or can be a
reg variable whose content is interpreted as the format string. No other arguments
are interpreted as format strings. $sformat supports all the format specifies supported
by $display.

EXAMPLE:

http://testbench.in/TB_26_FILE_HANDLING.html[9/26/2012 2:40:40 PM]


WWW.TESTBENCH.IN - Verilog for Verification

$sformat(string, "Formatted %d %x", a, b); 

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TB_26_FILE_HANDLING.html[9/26/2012 2:40:40 PM]


WWW.TESTBENCH.IN - Verilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS VERILOG SEMAPHORE Index


Introduction
SystemVerilog Semaphore In Verilog Linear Tb
Verification File Io Tb
A semaphore is a type of Interposes communication resource used for synchronization State Machine Based Tb
Constructs and mutual exclusion between any two asynchronous processes. A semaphore object is Task Based Tb
Interface a synchronization object that maintains a count between zero and a specified Self Checking Testbench
maximum value. The count is decremented each time a thread completes a wait for Verification Flow
OOPS Clock Generator
the semaphore object and incremented each time a thread releases the semaphore.
Randomization When the count reaches zero, no more threads can successfully wait for the Simulation
semaphore object state to become signaled. The state of a semaphore is set to Incremental Compilation
Functional Coverage Store And Restore
signaled when its count is greater than zero, and non-signaled when its count is zero.
Assertion The semaphore object is useful in controlling a shared resource that can support a Event Cycle Simulation
limited number of users. It acts as a gate that limits the number of threads sharing Time Scale And Precision
DPI Stimulus Generation
the resource to a specified maximum number.
UVM Tutorial System Function Random
Take an example, Many components in the testbench wants to access the dut A Myth
VMM Tutorial Race Condition
memory. But memory has only one interface. So only one can do write and read
OVM Tutorial operation at a time. Using semaphore, we can make sure that only one operation is Checker
done at a time. Task And Function
Easy Labs : SV
Process Control
Easy Labs : UVM Imagine a home with six persons living. They have only one car. Everyone wants to Disableing The Block
drive the car. But others plan to make a trip, when some other has gone out with car. Watchdog
Easy Labs : OVM
The eldest person in home made a rule. Key will be with  him. Whoever wants, come Compilation N Simulation
Easy Labs : VMM to me and get the key. After finishing the job, return the key to him. This way, only Switchs
AVM Switch TB one can plan for the trip. Debugging
About Code Coverage
VMM Ethernet sample Testing Stratigies
EXAMPLE: File Handling
module sema();  Verilog Semaphore
Verilog Finding Testsenarious
    integer keys;  Handling Testcase Files
Verification
     Terimination
Verilog Switch TB     initial  Error Injuction
       keys = 1;  Register Verification
Basic Constructs
     Parameterised Macros
    task get_key();  White Gray Black Box
    input integer i;  Regression
OpenVera     begin  Tips
Constructs         if ( keys == 0) 
        begin  Report a Bug or Comment
Switch TB
        $display(" KEY IS NOT AVAILABLE : WAITING FOR KEYS : process %d",i);  on This section - Your
RVM Switch TB         wait(keys == 1);  input is what keeps
Testbench.in improving
RVM Ethernet sample         end 
        $display(" GOT THE KEY : GET SET GO :process %d",i);  with time!
        keys = 0; 
    end  
Specman E     endtask 
Interview Questions     
    task put_keys(); 
    input integer i; 
    begin 
        keys = 1 ; 
        $display(" PROCESS %d gave the key back ",i); 
    end 
    endtask 
    
    initial 
    begin 

http://testbench.in/TB_27_VERILOG_SEMAPHORE.html[9/26/2012 2:40:48 PM]


WWW.TESTBENCH.IN - Verilog for Verification

       # 10 ; 
       get_key(1); 
       repeat(4) 
       # 10 $display(" PROCESS 1 GOT KEYS : OTHERS CANT WRITE MESSAGE TO LOG "); 
       put_keys(1); 
    end 
    
    initial 
    begin 
        # 10 ; 
        get_key(2); 
        repeat(4) 
        # 10 $display(" PROCESS 2 GOT KEYS : OTHERS CANT WRITE MESSAGE TO LOG "); 
        put_keys(2); 
    end 
    
endmodule 

RESULTS:

GOT THE KEY : GET SET GO :process 1


KEY IS NOT AVAILABLE : WAITING FOR KEYS : process 2
PROCESS 1 GOT KEYS : OTHERS CANT WRITE MESSAGE TO LOG  
PROCESS 1 GOT KEYS : OTHERS CANT WRITE MESSAGE TO LOG  
PROCESS 1 GOT KEYS : OTHERS CANT WRITE MESSAGE TO LOG  
PROCESS 1 GOT KEYS : OTHERS CANT WRITE MESSAGE TO LOG  
PROCESS 1 gave the key back  
GOT THE KEY : GET SET GO :process 2
PROCESS 2 GOT KEYS : OTHERS CANT WRITE MESSAGE TO LOG  
PROCESS 2 GOT KEYS : OTHERS CANT WRITE MESSAGE TO LOG  
PROCESS 2 GOT KEYS : OTHERS CANT WRITE MESSAGE TO LOG  
PROCESS 2 GOT KEYS : OTHERS CANT WRITE MESSAGE TO LOG  
PROCESS 2 gave the key back  

In this home, some of them are not interested to wait until they got the key. So they
want tp progress to other works without waiting for keys.
The following example shows, if keys are not available, the process don't wait.

EXAMPLE:
module sema(); 

integer keys; 

initial 
keys = 1; 

task get_key(); 
input integer i; 
begin 
if ( keys == 0) 
begin 
$display(" KEY IS NOT AVAILABLE : WAITING FOR KEYS : process %d",i); 
wait(keys == 1); 
end 
$display(" GOT THE KEY : GET SET GO :process %d",i); 
keys = 0; 
end  
endtask 

function get_key_dont_wait(); 
input integer i; 

http://testbench.in/TB_27_VERILOG_SEMAPHORE.html[9/26/2012 2:40:48 PM]


WWW.TESTBENCH.IN - Verilog for Verification

reg got; 
begin 
got =0; 
if ( keys == 0) 
$display(" KEY IS NOT AVAILABLE : LEAVING WITHOUT WAITING FOR KEYS : process
%d",i); 
else 
begin 
$display(" GOT THE KEY : GET SET GO :process %d",i); 
keys = 0; 
got = 1; 
end 
get_key_dont_wait = got; 
end  
endfunction 

task put_keys(); 
input integer i; 
begin 
keys = 1 ; 
$display(" PROCESS %d gave the key back ",i); 
end 
endtask 

initial 
begin 
# 10 ; 
get_key(1); 
repeat(4) 
# 10 $display(" PROCESS 1 GOT KEYS : OTHERS CANT WRITE MESSAGE TO LOG "); 
put_keys(1); 
end 

initial 
begin 
# 10 ; 
if(get_key_dont_wait(2)) 
begin 
repeat(4) 
# 10 $display(" PROCESS 2 GOT KEYS : OTHERS CANT WRITE MESSAGE TO LOG "); 
put_keys(2); 
end 
else 
$display(" IM not interested to wait "); 
end 

endmodule 

RESULTS:

GOT THE KEY : GET SET GO :process 1


KEY IS NOT AVAILABLE : LEAVING WITHOUT WAITING FOR KEYS : process 2
IM not interested to wait  
PROCESS 1 GOT KEYS : OTHERS CANT WRITE MESSAGE TO LOG  
PROCESS 1 GOT KEYS : OTHERS CANT WRITE MESSAGE TO LOG  
PROCESS 1 GOT KEYS : OTHERS CANT WRITE MESSAGE TO LOG  
PROCESS 1 GOT KEYS : OTHERS CANT WRITE MESSAGE TO LOG  
PROCESS 1 gave the key back

After some days, they got new car to home. Now they have two cars, at once 2
members can go on drive. Looking at the following code. The keys are initialized to 2.
Two processes are running at once.

EXAMPLE:
module sema(); 

integer keys; 

initial 
keys = 2; 

http://testbench.in/TB_27_VERILOG_SEMAPHORE.html[9/26/2012 2:40:48 PM]


WWW.TESTBENCH.IN - Verilog for Verification

task get_key(); 
input integer i; 
begin 
if ( keys == 0) 
begin 
$display(" KEY IS NOT AVAILABLE : WAITING FOR KEYS : process %d",i); 
wait(keys > 0); 
end 
$display(" GOT THE KEY : GET SET GO :process %d",i); 
keys = keys - 1; 
end  
endtask 

function get_key_dont_wait(); 
input integer i; 
reg got; 
begin 
got =0; 
if ( keys == 0) 
$display(" KEY IS NOT AVAILABLE : LEAVING WITHOUT WAITING FOR KEYS : process
%d",i); 
else 
begin 
$display(" GOT THE KEY : GET SET GO :process %d",i); 
keys = keys - 1; 
got = 1; 
end 
get_key_dont_wait = got; 
end  
endfunction 

task put_keys(); 
input integer i; 
begin 
keys = keys + 1 ; 
$display(" PROCESS %d gave the key back ",i); 
end 
endtask 

initial 
begin 
# 10 ; 
get_key(1); 
repeat(4) 
# 10 $display(" PROCESS 1 GOT KEYS : IM ALOS RUNNING "); 
put_keys(1); 
end 

initial 
begin 
# 10 ; 
if(get_key_dont_wait(2)) 
begin 
repeat(4) 
# 10 $display(" PROCESS 2 GOT KEYS : IM ALSO RUNNING "); 
put_keys(2); 
end 
else 
$display(" IM not interested to wait "); 
end 

endmodule 

RESULTS:

GOT THE KEY : GET SET GO :process 1


GOT THE KEY : GET SET GO :process 2
PROCESS 1 GOT KEYS : IM ALOS RUNNING  
PROCESS 2 GOT KEYS : IM ALSO RUNNING  
PROCESS 1 GOT KEYS : IM ALOS RUNNING  
PROCESS 2 GOT KEYS : IM ALSO RUNNING  
PROCESS 1 GOT KEYS : IM ALOS RUNNING  
PROCESS 2 GOT KEYS : IM ALSO RUNNING  

http://testbench.in/TB_27_VERILOG_SEMAPHORE.html[9/26/2012 2:40:48 PM]


WWW.TESTBENCH.IN - Verilog for Verification

PROCESS 1 GOT KEYS : IM ALOS RUNNING  


PROCESS 1 gave the key back  
PROCESS 2 GOT KEYS : IM ALSO RUNNING  
PROCESS 2 gave the key back

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TB_27_VERILOG_SEMAPHORE.html[9/26/2012 2:40:48 PM]


WWW.TESTBENCH.IN - Verilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS FINDING TESTSENARIOUS Index


Introduction
SystemVerilog Test scenarios can be divided in to following category while implementing @bull test Linear Tb
Verification plan.  File Io Tb
@bull Register Tests State Machine Based Tb
Constructs @bull Interrupt Tests   Task Based Tb
Interface @bull Interface Tests   Self Checking Testbench
@bull Protocol Tests   Verification Flow
OOPS Clock Generator
@bull Functional Tests  
Randomization @bull Error Tests Simulation
@bull Golden Tests Incremental Compilation
Functional Coverage Store And Restore
@bull Performance Tests
Assertion Event Cycle Simulation
Register Tests Time Scale And Precision
DPI Stimulus Generation
UVM Tutorial This is complex to build efficiently. These tests requires more advanced planning and System Function Random
architecting . A poorly planned infrastructure is buggy, insufficient, and hard to use. A Myth
VMM Tutorial Race Condition
OVM Tutorial System Tests Checker
Task And Function
Easy Labs : SV
These tests Verify whether ASIC interacts correctly with other ASICs / ICs correctly in Process Control
Easy Labs : UVM the system. Disableing The Block
Watchdog
Easy Labs : OVM
Interrupt Tests Compilation N Simulation
Easy Labs : VMM Switchs
AVM Switch TB These tests Verify how the interrupt logic is working. Debugging
About Code Coverage
VMM Ethernet sample Interface Tests Testing Stratigies
File Handling
These tests verify the Interface functionality. Verilog Semaphore
Verilog Finding Testsenarious
Functional Tests Handling Testcase Files
Verification
Terimination
Verilog Switch TB Contains scenarios related to specific features & combinations of these features.   Error Injuction
Register Verification
Basic Constructs
Error Tests Parameterised Macros
White Gray Black Box
Error-oriented testing develops test data by focusing on the presence or absence of Regression
OpenVera errors in DUT. Tips
Constructs
Golden Tests Report a Bug or Comment
Switch TB
on This section - Your
RVM Switch TB Set of well defined test cases executed on a modified code to ensure that changes input is what keeps
Testbench.in improving
RVM Ethernet sample made to the code haven't adversely affected previously existing functions. These
includes register tests, interrupt tests, interface tests, protocol tests, functional tests with time!
& error tests.
Specman E Performance Tests
Interview Questions
These tests measures how well the product meets its specified performance
objectives. Example: bandwidth monitoring.

http://testbench.in/TB_28_FINDING_TESTSENARIOUS.html[9/26/2012 2:40:58 PM]


WWW.TESTBENCH.IN - Verilog for Verification

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TB_28_FINDING_TESTSENARIOUS.html[9/26/2012 2:40:58 PM]


WWW.TESTBENCH.IN - Verilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS HANDLING TESTCASE FILES Index


Introduction
SystemVerilog Linear Tb
Verification A test case is a file that describes an input, action, or event and an expected File Io Tb
response, to determine if a feature of an application is working correctly. A test case State Machine Based Tb
Constructs should contain particulars such as test case identifier, test case name, objective, test Task Based Tb
Interface conditions/setup, input data requirements, steps, and expected results. Self Checking Testbench
Verification Flow
OOPS Clock Generator
Note that the process of developing test cases can help find problems in the
Randomization requirements or design of an application, since it requires completely thinking through Simulation
the operation of the application. For this reason, it's useful to prepare test cases early Incremental Compilation
Functional Coverage Store And Restore
in the development cycle if possible.  
Assertion Event Cycle Simulation
Time Scale And Precision
DPI Stimulus Generation
The following example contains testbench environment and has 2 test cases.
UVM Tutorial System Function Random
A Myth
VMM Tutorial Race Condition
EXAMPLE:  top.v
OVM Tutorial Checker
module top();  Task And Function
Easy Labs : SV
// DUT instance, clock generator and TB components Process Control
Easy Labs : UVM Disableing The Block
// some tasks Watchdog
Easy Labs : OVM
Compilation N Simulation
Easy Labs : VMM task write()  Switchs
AVM Switch TB begin  Debugging
// some logic About Code Coverage
VMM Ethernet sample end  Testing Stratigies
endtask  File Handling
Verilog Semaphore
Verilog task read()  Finding Testsenarious
begin  Handling Testcase Files
Verification
// some logic Terimination
Verilog Switch TB end  Error Injuction
endtask  Register Verification
Basic Constructs
Parameterised Macros
White Gray Black Box
end  Regression
OpenVera Tips
Constructs EXAMPLE: testcase_1.v
Report a Bug or Comment
Switch TB
// Do 10 write operations on This section - Your
RVM Switch TB input is what keeps
Testbench.in improving
RVM Ethernet sample EXAMPLE: testcase_2.v
with time!
// Do 10 read operations
Specman E
Interview Questions
To test first test cases, We have to simulate the contents of top.v file and
testcase_1.v file.

1) Take an instance of module TEST in top.v file. Define the module definition in test
cases.

During compilation just use the following commands

for testcase_1.v file


comile_command top.v testcase_1.v

http://testbench.in/TB_29_HANDLING_TESTCASE_FILES.html[9/26/2012 2:41:06 PM]


WWW.TESTBENCH.IN - Verilog for Verification

for testcase_2.v file


comile_command top.v testcase_2.v

EXAMPLE:  top.v

module top(); 
// DUT instance, clock generator and TB components

// some tasks

task write() 
begin 
// some logic
end 
endtask 

task read() 
begin 
// some logic
end 
endtask 

//  TEST case instance

TEST tst(); 

end 

EXAMPLE: testcase_1.v

// Do 10 write operations

module TEST(); 

initial 
repeat(10) 
top.write(); 

endmodule 
EXAMPLE: testcase_2.v

// Do 10 read operations

module TEST(); 

initial 
repeat(10) 
top.read(); 

endmodule 

2) use `include test.v file. This needs a small script to copy the testcase file to test
file. The compilation command is same. But copy command which copies the testcase
to test.v file is different.

During compilation just use the following commands

for testcase_1.v file


cp testcase_1 test.v

http://testbench.in/TB_29_HANDLING_TESTCASE_FILES.html[9/26/2012 2:41:06 PM]


WWW.TESTBENCH.IN - Verilog for Verification

comile_command top.v test.v

for testcase_2.v file


cp testcase_2 test.v
comile_command top.v test.v

EXAMPLE:  top.v

module top(); 
// DUT instance, clock generator and TB components

// some tasks

task write() 
begin 
// some logic
end 
endtask 

task read() 
begin 
// some logic
end 
endtask 

//  incule test.v file

`include test.v

end 

EXAMPLE: testcase_1.v

// Do 10 write operations

initial 
repeat(10) 
top.write(); 

EXAMPLE: testcase_2.v

// Do 10 read operations

initial 
repeat(10) 
top.read(); 

2) With the above two approaches, for each test case, we have to do individual
compilation. In  this method, compile once and use simulation command to test with
individual test case.

This needs a small script to convert all the test cases to single intermediate file.
compilation command is same. During simulation by giving the test case file name, we
can include particular testcase.

During compilation just give following command

cat testcase_1.v > test.v


cat testcase_2.v > test.v
compile_command top.v test.v

During simulation ,
for each test case, use

run_command +testcase_1
run_coomand +testcase_2

EXAMPLE:  top.v

module top(); 
// DUT instance, clock generator and TB components

http://testbench.in/TB_29_HANDLING_TESTCASE_FILES.html[9/26/2012 2:41:06 PM]


WWW.TESTBENCH.IN - Verilog for Verification

// some tasks

task write() 
begin 
// some logic
end 
endtask 

task read() 
begin 
// some logic
end 
endtask 

//  incule test.v file

`include test.v

end 

EXAMPLE: testcase_1.v

// Do 10 write operations

repeat(10) 
top.write(); 

EXAMPLE: testcase_2.v

// Do 10 read operations

repeat(10) 
top.read(); 

Intermediate file generated contains all the testcase contents with some extra logic as
shown.

EXAMPLE: INTERMEDIATE FILE   test.v

initial 
begin 
if($test$plusargs("testcase_1")    
begin             // testcase_1 contents
// Do 10 write operations
repeat(10) 
top.write(); 
end 
if($test$plusargs("testcase_2") 
begin            // testcase_2 contents
// Do 10 read operations
repeat(10) 
top.read(); 
end 
end 

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/TB_29_HANDLING_TESTCASE_FILES.html[9/26/2012 2:41:06 PM]


WWW.TESTBENCH.IN - Verilog for Verification

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TB_29_HANDLING_TESTCASE_FILES.html[9/26/2012 2:41:06 PM]


WWW.TESTBENCH.IN - Verilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS TERIMINATION Index


Introduction
SystemVerilog Linear Tb
Verification Simulation should terminate after all the required operations are done. Recommended File Io Tb
way to exit simulation is using a task. This termination task contains some messages State Machine Based Tb
Constructs about the activities done and $finish. This task should be called after collecting all the Task Based Tb
Interface responses from DUT, then analyzing them only. If the simulation time is long and if Self Checking Testbench
there is bug in DUT, you can stop simulation at that time itself. This saves lot of time. Verification Flow
OOPS Clock Generator
Otherwise, even after the testbench found error, it will simulate till the end of the
Randomization process or it may get hanged and waste your time and costly licenses. Simulation
Incremental Compilation
Functional Coverage Store And Restore
 Sometimes, you are not just interested to terminate the simulation for known
Assertion unfixed bugs. Then there should be a controllable way not to stop the simulation even Event Cycle Simulation
after the error was found. Time Scale And Precision
DPI Stimulus Generation
UVM Tutorial System Function Random
EXAMPLE: A Myth
VMM Tutorial Race Condition
OVM Tutorial task teriminate();  Checker
begin  Task And Function
Easy Labs : SV
if(no_of_errors == 0)  Process Control
Easy Labs : UVM $display(" *********TEST PASSED ***********");  Disableing The Block
else  Watchdog
Easy Labs : OVM
$display(" *********TEST FAILED ***********");  Compilation N Simulation
Easy Labs : VMM Switchs
AVM Switch TB #10 $display(" SIMULATION TERMINATION at %d",$time);  Debugging
$finish;  About Code Coverage
VMM Ethernet sample end  Testing Stratigies
endtask  File Handling
Verilog Semaphore
Verilog always@(error)  Finding Testsenarious
begin  Handling Testcase Files
Verification
no_of_errors = num_of_errors +1 ;  Terimination
Verilog Switch TB Error Injuction
`ifndef CONTINUE_ON_ERROR  Register Verification
Basic Constructs
terminate();  Parameterised Macros
`endif  White Gray Black Box
end  Regression
OpenVera Tips
Constructs
Report a Bug or Comment
Switch TB
If you know already a well known bug is there and it is giving 2 error counts. Its on This section - Your
RVM Switch TB better to stop the simulation after 2 errors. From command line just give input is what keeps
Testbench.in improving
RVM Ethernet sample +define+NO_FO_ERR=2, simulation terminates after 3 errors.
with time!

EXAMPLE:
Specman E always@(error) 
Interview Questions begin 
no_of_errors = num_of_errors +1 ; 

`ifndef CONTINUE_ON_ERROR 
`ifndef NO_OF_ERR 
`define NO_OF_ERR 0 
`endif 
if(`NO_OF_ERR < no_of_erros) 
terminate(); 
`endif 
end 

http://testbench.in/TB_30_TERIMINATION.html[9/26/2012 2:41:13 PM]


WWW.TESTBENCH.IN - Verilog for Verification

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TB_30_TERIMINATION.html[9/26/2012 2:41:13 PM]


WWW.TESTBENCH.IN - Verilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS ERROR INJUCTION Index


Introduction
SystemVerilog Linear Tb
Verification To verify error detection, reporting, and recovery features of the DUT, an error File Io Tb
injection mechanism must be in place in testbench to generate error scenarios. The State Machine Based Tb
Constructs objective is to ensure that the errors are handled correctly. This is accomplished by Task Based Tb
Interface introducing internal monitoring mechanisms. The simulation environment integrates a Self Checking Testbench
structure to randomly set the errors and verify that each error condition is handled Verification Flow
OOPS Clock Generator
properly.
Randomization Simulation
Errors can be classified in to following categories: Incremental Compilation
Functional Coverage Store And Restore
Assertion Value Errors Event Cycle Simulation
Time Scale And Precision
DPI Stimulus Generation
The specification says that packet length should be greater than 64 and less than
UVM Tutorial 1518. Testbench should be able to generate packets of length less than 64 and greater System Function Random
than 1518 and verify how the DUT is handling these. Testbench should also monitor A Myth
VMM Tutorial Race Condition
that DUT is not generating any packets violating this rule.
OVM Tutorial Checker
Temporal Errors Task And Function
Easy Labs : SV
Process Control
Easy Labs : UVM Errors like acknowledgement should come after 4 cycles of request.   Disableing The Block
Watchdog
Easy Labs : OVM
Compilation N Simulation
Easy Labs : VMM Interface Error Switchs
AVM Switch TB Debugging
Sometimes interfaces have invalid pins or error pins to inform to DUT that the some About Code Coverage
VMM Ethernet sample malfunction happened. Generate scenarios to test whether the DUT is properly Testing Stratigies
responding to these signals. File Handling
Verilog Semaphore
Verilog Finding Testsenarious
Sequence Errors Handling Testcase Files
Verification
Terimination
Verilog Switch TB To test protocols which define sequence of operations, generate sequence which Error Injuction
violates the rule and check the DUT. Register Verification
Basic Constructs
Parameterised Macros
White Gray Black Box
Regression
OpenVera Tips
Constructs
Report a Bug or Comment
Switch TB
on This section - Your
RVM Switch TB input is what keeps
Testbench.in improving
RVM Ethernet sample
with time!

Specman E
Interview Questions

http://testbench.in/TB_31_ERROR_INJUCTION.html[9/26/2012 2:41:22 PM]


WWW.TESTBENCH.IN - Verilog for Verification

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TB_31_ERROR_INJUCTION.html[9/26/2012 2:41:22 PM]


WWW.TESTBENCH.IN - Verilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS REGISTER VERIFICATION Index


Introduction
SystemVerilog Register Verification Linear Tb
Verification File Io Tb
Todays complex chips has thousands of register to configure the chip and to State Machine Based Tb
Constructs communicate the status to software. These registers  play a complex role in the chip Task Based Tb
Interface operation So a test bench should verify these registers properly. Verification of these Self Checking Testbench
registers is tedious. As there are thousands of registers in a chip, the testbench should Verification Flow
OOPS Clock Generator
have a handy hooks to access these registers. Implementing testbench components
Randomization for these registers is not one time job. Most designs change their register Simulation
specification during the design development. So a very flexible testbench component Incremental Compilation
Functional Coverage Store And Restore
should be available to satisfy these needs. When I was working for Ample, we had a
Assertion script which generates testbench component for these registers. Register Event Cycle Simulation
specification is input to these script. So when ever register file is changed, Just run Time Scale And Precision
DPI Stimulus Generation
the script, we don't need to change verilog module for these changes. These scripts
UVM Tutorial can be used across modules, across projects and across companies also. There are System Function Random
some EDA tools just to do this job. I believe that a proper homemade script has better A Myth
VMM Tutorial Race Condition
control then getting it from some EDA guy and you know home made scripts are life
OVM Tutorial time free. Checker
Task And Function
Easy Labs : SV
Process Control
Easy Labs : UVM Register Classification: Disableing The Block
Watchdog
Easy Labs : OVM
Registers can be mainly classified in to these categories Compilation N Simulation
Easy Labs : VMM 1) Configuration Registers. Switchs
AVM Switch TB 2) Status Registers. Debugging
3) Mask Registers. About Code Coverage
VMM Ethernet sample 4) Interrupt Registers(makeable and nonmaskable). Testing Stratigies
File Handling
Verilog Semaphore
Verilog Finding Testsenarious
Features: Handling Testcase Files
Verification
Terimination
Verilog Switch TB What are the features that this testbench component should support? Error Injuction
Register Verification
Basic Constructs
1) It should have a data structure to store the values of config register .Testbench will Parameterised Macros
write in to these register while it is writing to dut registers. These are called shadow White Gray Black Box
registers. Shadow registers should have the same address and register name as DUT so Regression
OpenVera it is easy to debug. Tips
Constructs
2) Back door access: There are two type of access to register in DUT. Front door and Report a Bug or Comment
Switch TB
back door. Front door access uses physical bus . To write a value in to DUT registers, on This section - Your
RVM Switch TB it takes some clock cycles in front door access. And writing for thousands of registers input is what keeps
Testbench.in improving
RVM Ethernet sample is resource consuming. Remember, only one register can be assigned at a time. One
cannot make sure that only one method is called at one time. To make sure that only with time!
one method is assessing the bus, semaphore is used. In back door access, registers are
access directly. In zero time. Accessing to these locations using back door will save
Specman E simulation time. There should be a switch to control these feature. So after verifying
Interview Questions the actual access path of these registers, we can start using back door access. In
verilog, using Hierarchy reference to DUT register, we can by pass this path.

3) The Shadow registers by default should contain default values from register
specification. A task should be provided to compare each register in shadow registers
and DUT. After reset, just call this task before doing any changes to DUT registers.
This will check the default values of the registers.

4) Methods should be provided for read or write operation to dut registers using name
and also address. Named methods are handy and readable mainly from test cases.
While address based methods are good while writing to bulk locations( using for loop

http://testbench.in/TB_32_REGISTER_VERIFICATION.html[9/26/2012 2:41:29 PM]


WWW.TESTBENCH.IN - Verilog for Verification

etc...).
 
5) Every register in Testbench may have these information.
// Comments which describes the register information.
Address of register.
Offset of register.
Width of register.
Reset value.
Access permissions.
Register value.
Register name as string.( Name should be self descriptive and same as in DUT. This
string is used in printing while debugging.)

Some are methods which are used for register in functional verification .
Read function.
Write task.
Update task.
Print task.
Check function.
write_random task.

All the above methods should be accessible by name and also by address.

Write random task:


Some registers values can be any constrained random value. Lets take an ether net.
The unicast destination address can be any value which is not broadcast or multi cast.
So the random values should be constraint. Some times, these random values depend
on some other registers also. If this task is not provided,  while writing the test cases,
one may forget the limitation of the register value and the DUT misbehaves and may
spend hours in debugging. The best way to use random values is using this task.

Update task:
Interrupt and status registers in Testbench should be updated by update task. These
registers should contain the expected values. When check function is called, the
check reads the register values in DUT and compares with the expected value in
shadow registers.

Check task:
Check task compares the DUT and shadow registers. Care should be taken while using
back door access, as they are not cycle accurate. Config registers are compared for
what is configured and what is in the register. Interrupt and status registers are
compared with what is in DUT with the expected values.

Access permission:
Each register in test bench should maintain the permissions. This permissions are used
in write, read, check methods.

Fallowing are possible types of permissions:


read/write
read only
write only
read only,  write can be by the design
clear on read
automatically set to 1 by design.
Automatically set to 0 by design.
Readable and settable by writing 1
Readable and clearable by writing 1

By default the type of permission is read/write. If you are using any scripts, if you
don't mention any permission, then it should be considered as read/write.

http://testbench.in/TB_32_REGISTER_VERIFICATION.html[9/26/2012 2:41:29 PM]


WWW.TESTBENCH.IN - Verilog for Verification

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TB_32_REGISTER_VERIFICATION.html[9/26/2012 2:41:29 PM]


WWW.TESTBENCH.IN - Verilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PARAMETERISED MACROS Index


Introduction
SystemVerilog Linear Tb
Verification How do we get rid of the typing repeating functionality which should be present at File Io Tb
compilation level ? State Machine Based Tb
Constructs Task Based Tb
Interface You can Use generate block. But Generate will not help always. Self Checking Testbench
Verification Flow
OOPS Clock Generator
Look at the example.
Randomization There are four modules and_gate,or_gate,xor_gate,nand_gate. They are instantiated Simulation
in top modules. Incremental Compilation
Functional Coverage Store And Restore
Assertion Each module has 2 inputs a,b and one output c. Instance port are connected wires Event Cycle Simulation
which are prefixed with getname to signal name. Time Scale And Precision
DPI Stimulus Generation
Example
UVM Tutorial    System Function Random
 and_gate  a_g (.a(and_a), .b(and_b), .c(and_c)  ); A Myth
VMM Tutorial Race Condition
OVM Tutorial and is prefexed to signal "a","b" and "c". Checker
Task And Function
Easy Labs : SV
The following is what a novice engineer will do. Process Control
Easy Labs : UVM Disableing The Block
CODE: Watchdog
Easy Labs : OVM
Compilation N Simulation
Easy Labs : VMM module top(); Switchs
AVM Switch TB wire and_a, or_a, xor_a, nand_a ; Debugging
wire and_b, or_b, xor_b, nand_b ; About Code Coverage
VMM Ethernet sample wire and_c, or_c, xor_c, nand_c ; Testing Stratigies
File Handling
and_gate  a_g (.a(and_a), .b(and_b), .c(and_c)  ); Verilog Semaphore
Verilog or_gate   o_g (.a(or_a),  .b(or_b),  .c(or_c)   ); Finding Testsenarious
xor_gate  x_g (.a(xor_a), .b(xor_b), .c(xor_c)  ); Handling Testcase Files
Verification
nand_gate n_g (.a(nand_a),.b(nand_b),.c(nand_c) ); Terimination
Verilog Switch TB Error Injuction
Register Verification
Basic Constructs
endmodule Parameterised Macros
White Gray Black Box
Regression
OpenVera module and_gate(a,b,c); Tips
Constructs input a,b;
output c; Report a Bug or Comment
Switch TB
endmodule on This section - Your
RVM Switch TB input is what keeps
Testbench.in improving
RVM Ethernet sample module or_gate(a,b,c);
input a,b; with time!
output c;
endmodule
Specman E
Interview Questions module xor_gate(a,b,c);
input a,b;
output c;
endmodule

module nand_gate(a,b,c);
input a,b;
output c;
endmodule

http://testbench.in/TB_33_PARAMETERISED_MACROS.html[9/26/2012 2:41:37 PM]


WWW.TESTBENCH.IN - Verilog for Verification

This looks easy to do, as there are 3 inputs only. Real time projects doesnt have this
much less. One may probable spend half day to connect all the ports. Sometime later
if there is change in any of the ports, then all the instances needs to be changed.

Using parameterized macros, this job can be done easily. The directive <91>define
creates a macro for text substitution. This directive can be used both inside and
outside module definitions. After a text macro is defined, it can be used in the source
description by using the (<91>) character, followed by the macro name. The compiler
shall substitute the text of the macro for the string `macro_name. All compiler
directives shall be considered predefined macro names; it shall be illegal to redefine
a compiler directive as a macro name.

A text macro can be defined with arguments. This allows the macro to be customized
for each use individually. If a one-line comment (that is, a comment specified with
the characters //) is included in the text, then the comment shall not become part of
the substituted text.

EXAMPLE:
<91>define max(a,b)((a) > (b) ? (a) : (b))
n = <91>max(p+q, r+s) ;

To use this for the above discussed example,

First step is declare a parameterized macro.


Second step is just use macro instance.

CODE:
`define GATE(M) M\
_gate M\
_g (.a(M\
_a), .b(M\
_b), .c(M\
_c));

`define SIG and_\
S, or_\
S,xor_\
S,nand_\
S; \

module top();
wire `SIG(a)
wire `SIG(b)
wire `SIG(c)

`GATE(and)
`GATE(or)
`GATE(xor)
`GATE(nand)

endmodule

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/TB_33_PARAMETERISED_MACROS.html[9/26/2012 2:41:37 PM]


WWW.TESTBENCH.IN - Verilog for Verification

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TB_33_PARAMETERISED_MACROS.html[9/26/2012 2:41:37 PM]


WWW.TESTBENCH.IN - Verilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS WHITE GRAY BLACK BOX Index


Introduction
SystemVerilog Black Box Verification Linear Tb
Verification File Io Tb
State Machine Based Tb
Constructs Task Based Tb
Interface Self Checking Testbench
Verification Flow
OOPS Clock Generator
Randomization Black Box verification refers to the technique of Simulation
verification if  system with no knowledge of the internals of the DUT. Black Box Incremental Compilation
Functional Coverage Store And Restore
testbench do not have access to the source code of DUT, and are oblivious of the DUT
Assertion architecture. A Black Box testbench, typically, interacts with a system through a user Event Cycle Simulation
interface by providing inputs and examining outputs, without knowing where and how Time Scale And Precision
DPI Stimulus Generation
the inputs were operated upon. In Black Box verification, the target DUT is exercised
UVM Tutorial over a range of inputs, and the outputs are observed for correctness. How those System Function Random
outputs are generated or what is inside the box doesn't matter. A Myth
VMM Tutorial Race Condition
OVM Tutorial Checker
White Box Verification Task And Function
Easy Labs : SV
Process Control
Easy Labs : UVM In White box verification, testbench has access to internal structure of DUT. This Disableing The Block
makes the testbench environment reuse less. This is not much preferred in the Watchdog
Easy Labs : OVM
industry. Compilation N Simulation
Easy Labs : VMM Switchs
AVM Switch TB Debugging
Gray Box Verification About Code Coverage
VMM Ethernet sample Testing Stratigies
Gray box verification, the name itself Conway that testbench has access to some part File Handling
of the DUT. Verilog Semaphore
Verilog Finding Testsenarious
Handling Testcase Files
Verification
Terimination
Verilog Switch TB Error Injuction
Register Verification
Basic Constructs
Parameterised Macros
White Gray Black Box
Regression
OpenVera Tips
Constructs
Report a Bug or Comment
Switch TB
on This section - Your
RVM Switch TB input is what keeps
Testbench.in improving
RVM Ethernet sample
with time!

Specman E
Interview Questions

http://testbench.in/TB_34_WHITE_GRAY_BLACK_BOX.html[9/26/2012 2:41:47 PM]


WWW.TESTBENCH.IN - Verilog for Verification

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TB_34_WHITE_GRAY_BLACK_BOX.html[9/26/2012 2:41:47 PM]


WWW.TESTBENCH.IN - Verilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS REGRESSION Index


Introduction
SystemVerilog Linear Tb
Verification Regression is re-running previously run tests and checking whether previously fixed File Io Tb
faults have re-emerged. New bugs may come out due to new changes in RTL or DUT to State Machine Based Tb
Constructs unmasking of previously hidden bugs due to new changes. Each time time,when design Task Based Tb
Interface is changed, regression is done. One more important aspect of regression is testing by Self Checking Testbench
generation new vectors. Usually the seed to generate stimulus is the system time. Verification Flow
OOPS Clock Generator
Whenever a regression is done, it will take the current system time and generate new
Randomization vectors than earlier tested. This way testbench can reach corners of DUT. Simulation
Incremental Compilation
Functional Coverage Store And Restore
Assertion Event Cycle Simulation
Time Scale And Precision
DPI Stimulus Generation
UVM Tutorial System Function Random
A Myth
VMM Tutorial Race Condition
OVM Tutorial Checker
Task And Function
Easy Labs : SV
Process Control
Easy Labs : UVM Disableing The Block
Watchdog
Easy Labs : OVM
Compilation N Simulation
Easy Labs : VMM Switchs
AVM Switch TB Debugging
About Code Coverage
VMM Ethernet sample Testing Stratigies
File Handling
Verilog Semaphore
Verilog Finding Testsenarious
Handling Testcase Files
Verification
Terimination
Verilog Switch TB Error Injuction
Register Verification
Basic Constructs
Parameterised Macros
White Gray Black Box
Regression
OpenVera Tips
Constructs
Report a Bug or Comment
Switch TB
on This section - Your
RVM Switch TB input is what keeps
Testbench.in improving
RVM Ethernet sample
with time!

Specman E
Interview Questions

http://testbench.in/TB_35_REGRESSION.html[9/26/2012 2:41:54 PM]


WWW.TESTBENCH.IN - Verilog for Verification

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TB_35_REGRESSION.html[9/26/2012 2:41:54 PM]


WWW.TESTBENCH.IN - Verilog for Verification

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS TIPS Index


Introduction
SystemVerilog How To Avoid &Quot;Module Xxx Already Defined&Quot; Error Linear Tb
Verification File Io Tb
State Machine Based Tb
Constructs Sometimes compilation error "module xxx already defined" is tough to avoid when Task Based Tb
Interface hundreds of files are there. Its hard to find where `include is including xxx file and Self Checking Testbench
how many times the file is given in compilation command.   Verification Flow
OOPS Clock Generator
Randomization Simulation
EXAMPLE: xxx.v file Incremental Compilation
Functional Coverage Store And Restore
Assertion module xxx();  Event Cycle Simulation
Time Scale And Precision
DPI Stimulus Generation
initial 
UVM Tutorial $display(" MODULE ");  System Function Random
A Myth
VMM Tutorial Race Condition
endmodule  
OVM Tutorial Checker
EXAMPLE: yyy.v file Task And Function
Easy Labs : SV
`include "xxx.v"  Process Control
Easy Labs : UVM module yyy()  Disableing The Block
Watchdog
Easy Labs : OVM
endmodule  Compilation N Simulation
Easy Labs : VMM Switchs
AVM Switch TB Debugging
About Code Coverage
VMM Ethernet sample Now compile with any of the comand. Testing Stratigies
File Handling
compile_ur_command xxx.v yyy.v Verilog Semaphore
Verilog compile_ur_command xxx.v yyy.v yyy.v Finding Testsenarious
Handling Testcase Files
Verification
To avoid this problem, Just use compilation switches. In the following example initial Terimination
Verilog Switch TB macros XXX and YYY are not defined. When the compiler comes the xxx.v file first Error Injuction
times, macro XXX is defined. Nedtime when the comes across xxx.v, as already the Register Verification
Basic Constructs
macro XXX is defined, it will neglect the module definition. Parameterised Macros
White Gray Black Box
Regression
OpenVera EXAMPLE: xxx.v file Tips
Constructs `ifndef XXX 
`define XXX  Report a Bug or Comment
Switch TB
module xxx();  on This section - Your
RVM Switch TB input is what keeps
Testbench.in improving
RVM Ethernet sample initial 
$display(" MODULE ");  with time!

endmodule  
Specman E `endif 
Interview Questions
EXAMPLE: yyy.v file
`include "xxx.v" 
`ifndef YYY 
`define YYY 
module yyy() 

endmodule 
`endif 

http://testbench.in/TB_36_TIPS.html[9/26/2012 2:42:03 PM]


WWW.TESTBENCH.IN - Verilog for Verification

Now compile with any of the command.

compile_ur_command xxx.v yyy.v


compile_ur_command xxx.v yyy.v yyy.v

You will not see any compilation error.

Colourful Messages:

Look at the picture. Do you want to make your Linux terminal colorful like this, while
you run your  verilog code?

Copy the following code and simulate in batch mode in Linux. What you can see is
colorful messages from verilog.

CODE:

module colour();

initial
begin
$write("%c[1;34m",27);
$display("*********** This is in blue ***********");
$write("%c[0m",27);

$display("%c[1;31m",27); 
$display("*********** This is in red   ***********");
$display("%c[0m",27);

$display("%c[4;33m",27);
$display("*********** This is in brown ***********"); 
$display("%c[0m",27);

$display("%c[5;34m",27);
$display("*********** This is in green ***********");
$display("%c[0m",27); 

http://testbench.in/TB_36_TIPS.html[9/26/2012 2:42:03 PM]


WWW.TESTBENCH.IN - Verilog for Verification

$display("%c[7;34m",27); 
$display("*********** This is in Back ground color ***********");
$display("%c[0m",27);

end
endmodule

This works only in Linux or Unix terminals. To get required colors, ("%c[1;34m",27);
should be used to print once. Ordinary messages following this messages continue to
be the color specified.

Lets see how to get different colors and font format.


The message to be printed is  ("%c[TYPE;COLOURm",27);.

TYPE specifies how the message should be?

1 set bold
2 set half-bright (simulated with color on a color display)
4 set underscore (simulated with color on a color display)
5 set blink
7 set reverse video

COLOR specifies the message color.

30 set black foreground


31 set red foreground
32 set green foreground
33 set brown foreground
34 set blue foreground
35 set magenta foreground
36 set cyan foreground
37 set white foreground

If you really want to use in your environment, use macros.

`define display_blue  $write("%c[0m",27); $write("%c[1;34m",27); $display
`define display_red   $write("%c[0m",27); $write("%c[1;31m",27); $display
`define display_green $write("%c[0m",27); $write("%c[1;32m",27); $display

Use the macros instead of $display().

EXAMPLE:
module color();

initial
begin
`display_blue(" ******** this is blue ********** ");
`display_red(" ******** this is red ********** ");
`display_green(" ******** this is green ********** ");

end

endmodule

Debugging Macros

Most tools don't support Debugging Macros. The compilation error information is not
enough to find the exactly line where the bug is. In simulation/Compilation steps ,  
the first step is Macro preprocessing. The macro preprocessing step performs textual
substitutions of macros defined with `define statements, textual inclusion with
`include statements, and conditional compilation by `ifdef and `ifndef statements.

EXAMPLE:

`define SUM(A,B) A + B ;

module example();

http://testbench.in/TB_36_TIPS.html[9/26/2012 2:42:03 PM]


WWW.TESTBENCH.IN - Verilog for Verification

integer a,b,c;

initial 
a = SUM(b,c);

endmodule

Run the above example and check where the error is.

The find the exact cause of error, simply use the C pre-processor.

Just use command

cpp file_name.v

NOTE: cpp cannot understand `define. Before using cpp, covert all `define to
#define.

Output of the above code using cpp preprocessor is

RESULTS

# 1 "fine_name.v"
# 1 "<built-in>"
# 1 "<command line>"
# 1 "fine_name.v"

module example();

integer a,b,c;

initial
a = b + c ;;

endmodule

http://testbench.in/TB_36_TIPS.html[9/26/2012 2:42:03 PM]


WWW.TESTBENCH.IN - Verilog for Verification

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/TB_36_TIPS.html[9/26/2012 2:42:03 PM]


WWW.TESTBENCH.IN - Verilog Switch TestBench

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS DUT SPECIFICATION Index


Dut Specification
SystemVerilog This DUT is a simple switch, which can drive the incoming packet to destination ports Rtl
Verification based on the address contained in the packet. Top
Packet
Constructs The dut contain one input interface from which the packet enters the dut. It has four Driver
Interface output interfaces where the packet is driven out. Reciever
Scoreboard
OOPS Env
Randomization
Report a Bug or Comment
Functional Coverage on This section - Your
Assertion input is what keeps
Testbench.in improving
DPI with time!
UVM Tutorial
VMM Tutorial
OVM Tutorial
Easy Labs : SV
Easy Labs : UVM
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

Verilog
Verification
Verilog Switch TB
Basic Constructs

Packet format:
OpenVera Packet contains Header, data and frame check sequence. Packet width is 8 bits and
Constructs the length of the packet can be between 4 bytes to 259 bytes.
Switch TB
Packet header:
RVM Switch TB Packet header contains three fields DA, SA and length.
RVM Ethernet sample DA: Destination address of the packet. It is 8 bits. The switch drives the packet to
respective ports based on this destination address of the packets.
SA: Source address of the packet from where it originate.
Length: This is the length of the data. It can be from 0 to 255.
Specman E
Interview Questions Data: Data should be in terms of bytes. It can be between 0 to 255 bytes.

FCS: This field contains the security check of the packet. It is calculated over the
header and data.

http://testbench.in/VS_01_DUT_SPECIFICATION.html[9/26/2012 2:42:12 PM]


WWW.TESTBENCH.IN - Verilog Switch TestBench

Configuration:

Dut has four output ports. These output ports have to be configure to a address. Dut
matches the DA field of the packet with this configured port address and sends the
packet on to that port. To configure the dut, a memory interface is provided. The
address of the ports should be unique. It is 8 bits wide. Memory address (0,1,2,3)
contains the address of port(0,1,2,4) respectively.

Interface Specification:

The dut has one input Interface, from where the packet enters the dut and 4 output
interfaces from where the packet comes out and one memory interface, through the
port address can be configured.

Memory Interface:

Through memory interfaced output port address are configured. It accepts 8 bit data
to be written to memory. It has 8 bit address inputs. Address 0,1,2,3 contains the
address of the port 0,1,2,3 respectively. If the DA feild in the packet matches with
the confugured address of any port ,then the packet comes out of that  port.

Input Interface:

The status signal has to be high when data is when packet is sent on to the dut it has
to become low after sending last byte of the packet.
When the dut is busy, and if it is not in a position to accept any more data, it will
assert busy signal. Data which is sent during this busy signal is lost if input is driving
when busy is high

Output Interface:

There are 4 ports, each having data, ready and read signals.

When the data is ready to be sent out from the port, dut makes the ready signal high
indicating that data is ready to be sent.
If the read signal is made high when ready is high, then the data comes out of the
data signal.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/VS_01_DUT_SPECIFICATION.html[9/26/2012 2:42:12 PM]


WWW.TESTBENCH.IN - Verilog Switch TestBench

http://testbench.in/VS_01_DUT_SPECIFICATION.html[9/26/2012 2:42:12 PM]


WWW.TESTBENCH.IN - Verilog Switch TestBench

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS RTL Index


Dut Specification
SystemVerilog CODE: switch.v Rtl
Verification module fifo (clk, Top
             reset, Packet
Constructs              write_enb, Driver
Interface              read, Reciever
             data_in, Scoreboard
OOPS Env
             data_out,
Randomization              empty,
             full); Report a Bug or Comment
Functional Coverage on This section - Your
input     clk;
Assertion input     reset; input is what keeps
input write_enb; Testbench.in improving
DPI with time!
input read;
UVM Tutorial input  [7:0] data_in;
VMM Tutorial output [7:0] data_out;
output empty;
OVM Tutorial output full;
Easy Labs : SV wire     clk;
wire write_enb;
Easy Labs : UVM wire read;
Easy Labs : OVM wire   [7:0] data_in;
reg    [7:0] data_out;
Easy Labs : VMM wire empty;
AVM Switch TB wire full;
reg      [7:0] ram[0:25];
VMM Ethernet sample reg            tmp_empty;
reg            tmp_full;
integer        write_ptr;
Verilog integer        read_ptr;
Verification    always@(negedge reset)
   begin
Verilog Switch TB       data_out  = 8'b0000_0000;
Basic Constructs       tmp_empty = 1'b1;
      tmp_full  = 1'b0;
      write_ptr = 0;
      read_ptr  = 0;
OpenVera    end
Constructs
Switch TB    assign empty = tmp_empty;
   assign full  = tmp_full;
RVM Switch TB  always @(posedge clk) begin 
RVM Ethernet sample       if ((write_enb == 1'b1) &&  (tmp_full == 1'b0)) begin
         ram[write_ptr] = data_in;
         tmp_empty <= 1'b0;
         write_ptr = (write_ptr + 1) % 16;
Specman E          if ( read_ptr == write_ptr ) begin
Interview Questions             tmp_full <= 1'b1;
         end 
      end 

 if ((read == 1'b1) &&  (tmp_empty == 1'b0)) begin


         data_out <= ram[read_ptr];
         tmp_full <= 1'b0;
         read_ptr = (read_ptr + 1) % 16;
         if ( read_ptr == write_ptr ) begin
            tmp_empty <= 1'b1;
         end 

http://testbench.in/VS_02_RTL.html[9/26/2012 2:42:22 PM]


WWW.TESTBENCH.IN - Verilog Switch TestBench

      end 
   end  
endmodule //fifo

module port_fsm (clk,
                 reset,
                 write_enb,
                 ffee,
                 hold,
                 data_status,
                 data_in,
                 data_out,
                 mem0,
                 mem1,
                 mem2,
                 mem3,
                 addr);
input      clk;
input      reset;
input   [7:0]   mem0;
input   [7:0]   mem1;
input   [7:0]   mem2;
input   [7:0]   mem3;
output[3:0]  write_enb;
input  ffee;
input      hold;
input      data_status;
input[7:0]  data_in;
output[7:0]  data_out;
output  [7:0]     addr;
reg [7:0]  data_out;
reg [7:0]  addr;
reg    [3:0] write_enb_r;
reg          fsm_write_enb;
reg    [3:0] state_r;
reg    [3:0] state;
reg    [7:0] parity;
reg    [7:0] parity_delayed;
reg          sus_data_in,error;

parameter ADDR_WAIT   = 4'b0000;
parameter DATA_LOAD   = 4'b0001;
parameter PARITY_LOAD = 4'b0010;
parameter HOLD_STATE  = 4'b0011;
parameter BUSY_STATE  = 4'b0100;

  always@(negedge reset)
  begin
       error            = 1'b0;
       data_out       = 8'b0000_0000;
       addr           = 8'b00000000;
       write_enb_r    = 3'b000;
       fsm_write_enb  = 1'b0;
       state_r        = 4'b0000;
       state          = 4'b0000;
       parity         = 8'b0000_0000;
       parity_delayed = 8'b0000_0000;
       sus_data_in    = 1'b0;
  end
  assign busy = sus_data_in;
  always @(data_status) begin : addr_mux
    if (data_status == 1'b1) begin
      case (data_in)
      mem0 :  begin
            write_enb_r[0] = 1'b1;
            write_enb_r[1] = 1'b0;
            write_enb_r[2] = 1'b0;
            write_enb_r[3] = 1'b0;
      end

http://testbench.in/VS_02_RTL.html[9/26/2012 2:42:22 PM]


WWW.TESTBENCH.IN - Verilog Switch TestBench

      mem1 :  begin
        write_enb_r[0] = 1'b0;
        write_enb_r[1] = 1'b1;
        write_enb_r[2] = 1'b0;
        write_enb_r[3] = 1'b0;
       end
      mem2 :  begin
        write_enb_r[0] = 1'b0;
        write_enb_r[1] = 1'b0;
        write_enb_r[2] = 1'b1;
        write_enb_r[3] = 1'b0;
      end
      
      mem3 :  begin
        write_enb_r[0] = 1'b0;
        write_enb_r[1] = 1'b0;
        write_enb_r[2] = 1'b0;
        write_enb_r[3] = 1'b1;
     end
     default :write_enb_r = 3'b000;
    endcase
  //  $display(" data_inii %d ,mem0 %d ,mem1 %d ,mem2 %d
mem3",data_in,mem0,mem1,mem2,mem3);
     end //if
end //addr_mux;
 always @(posedge clk) begin : fsm_state
     state_r <= state;
  end //fsm_state;

  always @(state_r or data_status or ffee or hold or data_in)


  begin : fsm_core
  state = state_r;   //Default state assignment
      case (state_r)
        ADDR_WAIT :   begin
                  if ((data_status == 1'b1) &&
                      ((mem0 == data_in)||(mem1 == data_in)||(mem3 == data_in) ||(mem2
== data_in))) begin
                     if (ffee == 1'b1) begin
                       state = DATA_LOAD;
                     end
                     else begin
                       state = BUSY_STATE;
                     end //if
                   end //if;
                  sus_data_in = !ffee;
                  if ((data_status == 1'b1) &&
                      ((mem0 == data_in)||(mem1 == data_in)||(mem3 == data_in) ||(mem2
== data_in)) &&
                      (ffee == 1'b1)) begin
                          addr = data_in;
                          data_out  = data_in;
                          fsm_write_enb = 1'b1;
                        
                  end
                  else begin
                      fsm_write_enb = 1'b0;
                  end //if
                end // of case ADDR_WAIT
         PARITY_LOAD : begin
                  state = ADDR_WAIT;
                  data_out = data_in;
                  fsm_write_enb = 1'b0;
                end // of case PARITY_LOAD
         DATA_LOAD :   begin
              if ((data_status == 1'b1) &&
               (hold == 1'b0)) begin
                  state = DATA_LOAD;
              end
              else if ((data_status == 1'b0) &&
              (hold == 1'b0)) begin
                  state = PARITY_LOAD;
              end
              else begin
                  state = HOLD_STATE;

http://testbench.in/VS_02_RTL.html[9/26/2012 2:42:22 PM]


WWW.TESTBENCH.IN - Verilog Switch TestBench

              end  //if
             sus_data_in = 1'b0;
             if ((data_status == 1'b1) &&
               (hold == 1'b0)) begin
                  data_out = data_in;
                  fsm_write_enb = 1'b1;
             end
             else if ((data_status == 1'b0) &&
              (hold == 1'b0)) begin
                  data_out = data_in;
                  fsm_write_enb = 1'b1;
             end
             else begin
             fsm_write_enb = 1'b0;
             end //if
        end  //end of case DATA_LOAD
       HOLD_STATE :  begin
             if (hold == 1'b1) begin
                  state = HOLD_STATE;
             end
             else if ((hold == 1'b0) && (data_status == 1'b0)) begin
                  state = PARITY_LOAD;
             end
             else begin
                  state = DATA_LOAD;
             end //if
             if (hold == 1'b1) begin
                   sus_data_in = 1'b1;
                   fsm_write_enb = 1'b0;
             end
             else begin
                   fsm_write_enb = 1'b1;
                   data_out = data_in;
             end //if
         end  //end of case HOLD_STATE
            BUSY_STATE :  begin
             if (ffee == 1'b0) begin
                   state = BUSY_STATE;
             end
             else begin
                   state = DATA_LOAD;
             end //if
             if (ffee == 1'b0) begin
                   sus_data_in = 1'b1;
             end
             else begin
                   addr = data_in; // hans
                   data_out  = data_in;
                   fsm_write_enb = 1'b1;
             end //if
         end  //end of case BUSY_STATE
   endcase
  end //fsm_core

  assign write_enb[0] = write_enb_r[0] & fsm_write_enb;
  assign write_enb[1] = write_enb_r[1] & fsm_write_enb;
  assign write_enb[2] = write_enb_r[2] & fsm_write_enb;
  assign write_enb[3] = write_enb_r[3] & fsm_write_enb;

endmodule //port_fsm
module switch (clk,
               reset,
               data_status,
               data,
               port0,
               port1,
               port2,
               port3,
               ready_0,
               ready_1,
               ready_2,
               ready_3,
               read_0,
               read_1,

http://testbench.in/VS_02_RTL.html[9/26/2012 2:42:22 PM]


WWW.TESTBENCH.IN - Verilog Switch TestBench

               read_2,
               read_3,
               mem_en,
               mem_rd_wr,
               mem_add,
               mem_data);
input          clk;
input          reset;
input          data_status;
input    [7:0] data;
input mem_en;
input mem_rd_wr;
input [1:0] mem_add;
input  [7:0] mem_data;
output   [7:0] port0;
output   [7:0] port1;
output   [7:0] port2;
output   [7:0] port3;
output         ready_0;
output       ready_1;
output       ready_2;
output       ready_3;
input       read_0;
input       read_1;
input       read_2;
input       read_3;
wire   [7:0] data_out_0;
wire   [7:0] data_out_1;
wire   [7:0] data_out_2;
wire   [7:0] data_out_3;
wire ll0;
wire ll1;
wire ll2;
wire ll3;
wire empty_0;
wire empty_1;
wire empty_2;
wire empty_3;
wire ffee;
wire ffee0;
wire ffee1;
wire ffee2;
wire ffee3;
wire ld0;
wire ld1;
wire ld2;
wire ld3;
wire hold;
wire   [3:0] write_enb;
wire   [7:0] data_out_fsm;
wire   [7:0] addr;

reg  [7:0]mem[3:0];
wire reset;
  fifo queue_0 (.clk     (clk),
                .reset     (reset),
                .write_enb (write_enb[0]),
                .read  (read_0),
                .data_in   (data_out_fsm),
                .data_out  (data_out_0),
                .empty     (empty_0),
                .full      (ll0));

  fifo queue_1 (.clk     (clk),


                .reset     (reset),
                .write_enb (write_enb[1]),
                .read  (read_1),
                .data_in   (data_out_fsm),
                .data_out  (data_out_1),
                .empty     (empty_1),
                .full      (ll1));

  fifo queue_2 (.clk     (clk),


                .reset     (reset),

http://testbench.in/VS_02_RTL.html[9/26/2012 2:42:22 PM]


WWW.TESTBENCH.IN - Verilog Switch TestBench

                .write_enb (write_enb[2]),
                .read  (read_2),
                .data_in   (data_out_fsm),
                .data_out  (data_out_2),
                .empty     (empty_2),
                .full      (ll2));

 fifo queue_3 (.clk     (clk),


                .reset     (reset),
                .write_enb (write_enb[3]),
                .read  (read_3),
                .data_in   (data_out_fsm),
                .data_out  (data_out_3),
                .empty     (empty_3),
                .full      (ll3));

  port_fsm in_port (.clk           (clk),


                    .reset           (reset),
                    .write_enb       (write_enb),
                    .ffee      (ffee),
                    .hold            (hold),
                    .data_status    (data_status),
                    .data_in         (data),
                    .data_out        (data_out_fsm),
                    .mem0            (mem[0]),
                    .mem1            (mem[1]),
                    .mem2            (mem[2]),
                    .mem3            (mem[3]),
                    .addr            (addr));
  assign port0 = data_out_0;   //make note assignment only for
                                  //consistency with vlog env
  assign port1 = data_out_1;
  assign port2 = data_out_2;
  assign port3 = data_out_3;
  
  assign ready_0 = ~empty_0;
  assign ready_1 = ~empty_1;
  assign ready_2 = ~empty_2;
  assign ready_3 = ~empty_3;

  assign ffee0 = (empty_0 | ( addr != mem[0])); 


  assign ffee1 = (empty_1 | ( addr != mem[1])); 
  assign ffee2 = (empty_2 | ( addr != mem[2])); 
  assign ffee3 = (empty_3 | ( addr != mem[3])); 

  assign ffee  = ffee0 & ffee1 & ffee2 & ffee3;

  assign ld0 = (ll0 & (addr == mem[0])); 


  assign ld1 = (ll1 & (addr == mem[1])); 
  assign ld2 = (ll2 & (addr == mem[2])); 
  assign ld3 = (ll3 & (addr == mem[3])); 

  assign hold   = ld0 | ld1 | ld2 | ld3;

always@(posedge clk)
begin

if(mem_en)
if(mem_rd_wr)
begin
mem[mem_add]=mem_data;
///$display("%d  %d %d %d %d",mem_add,mem[0],mem[1],mem[2],mem[3]);
end
end
endmodule //router

http://testbench.in/VS_02_RTL.html[9/26/2012 2:42:22 PM]


WWW.TESTBENCH.IN - Verilog Switch TestBench

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/VS_02_RTL.html[9/26/2012 2:42:22 PM]


WWW.TESTBENCH.IN - Verilog Switch TestBench

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS TOP Index


Dut Specification
SystemVerilog Verification Environment: Rtl
Verification Top
This is simple verification environment. Packet
Constructs It has top,tb,packet,Driver, Scoreboard and Receiver components. Driver
Interface Reciever
Scoreboard
OOPS Env
Randomization
Report a Bug or Comment
Functional Coverage on This section - Your
Assertion input is what keeps
Testbench.in improving
DPI with time!
UVM Tutorial
VMM Tutorial
OVM Tutorial
Easy Labs : SV
Easy Labs : UVM
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

Verilog
Verification
Verilog Switch TB Top Module:
Basic Constructs Top module contains the instance of the Dut and verification environment.
It also has the clock generator. For more information about clock generation, go
through TB_CONCEPTS in this website. Do reset and Confgure the dut port address.
OpenVera
Constructs CODE: top
module top();
Switch TB   reg          clock;
RVM Switch TB  wire          packet_valid;
wire [7:0]    data;
RVM Ethernet sample wire [7:0]    data_0;
wire [7:0]    data_1;
wire [7:0]    data_2;
Specman E wire [7:0]    data_3;
wire          ready_0;
Interview Questions wire          ready_1;
wire          ready_2;
wire          ready_3;
wire          read_0;
wire          read_1;
wire          read_2;
wire          read_3;
 
  reg reset;
  reg mem_en;
  reg mem_rd_wr;

http://testbench.in/VS_03_TOP.html[9/26/2012 2:42:32 PM]


WWW.TESTBENCH.IN - Verilog Switch TestBench

  reg [7:0] mem_data;
  reg [1:0] mem_add;
  reg [7:0] mem[3:0];

// take istance of testbench


sw_tb    tb  (clock, 
               packet_valid,
                data,
               data_0,
               data_1,
               data_2,
               data_3,
               ready_0,
               ready_1,
               ready_2,
               ready_3,
               read_0,
               read_1,
               read_2,
               read_3);

// take instance dut


switch dut (clock,
               reset,
               packet_valid,
               data,
               data_0,
               data_1,
               data_2,
               data_3,
               ready_0,
               ready_1,
               ready_2,
               ready_3,
               read_0,
               read_1,
               read_2,
               read_3,
               mem_en,
               mem_rd_wr,
               mem_add,
               mem_data);

//Clock generator
 initial 
 clock = 0;
always
  begin
   #5 clock = !clock;
   end

// Do reset and configure the dut port address


 initial begin
$dumpon;
      mem[0]=$random;
      mem[1]=$random;
      mem[2]=$random;
      mem[3]=$random;
    mem_en = 0;
    @(posedge clock);
    #2 reset = 1;
    @(posedge clock);
    #2 reset =0;
    mem_en = 1;
    @(negedge clock);
    mem_rd_wr = 1;
    mem_add = 0;

http://testbench.in/VS_03_TOP.html[9/26/2012 2:42:32 PM]


WWW.TESTBENCH.IN - Verilog Switch TestBench

    mem_data = mem[0];
@(negedge clock);
    mem_rd_wr = 1;
    mem_add = 1;
    mem_data = mem[1];
@(negedge clock);
    mem_rd_wr = 1;
    mem_add = 2;
    mem_data = mem[2];
@(negedge clock);
    mem_rd_wr = 1;
    mem_add = 3;
    mem_data = mem[3];
@(negedge clock);
    mem_en=0;
    mem_rd_wr = 0;
    mem_add = 0;
    mem_data = 0;
   end

 
endmodule //top

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/VS_03_TOP.html[9/26/2012 2:42:32 PM]


WWW.TESTBENCH.IN - Verilog Switch TestBench

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PACKET Index


Dut Specification
SystemVerilog Packet is a class with all the fields in the packet randomly. Rtl
Verification Types of possible packets : Top
Packet with DA with one of the configured port address.. Packet
Constructs Packets with DA which has unconfigured address. Driver
Interface Packets with valid and invalid length. Reciever
Packets with good and bad FCS. Scoreboard
OOPS Env
Payload size types: SMALL, MEDIUM and LARGE
Randomization
Define a task which can generate the above feilds randomly. Defind a task which does Report a Bug or Comment
Functional Coverage on This section - Your
packing.
Assertion Creat a parity function and call it in packing. input is what keeps
Testbench.in improving
DPI with time!
CODE: packet.v
UVM Tutorial //Define the enumerated types for packet payload size type
VMM Tutorial `define SMALL 0 
`define MEDIUM 1
OVM Tutorial `define LARGE 2
Easy Labs : SV `define GOOD 0
`define BAD 1
Easy Labs : UVM
Easy Labs : OVM
module pktgen();
Easy Labs : VMM integer payload_size;//Control field for the payload size
AVM Switch TB integer parity_type;// Control feild for the parity type.
reg [0:7] uid;    // Unique id field to identify the packet    
VMM Ethernet sample           
reg [7:0] len;
reg [7:0] Da;
Verilog reg [7:0] Sa;
Verification reg [0:7] pkt [0:64];//Size = MAX pkt size
reg [0:7] parity;
Verilog Switch TB
Basic Constructs initial
uid = 0;

task randomize();
OpenVera begin
Constructs uid = uid +1;
Switch TB parity_type= {$random}%2;// 0 and 1 are selected randomly
payload_size={$random}%3;// 0,1,2 are selected randomly
RVM Switch TB Da = top.mem[({$random}%3)];//{$random}%3;// 0,1,2,3 are selected randomly
RVM Ethernet sample Sa = $random;
if(payload_size== `SMALL)
len = {$random}%10;
else if(payload_size== `MEDIUM)
Specman E len = 10+{$random}%10;
Interview Questions else if(payload_size==`LARGE)
len = 20+{$random()}%10;
else len = {$random()}%10;
 if(parity_type==0)
parity=8'b0;
else
parity=8'b1;
end
endtask

http://testbench.in/VS_04_PACKET.html[9/26/2012 2:42:42 PM]


WWW.TESTBENCH.IN - Verilog Switch TestBench

task packing();
integer i;
begin
 pkt[0]=Da;
pkt[1]=Sa;
 pkt[2]=len;
$display("[PACKING] pkt[0] is Da %b %d Sa %b %d len %b %d
",pkt[0],Da,Sa,Sa,len,len);
for (i = 0;i<len+3;i=i+1)
pkt[i+3]=$random();
pkt[3] = uid;
pkt[i+3]=parity ^ parity_cal(0);
end
endtask

// parity_calc()
//
// Return the byte resulting from xor-ing among all data bytes
// and the byte resulting from concatenating addr and len
//////////////////////////////////////////////////////////////
function [0:7] parity_cal(input dummy);
integer i;
reg [0:7] result ;
begin
result = 8'hff;
for (i = 0;i<len+4;i=i+1)
begin
result = result ^ pkt[i];
end
parity_cal=result;
end
endfunction

endmodule 

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/VS_04_PACKET.html[9/26/2012 2:42:42 PM]


WWW.TESTBENCH.IN - Verilog Switch TestBench

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS DRIVER Index


Dut Specification
SystemVerilog Take an instance of packet Rtl
Verification Define task to generate the packet and call the drive task. Top
This task first, calls randomize task in the packet then calls the pack to packing the Packet
Constructs packet. Driver
Interface Calls the drive packet wich drives the packet to dut. Then add the sent packet to Reciever
score board. Scoreboard
OOPS Env
Randomization CODE:driver.v
Report a Bug or Comment
Functional Coverage on This section - Your
module driver(clock,packet_valid,data,busy); 
Assertion output          packet_valid; input is what keeps
output    [7:0] data; Testbench.in improving
DPI with time!
input         busy;
UVM Tutorial input clock;
VMM Tutorial reg  packet_valid;
reg  [7:0] data;
OVM Tutorial
Easy Labs : SV integer delay;
// Take an instance of packet
Easy Labs : UVM pktgen gen();
Easy Labs : OVM //Define task to generate the packet and call the drive task
task gen_and_drive(input integer no_of_pkts);
Easy Labs : VMM integer i;
AVM Switch TB begin
VMM Ethernet sample  for(i=0;i<no_of_pkts;i=i+1)
       begin
         delay={$random()}%4;
Verilog $display("DRIVER gen and drive pkt_no = %d delay %d",i,delay);
Verification           repeat (delay)@(negedge clock);
// randomize the packet
Verilog Switch TB          gen.randomize();
Basic Constructs //pack the packet
         gen.packing();
// call the drive packet task.
         @(negedge clock);
OpenVera          drive_packet();
Constructs // add the sent packet to score board
Switch TB          top.tb.sb.add_pkt(i);
RVM Switch TB        end
RVM Ethernet sample end 
endtask

Specman E
Interview Questions task    drive_packet() ;
integer i;
begin
$display("DRIVER Starting to drive packet to port %0d len %0d ",gen.Da,gen.len);
repeat(4)@(negedge clock);
for (i=0;i<gen.len+4;i=i+1)
begin
@ (negedge clock);

packet_valid = 1 ;
data[7:0] = gen.pkt[i];

http://testbench.in/VS_05_DRIVER.html[9/26/2012 2:42:51 PM]


WWW.TESTBENCH.IN - Verilog Switch TestBench

$display("[DRIVER] data %b at i %d",gen.pkt[i],i);

end
@ (negedge clock);
packet_valid = 0 ;
@(negedge clock);
end
endtask

endmodule

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/VS_05_DRIVER.html[9/26/2012 2:42:51 PM]


WWW.TESTBENCH.IN - Verilog Switch TestBench

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS RECIEVER Index


Dut Specification
SystemVerilog Rtl
Verification Build a receiver which can collect a packet on single port. Top
Define a task to unpack the recived packet. Packet
Constructs Define a task to check whether the received packet and sent packet are same are not. Driver
Interface In the initial block Start collecting packet. Reciever
Do unpacking,Call the checker task Scoreboard
OOPS
Checker Checks whether the packet is coming on the proper port or not, then checker Env
Randomization gets the packet from scoreboard and comares the recived packet with the sent
packet. If any error is there then error is asserted. Report a Bug or Comment
Functional Coverage on This section - Your
 
Assertion input is what keeps
CODE:receiver.v Testbench.in improving
DPI with time!
module receiver(clk,data, ready, read, port);
UVM Tutorial input ready;
VMM Tutorial
input clk;
OVM Tutorial input [7:0]data;
Easy Labs : SV input port;
output read;
Easy Labs : UVM reg read;
Easy Labs : OVM reg [0:7] mem [0:65];
wire [31:0] port;
Easy Labs : VMM integer j,delay;
AVM Switch TB
reg[7:0] rec_address;
VMM Ethernet sample
// Start collecting packet
initial
Verilog begin
Verification while(1)
begin
Verilog Switch TB     
Basic Constructs         begin
        @(posedge ready)
        delay= {$random()}%5+1;
        repeat(delay)@(negedge clk);
OpenVera
Constructs         j=0;
Switch TB         @(negedge clk);
        read=1'b1;
RVM Switch TB         while(ready==1'b1)
RVM Ethernet sample         begin
                @(negedge clk);
                mem[j]=data;
                j=j+1;
Specman E         $display(" RECV BYTE at PORT[%d] %b",port,data);
Interview Questions
        end//while
        read=1'b0;
        end
// Do unpacking
unpacking();
// Call the checker task
checker((j-1));
end
end
// Do unpack of the packet recived.

http://testbench.in/VS_06_RECIEVER.html[9/26/2012 2:42:59 PM]


WWW.TESTBENCH.IN - Verilog Switch TestBench

task unpacking;
reg [7:0]rec_parity;
reg [7:0]rec_paclen;
reg [7:0]separate;
reg [7:0]rec_data[0:63];
begin
rec_paclen=mem[2];
rec_parity=mem[rec_paclen+3];
rec_address=mem[0];
$display("rec_parity=%b rec_paclen=%0d %b, rec_address=%b header
%b",rec_parity,rec_paclen, rec_paclen, rec_address,mem[0]);
end
endtask

task checker(input integer size);
integer i;
begin
$display("[CHECKER] Checker started for pkt_no %d ",top.tb.sb.pkt_no );
if(rec_address!=top.mem[port])
begin
->top.tb.error;
// Check whether the packet is coming on the proper port or not
$display("[CHECKER] ERROR PKT RECIVED ON PORT %d,PKT ADDRESS is
%d",top.mem[port],rec_address);
end
for(i=0;i<size;i=i+1)
// get the packet from score board and comare the recived packet with the sent
packet.
if(top.tb.sb.sent_pkt[i][top.tb.sb.pkt_no]!== mem[i])
begin
$display("[CHECKER] ERROR at %d pkt no %d ",i,top.tb.sb.pkt_no);
$display("[CHECKER] at %d sentbyte %b rcevbyte
%b",i,top.tb.sb.sent_pkt[i][top.tb.sb.pkt_no], mem[i]);
->top.tb.error;
end
else
begin
$display("[CHECKER] at %d sentbyte %b rcevbyte
%b",i,top.tb.sb.sent_pkt[i][top.tb.sb.pkt_no], mem[i]);
end

top.tb.sb.pkt_no=top.tb.sb.pkt_no+1;

end
endtask

endmodule

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/VS_06_RECIEVER.html[9/26/2012 2:42:59 PM]


WWW.TESTBENCH.IN - Verilog Switch TestBench

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS SCOREBOARD Index


Dut Specification
SystemVerilog Rtl
Verification The expected packets are stored in scored board by driver. Top
Declare a memory to store sent packets Packet
Constructs task to add packets to scoreboard Driver
Interface Reciever
Scoreboard
OOPS Env
CODE: scoreboard.v
Randomization module scoreboard();
// Declare a memory to store sent packets Report a Bug or Comment
Functional Coverage on This section - Your
reg [0:7]sent_pkt [0:64][0:10];
Assertion input is what keeps
integer pkt_no; Testbench.in improving
DPI with time!
initial
UVM Tutorial pkt_no=0;
VMM Tutorial
// task to add packets to scoreboard
OVM Tutorial task add_pkt(input integer pkt_no);
Easy Labs : SV integer i;
begin
Easy Labs : UVM for(i=0;i<65;i=i+1)
Easy Labs : OVM sent_pkt[i][pkt_no]=top.tb.dv.gen.pkt[i];
end
Easy Labs : VMM endtask
AVM Switch TB
endmodule 
VMM Ethernet sample

Verilog
Verification
Verilog Switch TB
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/VS_07_SCOREBOARD.html[9/26/2012 2:43:08 PM]


WWW.TESTBENCH.IN - Verilog Switch TestBench

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/VS_07_SCOREBOARD.html[9/26/2012 2:43:08 PM]


WWW.TESTBENCH.IN - Verilog Switch TestBench

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS ENV Index


Dut Specification
SystemVerilog Env is a module which contains all the components of verification. A logic to Rtl
Verification increment the error counter. Top
Take a Driver instance and creat four reciever instancess. connect it to specific port. Packet
Constructs Creat instance of scoreboard Driver
Interface Call then packet gen and drive task in driver Reciever
Creat a finish task which display the tesults of the test. Scoreboard
OOPS Env
Randomization CODE:env.v
Report a Bug or Comment
Functional Coverage on This section - Your
module sw_tb(clock,
Assertion                   packet_valid, input is what keeps
                  data         , Testbench.in improving
DPI with time!
                  data_0     ,
UVM Tutorial                   data_1     ,
VMM Tutorial                   data_2     ,
                  data_3     ,
OVM Tutorial                   ready_0   ,
Easy Labs : SV                   ready_1   ,
                  ready_2   ,
Easy Labs : UVM                   ready_3   ,
Easy Labs : OVM                   read_0   ,
                  read_1   ,
Easy Labs : VMM                   read_2  ,
AVM Switch TB                   read_3  
                     );
VMM Ethernet sample input          clock;
output          packet_valid;
output    [7:0] data;
Verilog input   [7:0] data_0;
Verification input   [7:0] data_1;
input   [7:0] data_2;
Verilog Switch TB input   [7:0] data_3;
Basic Constructs input         ready_0;
input       ready_1;
input       ready_2;
input       ready_3;
OpenVera output       read_0;
Constructs output       read_1;
Switch TB output       read_2;
output       read_3;
RVM Switch TB reg pkt_status;
RVM Ethernet sample integer error_count=0;
event error;

//Incriment the error counter on error.


Specman E always@(error)
Interview Questions begin
#0 error_count=error_count+1;
$display(" ERROR RECIVED");
end

// Driver instance
driver dv(clock,packet_valid,data,busy);

// Make four reciever instancess. connect it to specific port.


receiver rec0(.clk(clock),.data(data_0), .ready(ready_0),          
                .read(read_0),  

http://testbench.in/VS_08_ENV.html[9/26/2012 2:43:16 PM]


WWW.TESTBENCH.IN - Verilog Switch TestBench

                .port(0)
);
receiver rec1(.clk(clock),.data(data_1), .ready(ready_1),
                .read(read_1),
                .port(1)
);
receiver rec2(.clk(clock),.data(data_2), .ready(ready_2),
                .read(read_2),
                .port(2)
);
receiver rec3(.clk(clock),.data(data_3), .ready(ready_3),
                .read(read_3),
                .port(3)
);

// Creat instance of scoreboard


scoreboard sb();

// Call then packet gen and drive task in driver


initial
begin
#100;
dv.gen_and_drive(9);
#1000;
finish;
end

// finish task which display the tesults of the test.


task finish();
begin
if(error_count!=0)
$display("############# TEST FAILED ###############");
else
$display("############# TEST PASSED ###############");

$finish;
end
endtask

endmodule

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/VS_08_ENV.html[9/26/2012 2:43:16 PM]


WWW.TESTBENCH.IN - Verilog Basic Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INTRODUCTION Index


Introduction
SystemVerilog Syntax
Verification This tutorial is aimed at the beginner. For Advanced Verilog for Verification topics , Data Types
refer to Advanced Verilog for Verification   Operators
Constructs Assignments
Interface Control Constructs
Introduction Procedural Timing
OOPS Controls
Randomization The Verilog® Hardware Description Language (Verilog HDL) became an IEEE standard Structure
in 1995 as IEEE Std 1364-1995. Verilog HDL is a formal notation intended for use in all Block Statements
Functional Coverage Structured Procedures
phases of the creation of electronic systems. Because it is both machine readable and
Assertion human readable, it supports the development, verification, synthesis, and testing of
DPI hardware designs; the communication of hardware design data; and the maintenance, Report a Bug or Comment
modification, and procurement of hardware. on This section - Your
UVM Tutorial input is what keeps
Testbench.in improving
VMM Tutorial
Verilog contains a rich set of built-in primitives, including logic gates, user-definable with time!
OVM Tutorial primitives, switches,
Easy Labs : SV and wired logic. It also has device pin-to-pin delays and timing checks.
Easy Labs : UVM
Easy Labs : OVM The Verilog language is extensible via the Programming Language Interface (PLI) and
the Verilog Procedural
Easy Labs : VMM Interface (VPI) routines.
AVM Switch TB
VMM Ethernet sample

Verilog
Verification
Verilog Switch TB
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/VT_01_INTRODUCTION.html[9/26/2012 2:43:24 PM]


WWW.TESTBENCH.IN - Verilog Basic Constructs

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/VT_01_INTRODUCTION.html[9/26/2012 2:43:24 PM]


WWW.TESTBENCH.IN - Verilog Basic Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS SYNTAX Index


Introduction
SystemVerilog Syntax
Verification Data Types
Comments : Verilog comments are the same as in C++. Use // for a single line Operators
Constructs comment or /*  */ for a multiline comment. Assignments
Interface Control Constructs
Punctuation : white spaces are ignored in Verilog. A semicolon is used to indicate the Procedural Timing
OOPS Controls
end of a command line and commas are typically used to separate elements in a list.
Randomization Like C++, Verilog is case sensitive. Structure
Block Statements
Functional Coverage Structured Procedures
Identifiers : An identifier is usually a variable. You can use any letter, digit, the
Assertion underscore, or $. Identifiers may not begin with a digit and may not be the same as a
DPI Verilog key word. As in C++ variable names should be chosen to assist in Report a Bug or Comment
documentation. on This section - Your
UVM Tutorial input is what keeps
VMM Tutorial Signal values : signals in Verilog have one of four values. These are 0 (logic 0), 1 (logic Testbench.in improving
1), ?, X, or x ( don<92>t care or unknown), and Z or z for high impedance tri-state. with time!
OVM Tutorial
Easy Labs : SV Parameters : a parameter in Verilog can be any Verilog constant. Parameters are used
to generalize a design. For example a 4-bit adder becomes more useful as a design if
Easy Labs : UVM it is put together as an n-bit adder where n is a parameter specified by the user
Easy Labs : OVM before compilation. Parameter declarations are done immediately after the module
declaration. Here are some typical parameter examples:
Easy Labs : VMM
AVM Switch TB EXAMPLE:
parameter n = 12;
VMM Ethernet sample parameter [3:0]p1 = 4'b1011;
parameter n = 12, m = 32;

Verilog Memory : Verilog allows for two dimensional arrays which typically get used for
Verification memory spaces. For example reg[7:0] m[63:0]; declares m to be a two-dimensional
array consisting of 64 eight-bit words. You can access any word as m[2] for example
Verilog Switch TB but you do not get access to the bits in the word unless you copy the word to another
Basic Constructs 8-bit reg variable.

Strings : Strings are delimited by " ... ", and cannot be on multiple lines.
OpenVera         "hello world";   // legal string
Constructs
Switch TB Number  :  Numbers in verilog are in the following format.
The size is always specified as a decimal number. If no is specified then the default
RVM Switch TB size is at least 32bits and may be larger depending on the machine. Valid base formats
RVM Ethernet sample are 'b , 'B , 'h , 'H 'd , 'D , 'o , 'O for binary, hexadecimal, decimal, and octal. Numbers
consist of strings of digits (0-9, A-F, a-f, x, X, z, Z). The X's mean unknown, and the
Z's mean high impedance If no base format is specified the number is assumed to be a
decimal number. Some examples of valid numbers are:
Specman E
Interview Questions
EXAMPLE: Unsized constant numbers
659 // is a decimal number
'h 837FF // is a hexadecimal number
'o7460 // is an octal number
4af // is illegal (hexadecimal format requires <92>h)

EXAMPLE: Sized constant numbers


4'b1001 // is a 4-bit binary number
5'D 3 // is a 5-bit decimal number

http://testbench.in/VT_02_SYNTAX.html[9/26/2012 2:43:34 PM]


WWW.TESTBENCH.IN - Verilog Basic Constructs

3'b01x // is a 3-bit number with the least


// significant bit unknown
12'hx // is a 12-bit unknown number
16'hz // is a 16-bit high-impedance number

EXAMPLE: Using sign with constant numbers

8'd -6 // this is illegal syntax


-8'd 6 // this defines the two<92>s complement of 6,
// held in 8 bits<97>equivalent to -(8<92>d 6)
4'hf // this denotes the 4-bit number <91>1111<92>, to
// be interpreted as a 2<92>s complement number,
// or <91>-1<92>. This is equivalent to -4<92>h 1
-4'sd15 // this is equivalent to -(-4<92>d 1), or <91>0001<92>.

EXAMPLE: Automatic left padding

reg [11:0] a, b, c, d;
initial begin
a = 'h x; // yields xxx
b = 'h 3x; // yields 03x
c = 'h z3; // yields zz3
d = 'h 0z3; // yields 0z3
end
reg [84:0] e, f, g;
e = 'h5; // yields {82{1'b0},3'b101}
f = 'hx; // yields {85{1'hx}}
g = 'hz; // yields {85{1'hz}}

EXAMPLE: Using underscore character in numbers

27_195_000
16'b0011_0101_0001_1111
32'h 12ab_f001

EXAMPLE: Real constants

1.2
0.1
2394.26331
1.2E12 (the exponent symbol can be e or E)
1.30e-2
0.1e-0
23E10
29E-2
236.123_763_e-12 (underscores are ignored)

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/VT_02_SYNTAX.html[9/26/2012 2:43:34 PM]


WWW.TESTBENCH.IN - Verilog Basic Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS DATA TYPES Index


Introduction
SystemVerilog Value Set Syntax
Verification Data Types
Operators
Constructs The Verilog HDL value set consists of four basic values: Assignments
Interface 0 - represents a logic zero, or a false condition Control Constructs
1 - represents a logic one, or a true condition Procedural Timing
OOPS Controls
x - represents an unknown logic value
Randomization z - represents a high-impedance state Structure
The values 0 and 1 are logical complements of one another. Block Statements
Functional Coverage Structured Procedures
Assertion
Net Report a Bug or Comment
DPI on This section - Your
UVM Tutorial input is what keeps
VMM Tutorial The net data types shall represent physical connections between structural entities, Testbench.in improving
such as gates. A net shall not store a value (except for the trireg net). Instead, its with time!
OVM Tutorial value shall be determined by the values of its drivers,  such as a continuous
Easy Labs : SV assignment or a gate. If no driver is connected to a net, its value shall be high-
impedance (z) unless the net is a trireg, in which case it shall hold the previously
Easy Labs : UVM driven value. It is illegal to redeclare a name already declared by a net, parameter,
Easy Labs : OVM or variable declaration.
Easy Labs : VMM
AVM Switch TB Variable Or Reg
VMM Ethernet sample
A variable is an abstraction of a data storage element. A variable shall store a value
from one assignment to the next. An assignment statement in a procedure acts as a
Verilog trigger that changes the value in the data storage element. The initialization value for
Verification reg, time, and integer data types shall be the unknown value, x. The default
initialization value for real and realtime variable datatypes shall be 0.0. If a variable
Verilog Switch TB declaration assignment is used , the variable shall take this value as if the assignment
Basic Constructs occurred in a blocking assignment in an initial construct. It is illegal to redeclare a
name already declared by a net, parameter, or variable declaration.

OpenVera Vectors
Constructs
Switch TB
A net or reg declaration without a range specification shall be considered 1 bit wide
RVM Switch TB and is known as a scalar. Multiple bit net and reg data types shall be declared by
RVM Ethernet sample specifying a range, which is known as a vector.

EXAMPLES:
Specman E wand w; // a scalar net of type wand
Interview Questions tri [15:0] busa; // a three-state 16-bit bus
trireg (small) storeit; // a charge storage node of strength small
reg a; // a scalar reg
reg[3:0] v; // a 4-bit vector reg made up of (from most to
// least significant) v[3], v[2], v[1], and v[0]
reg signed [3:0] signed_reg; // a 4-bit vector in range -8 to 7
reg [-1:4] b; // a 6-bit vector reg
wire w1, w2; // declares two wires
reg [4:0] x, y, z; // declares three 5-bit regs

Memories

http://testbench.in/VT_03_DATA_TYPES.html[9/26/2012 2:43:42 PM]


WWW.TESTBENCH.IN - Verilog Basic Constructs

A one dimensional array with elements of type reg is also called a memory. These
memories can be used to model read-only memories (ROMs), random access memories
(RAMs), and reg files. Each reg in the array is known as an element or word and is
addressed by a single array index. An n-bit reg can be assigned a value in a single
assignment, but a complete memory cannot. To assign a value to a memory word, an
index shall be specified. The index can be an expression. This option provides a
mechanism to reference different memory words, depending on the value of other
variables and nets in the circuit. For example, a program counter reg could be used
to index into a RAM.

EXAMPLE:
reg [7:0] mema[0:255]; // declares a memory mema of 256 8-bit
// registers. The indices are 0 to 255
reg arrayb[7:0][0:255]; // declare a two dimensional array of
// one bit registers
wire w_array[7:0][5:0]; // declare array of wires
integer inta[1:64]; // an array of 64 integer values
time chng_hist[1:1000] // an array of 1000 time values

mema = 0; // Illegal syntax- Attempt to write to entire array


arrayb[1] = 0; // Illegal Syntax - Attempt to write to elements
// [1][0]..[1][255]
arrayb[1][12:31] = 0; // Illegal Syntax - Attempt to write to
// elements [1][12]..[1][31]
mema[1] = 0; //Assigns 0 to the second element of mema
arrayb[1][0] = 0; // Assigns 0 to the bit referenced by indices
// [1][0]
inta[4] = 33559; // Assign decimal number to integer in array
chng_hist[t_index] = $time; // Assign current simulation time to
// element addressed by integer index

reg [1:n] rega; // An n-bit register is not the same


reg mema [1:n]; // as a memory of n 1-bit registers

Net Types

There are several distinct types of nets , they are

wire , tri , tri0 , supply0 , wand, triand, tri1, supply1, wor, trior, trireg.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/VT_03_DATA_TYPES.html[9/26/2012 2:43:42 PM]


WWW.TESTBENCH.IN - Verilog Basic Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS OPERATORS Index


Introduction
SystemVerilog Binary Arithmetic Operators Syntax
Verification Data Types
Binary arithmetic operators operate on two operands. Register and net (wire) Operators
Constructs operands are treated as unsigned. However, real and integer operands may be signed. Assignments
Interface If any bit is unknown ('x') then result is unknown. Control Constructs
Procedural Timing
OOPS Controls
Randomization    Operator     Name                    
Structure
        +       Addition                 Block Statements
Functional Coverage         -       Subtraction Structured Procedures
Assertion         *       Multiplication
        /       Division        
Report a Bug or Comment
DPI         %       Modulus
on This section - Your
UVM Tutorial input is what keeps
Testbench.in improving
VMM Tutorial
with time!
OVM Tutorial
Unary Arithmetic Operators

Easy Labs : SV
Easy Labs : UVM   Operator      Name            
        -       Unary Minus    
Easy Labs : OVM
Easy Labs : VMM
Relational Operators
AVM Switch TB
VMM Ethernet sample Relational operators compare two operands and return a logical value, i. e., TRUE(1)
or FALSE(0). If any bit is unknown, the relation is ambiguous and the result is
unknown.
Verilog
Verification   Operator      Name                    
Verilog Switch TB
   >            Greater than
Basic Constructs    >=           Greater than or equal
   <            Less than
   <=           Less than or equal
   ==           Logical equality
OpenVera    !=           Logical inequality

Constructs
Switch TB
Logical Operators
RVM Switch TB
RVM Ethernet sample
Logical operators operate on logical operands and return a logical value, i. e.,
TRUE(1) or FALSE(0). Used typically in if and while statements. Do not confuse logical
operators with the bitwise Boolean operators. For example , ! is a logical NOT and ~ is
Specman E a bitwise NOT. The first negates, e. g., !(5 == 6) is TRUE. The second complements
Interview Questions the bits, e. g., ~{1,0,1,1} is 0100.

        Operator        Name            
        !       Logical negation
        &&      Logical AND
        ||      Logical OR

Bitwise Operators

http://testbench.in/VT_04_OPERATORS.html[9/26/2012 2:43:52 PM]


WWW.TESTBENCH.IN - Verilog Basic Constructs

Bitwise operators operate on the bits of the operand or operands. For example, the
result of A & B is the AND of each corresponding bit of A with B. Operating on an
unknown (x) bit results in the expected value. For example, the AND of an x with a
FALSE is an x. The OR of an x with a TRUE is a TRUE.

        Operator        Name            
        ~         Bitwise negation
        &         Bitwise AND
        |         Bitwise OR
        ^         Bitwise XOR
        ~&        Bitwise NAND
        ~|        Bitwise NOR
        ~^ or ^~  Equivalence   Bitwise NOT XOR

Unary Reduction Operators

Unary reduction operators produce a single bit result from applying the operator to all
of the bits of the operand. For example, &A will AND all the bits of A.

        Operator        Name            
        &       AND reduction
        |       OR reduction
        ^       XOR reduction
        ~&      NAND reduction
        ~|      NOR reduction
        ~^      XNOR reduction

Other Operators

The conditional operator operates much like in the language C.

  Operator Name        
  ===   Case equality  
  !==   Case inequality
  { , } Concatenation  
  <<    Shift left      
  >>    Shift right    
  ?:    Conditional

Case equality   : The bitwise comparison includes comparison of x and z values.  All


bits must match for equality.  Returns TRUE or FALSE.

Case inequality : The bitwise comparison includes comparison of x and z values.  Any


bit difference produces inequality.  Returns TRUE or FALSE.

Concatenation   : Joins bits together with 2 or more comma-separated


expressions,  e, g. {A[0], B[1:7]} concatenates the zeroth bit of A to  bits 1 to 7 of B.

Shift left      : Vacated bit positions are filled with zeros, e. g., A = A << 2; shifts A
two bits to left with zero fill.

Shift right     : Vacated bit positions are filled with zeros.

Conditional     : Assigns one of two values depending on the conditional expression.  E.


g., A = C>D ? B+3 : B-2  means if C greater than D, the value of A is B+3 otherwise B-
2.

Operator Precedence

http://testbench.in/VT_04_OPERATORS.html[9/26/2012 2:43:52 PM]


WWW.TESTBENCH.IN - Verilog Basic Constructs

The precedence of operators is shown below. The top of the table is the highest
precedence and the bottom is the lowest. Operators on the same line have the same
precedence and associate left to right in an expression. Parentheses can be used to
change the precedence or clarify the situation. We strongly urge you to use
parentheses to improve readability.

!  &  ~&  |  ~|  ^  ~^  +  -   (highest precedence)


*  /  %
+  -
<<  >>
<  <=  >  >+
==  !=  ===  ~==
&  ~&  ^  ~^
|  ~|
&&
||
?:

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/VT_04_OPERATORS.html[9/26/2012 2:43:52 PM]


WWW.TESTBENCH.IN - Verilog Basic Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS ASSIGNMENTS Index


Introduction
SystemVerilog The assignment is the basic mechanism for placing values into nets and variables. Syntax
Verification There are two basic forms of assignments: Data Types
-- The continuous assignment, which assigns values to nets Operators
Constructs -- The procedural assignment, which assigns values to variables Assignments
Interface Control Constructs
Procedural Timing
OOPS Controls
Randomization Legal left-hand side forms in assignment statements Structure
----------------------------------------------------------------- Block Statements
Functional Coverage Statement type            Left-hand side (LHS) Structured Procedures
-----------------------------------------------------------------
Assertion Continuous assignment     Net (vector or scalar)
                          Constant bit select of a vector net Report a Bug or Comment
DPI                           Constant part select of a vector net on This section - Your
UVM Tutorial                           Constant indexed part select of a vector net input is what keeps
                          Concatenation of any of the above four LHS
Testbench.in improving
VMM Tutorial -----------------------------------------------------------------
Procedural assignment     Variables (vector or scalar) with time!
OVM Tutorial                           Bit-select of a vector reg, integer, or time
variable
Easy Labs : SV                           Constant part select of a vector reg,
                                   integer, or time variable
Easy Labs : UVM                           Memory word
                          Indexed part select of a vector reg,
Easy Labs : OVM                                   integer, or time variable
Easy Labs : VMM                           Concatenation of regs; bit or part selects of
regs
AVM Switch TB
-----------------------------------------------------------------
VMM Ethernet sample

The following is an example of the use of a continuous assignment to model a 4-bit


Verilog adder.
Verification
EXAMPLE:
Verilog Switch TB module adder (sum_out, carry_out, carry_in, ina, inb);
Basic Constructs output [3:0] sum_out;
output carry_out;
input [3:0] ina, inb;
input carry_in;
OpenVera wire carry_out, carry_in;
Constructs wire [3:0] sum_out, ina, inb;
Switch TB assign {carry_out, sum_out} = ina + inb + carry_in;
endmodule
RVM Switch TB
RVM Ethernet sample The following is an example of the use of a Procedural assignment to model a
4-bit adder.
EXAMPLE:
module adder (sum_out, carry_out, carry_in, ina, inb);
Specman E output [3:0] sum_out;
Interview Questions output carry_out;
input [3:0] ina, inb;
input carry_in;
reg carry_out;
wire carry_in;
reg [3:0] sum_out;
wire [3:0] ina, inb;

always@(ina or inb or carry_in)


{carry_out, sum_out} = ina + inb + carry_in;

http://testbench.in/VT_05_ASSIGNMENTS.html[9/26/2012 2:43:59 PM]


WWW.TESTBENCH.IN - Verilog Basic Constructs

endmodule

Blocking Procedural Assignments

A blocking procedural assignment statement shall be executed before the execution of


the statements that follow it in a sequential block. A blocking procedural assignment
statement shall not prevent the execution of statements that follow it in a parallel
block .

EXAMPLE:
rega = 0;
rega[3] = 1; // a bit-select
rega[3:5] = 7; // a part-select
mema[address] = 8'hff; // assignment to a mem element
{carry, acc} = rega + regb; // a concatenation

The Nonblocking Procedural Assignment

The nonblocking procedural assignment allows assignment scheduling without blocking


the procedural flow. The nonblocking procedural assignment statement can be used
whenever several variable assignments within the same time step can be made
without regard to order or dependence upon each other.

EXAMPLE:

module evaluates2 (out);
output out;
reg a, b, c;
initial begin
a = 0;
b = 1;
c = 0;
end
always c = #5 ~c;
always @(posedge c) begin
a <= b; // evaluates, schedules,
b <= a; // and executes in two steps
end
endmodule

Procedural Continuous Assignments

The procedural continuous assignments (using keywords assign and force) are
procedural statements that allow expressions to be driven continuously onto variables
or nets.

The left-hand side of the assignment in the assign statement shall be a variable
reference or a concatenation of variables. It shall not be a memory word (array
reference) or a bit-select or a part-select of a variable. In contrast, the left-hand
side of the assignment in the force statement can be a variable reference or a net
reference. It can be a concatenation of any of the above. Bit-selects and part-selects
of vector variables are not allowed.

Assign And Deassign Procedural Statements

The assign procedural continuous assignment statement shall override all procedural
assignments to a variable. The deassign procedural statement shall end a procedural
continuous assignment to a variable. The value of the variable shall remain the same
until the reg is assigned a new value through a procedural assignment or a procedural
continuous assignment.

EXAMPLE:
module dff (q, d, clear, preset, clock);
output q;
input d, clear, preset, clock;

http://testbench.in/VT_05_ASSIGNMENTS.html[9/26/2012 2:43:59 PM]


WWW.TESTBENCH.IN - Verilog Basic Constructs

reg q;
always @(clear or preset)
if (!clear)
assign q = 0;
else if (!preset)
assign q = 1;
else
deassign q;
always @(posedge clock)
q = d;
endmodule

Force And Release Procedural Statements

Another form of procedural continuous assignment is provided by the force and release
procedural statements. These statements have a similar effect to the assign-deassign
pair, but a force can be applied to nets as well as to variables. The left-hand side of
the assignment can be a variable, a net, a constant bit-select of a vector net, a part-
select of a vector net, or a concatenation. It cannot be a memory word (array
reference) or a bit-select or a part-select of a vector variable.

A force statement to a variable shall override a procedural assignment or procedural


continuous assignment that takes place on the variable until a release procedural
statement is executed on the variable. After the release procedural statement is
executed, the variable shall not immediately change value (as would a net that is
assigned with a procedural continuous assignment). The value specified in the force
statement shall be maintained in the variable until the next procedural assignment
takes place, except in the case where a procedural continuous assignment is active on
the variable.

A force procedural statement on a net overrides all drivers of the net gate outputs,
module outputs, and continuous assignments until a release procedural statement is
executed on the net. Releasing a variable that currently has an active procedural
continuous assignment shall re-establish that assignment.

EXAMPLE:
module test;
reg a, b, c, d;
wire e;
and and1 (e, a, b, c);
initial begin
$monitor("%d d=%b,e=%b", $stime, d, e);
assign d = a & b & c;
a = 1;
b = 0;
c = 1;
#10;
force d = (a | b | c);
force e = (a | b | c);
#10 $stop;
release d;
release e;
#10 $finish;
end
endmodule
Results:
0 d=0,e=0
10 d=1,e=1
20 d=0,e=0

Delays

Delays are not synthesysable. In a delayed assignment Dt time units pass before the
statement is executed and the left-hand assignment is made. With intra-assignment
delay, the right side is evaluated immediately but there is a delay of Dt before the
result is place in the left hand assignment. If another procedure changes a right-hand
side signal during Dt, it does not effect the output. Delays are not supported by
synthesis tools.

Inter Assignmnet Delay .

http://testbench.in/VT_05_ASSIGNMENTS.html[9/26/2012 2:43:59 PM]


WWW.TESTBENCH.IN - Verilog Basic Constructs

This is the most common delay used - sometimes also referred to as inter-assignment
delay control.

EXAMPLE:

#10 q = x + y;

It simply waits for the appropriate number of timesteps before executing the
command.

Intra-Assignment Delay Control

With this kind of delay, the value of x + y is stored at the time that the assignment is
executed, but this value is not assigned to q until after the delay period, regardless of
whether or not x or y have changed during that time.

EXAMPLE:

q = #10 x + y;

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/VT_05_ASSIGNMENTS.html[9/26/2012 2:43:59 PM]


WWW.TESTBENCH.IN - Verilog Basic Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS CONTROL CONSTRUCTS Index


Introduction
SystemVerilog Verilog HDL has a rich collection of control statements which can used in the Syntax
Verification procedural sections of code, i. e., within an initial or always block. Most of them will Data Types
be familiar to the programmer of traditional programming languages like C. The main Operators
Constructs difference is instead of C's { } brackets, Verilog HDL uses begin and end. In Verilog, Assignments
Interface the { } brackets are used for concatenation of bit strings. Since most users are Control Constructs
familiar with C, the following subsections typically show only an example of each Procedural Timing
OOPS Controls
construct.
Randomization Structure
If And If Else Statements Block Statements
Functional Coverage Structured Procedures
Assertion The conditional statement (or if-else statement) is used to make a decision as to
whether a statement is executed or not. Report a Bug or Comment
DPI on This section - Your
UVM Tutorial EXAMPLE: input is what keeps
    if (A == 4) Testbench.in improving
VMM Tutorial
       begin with time!
OVM Tutorial          B = 2;
Easy Labs : SV        end
    else
Easy Labs : UVM        begin
Easy Labs : OVM          B = 4;
       end
Easy Labs : VMM
AVM Switch TB Case
VMM Ethernet sample The case statement is a multiway decision statement that tests whether an
expression matches one of a number of other expressions and branches accordingly.

Verilog     case (<expression>)
Verification       <value1>: <statement>
      <value2>: <statement>
Verilog Switch TB       default: <statement>
Basic Constructs     endcase

The following example checks a 1-bit signal for its value.


OpenVera EXAMPLE:
Constructs     case (sig)
Switch TB       1'bz: $display("Signal is floating");
      1'bx: $display("Signal is unknown");
RVM Switch TB       default: $display("Signal is %b", sig);
RVM Ethernet sample     endcase

 
Specman E Forever
Interview Questions
Forever Continuously executes a statement or block till the end of simulation.

EXAMPLE:
        initial
        clock =0;
        forever
        #10 clock = ~clock;
        end

Repeat

http://testbench.in/VT_06_CONTROL_CONSTRUCTS.html[9/26/2012 2:44:08 PM]


WWW.TESTBENCH.IN - Verilog Basic Constructs

Executes a statement a fixed number of times. If the expression evaluates to unknown


or high impedance, it shall be treated as zero, and no statement shall be executed.

EXAMPLE:
parameter size = 8, longsize = 16;
reg [size:1] opa, opb;
reg [longsize:1] result;
begin : mult
reg [longsize:1] shift_opa, shift_opb;
shift_opa = opa;
shift_opb = opb;
result = 0;
repeat (size) begin
if (shift_opb[1])
result = result + shift_opa;
shift_opa = shift_opa << 1;
shift_opb = shift_opb >> 1;
end
end

While

Executes a statement until an expression becomes false. If the expression starts out
false, the statement shall not be executed at all.

EXAMPLE:
begin : count1s
reg [7:0] tempreg;
count = 0;
tempreg = rega;
while (tempreg) begin
if (tempreg[0])
count = count + 1;
tempreg = tempreg >> 1;
end
end

For

Controls execution of its associated statement(s) by a three-step process, as follows:


a) Executes an assignment normally used to initialize a variable that controls the
number of loops executed.
b) Evaluates an expression if the result is zero, the for-loop shall exit, and if it is not
zero, the for-loop shall execute its associated statement(s) and then perform step c.
If the expression evaluates to an unknown or high-impedance value, it shall be
treated as zero.
c) Executes an assignment normally used to modify the value of the loop-control
variable, then repeats step b.

EXAMPLE:
begin
initial_assignment;
while (condition) begin
statement
step_assignment;
end
end

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/VT_06_CONTROL_CONSTRUCTS.html[9/26/2012 2:44:08 PM]


WWW.TESTBENCH.IN - Verilog Basic Constructs

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/VT_06_CONTROL_CONSTRUCTS.html[9/26/2012 2:44:08 PM]


WWW.TESTBENCH.IN - Verilog Basic Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PROCEDURAL TIMING CONTROLS Index


Introduction
SystemVerilog Delay Control Syntax
Verification Data Types
A procedural statement following the delay control shall be delayed in its execution Operators
Constructs with respect to the procedural statement preceding the delay control by the specified Assignments
Interface delay. If the delay expression evaluates to an unknown or high-impedance value, it Control Constructs
shall be interpreted as zero delay. If the delay expression evaluates to a negative Procedural Timing
OOPS Controls
value, it shall be interpreted as a 2 s complement unsigned integer of the same size
Randomization as a time variable. Structure
Specify parameters are permitted in the delay expression. They may be overridden by Block Statements
Functional Coverage Structured Procedures
SDF annotation, in which case the expression is reevaluated.
Assertion
Report a Bug or Comment
DPI on This section - Your
EXAMPLE
UVM Tutorial #10 rega = regb; input is what keeps
#d rega = regb; // d is defined as a parameter Testbench.in improving
VMM Tutorial
#((d+e)/2) rega = regb;// delay is average of d and e with time!
OVM Tutorial #regr regr = regr + 1; // delay is the value in regr
Easy Labs : SV
Event Control
Easy Labs : UVM
Easy Labs : OVM The execution of a procedural statement can be synchronized with a value change on
a net or variable or the occurrence of a declared event. The value changes on nets
Easy Labs : VMM and variable can be used as events to trigger the execution of a statement. This is
AVM Switch TB known as detecting an implicit event. The event can also be based on the direction of
the change that is, towards the value 1 ( posedge) or towards the value 0 (negedge).
VMM Ethernet sample -- A negedge shall be detected on the transition from 1 to x, z, or 0, and from x or z
to 0
-- A posedge shall be detected on the transition from 0 to x, z, or 1, and from x or z
Verilog to 1
Verification
Verilog Switch TB EXAMPLE:
Basic Constructs @r rega = regb; // controlled by any value change in the reg r
@(posedge clock) rega = regb; // controlled by posedge on clock
forever @(negedge clock) rega = regb; // controlled by negative edge
OpenVera Named Events
Constructs
Switch TB A new data type, in addition to nets and variables, called event can be declared. An
identifier declared as an event data type is called a named event. A named event can
RVM Switch TB be triggered explicitly. It can be used in an event expression to control the execution
RVM Ethernet sample of procedural statements in the same manner as event control . Named events can be
made to occur from a procedure. This allows control over the enabling of multiple
actions in other procedures. An event name shall be declared explicitly before it is
used.
Specman E
Interview Questions

http://testbench.in/VT_07_PROCEDURAL_TIMING_CONTROLS.html[9/26/2012 2:44:18 PM]


WWW.TESTBENCH.IN - Verilog Basic Constructs

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/VT_07_PROCEDURAL_TIMING_CONTROLS.html[9/26/2012 2:44:18 PM]


WWW.TESTBENCH.IN - Verilog Basic Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS STRUCTURE Index


Introduction
SystemVerilog Module Syntax
Verification Data Types
A module in Verilog is used to define a circuit or a sub circuit. The module is the Operators
Constructs fundamental circuit building block in Verilog. Modules have the following structure: Assignments
Interface (keywords in bold). Note that the module declaration ends with a semicolon but the Control Constructs
keyword endmodule does not. Procedural Timing
OOPS Controls
Randomization Structure
CODE: Block Statements
Functional Coverage Structured Procedures
module module_name (port_name list);
Assertion [declarations]
[assign statements] Report a Bug or Comment
DPI on This section - Your
[initial block]
UVM Tutorial [always block] input is what keeps
[gate instantiations] Testbench.in improving
VMM Tutorial
[other module instantiations] with time!
OVM Tutorial endmodule
Easy Labs : SV
Ports
Easy Labs : UVM
Easy Labs : OVM Ports in Verilog can be of type input, output¸ or inout. The module ports are given in
the port name list and are declared in the beginning of the module. Here is a sample
Easy Labs : VMM module with input and output ports.
AVM Switch TB
VMM Ethernet sample EXAMPLE:
module MyModule(aIn, bOut);
input aIn;
Verilog output bOut;
Verification endmodule
Verilog Switch TB
Basic Constructs The port names input and output default to type wire. Either can be a vector and the
output variables can be of redeclared to type reg. The output and input variables in a
module are typically names for the output and input pins on the implementation chip.
OpenVera
Constructs Signals
Switch TB
a signal is represented by either a net type or a variable type in Verilog. The net type
RVM Switch TB represents a circuit node and these can be of several types. The two net types most
RVM Ethernet sample often used are wire and tri. Type nets do not have to be declared in Verilog since
Verilog assumes that all signals are nets unless they are declared otherwise. Variables
are either of type reg or integer. Integers are always 32-bits where the reg type of
variables may be of any length. Typically we use integers as loop counters and reg
Specman E variables for all other variables. The generic form for representing a signal in Verilog
Interview Questions is:

CODE:
type[range] signal_name

The range is omitted for scalar variables but used for vectors.
The net types are typically used for input signals and for intermediate signals within
combinational logic. Variables are used for sequential circuits or for outputs which
are assigned a value within a sequential always block.

http://testbench.in/VT_08_STRUCTURE.html[9/26/2012 2:44:27 PM]


WWW.TESTBENCH.IN - Verilog Basic Constructs

EXAMPLEs:
wire w; //w is a single net of type wire
wire[2:0] wVect; //Declares wVect[2], wVect[1], wVect[0]
tri[7:0] bus //An 8-bit tri state bus
integer i; //i is a 32-bit integer used for loop control
reg r; //r is a 1-bit register
reg[7:0] buf; //buf is an 8-bit register
reg[3:0] r1, r2 //r1 and r2 are both 4-bit registers

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/VT_08_STRUCTURE.html[9/26/2012 2:44:27 PM]


WWW.TESTBENCH.IN - Verilog Basic Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS BLOCK STATEMENTS Index


Introduction
SystemVerilog Syntax
Verification The block statements are a means of grouping two or more statements together so Data Types
that they act syntactically like a single statement. There are two types of blocks in Operators
Constructs the Verilog HDL: Assignments
Interface Sequential block, also called begin-end block Control Constructs
Parallel block, also called fork-join block Procedural Timing
OOPS Controls
The sequential block shall be delimited by the keywords begin and end. The
Randomization procedural statements in sequential block shall be executed sequentially in the given Structure
order. Block Statements
Functional Coverage Structured Procedures
The parallel block shall be delimited by the keywords fork and join. The procedural
Assertion statements in parallel block shall be executed concurrently.
Report a Bug or Comment
DPI on This section - Your
UVM Tutorial Sequential Blocks input is what keeps
Testbench.in improving
VMM Tutorial
A sequential block shall have the following characteristics: with time!
OVM Tutorial -- Statements shall be executed in sequence, one after another
Easy Labs : SV -- Delay values for each statement shall be treated relative to the simulation time of
the execution of the previous statement
Easy Labs : UVM -- Control shall pass out of the block after the last statement executes
Easy Labs : OVM
Easy Labs : VMM EXAMPLE:
AVM Switch TB begin
areg = breg;
VMM Ethernet sample creg = areg; // creg stores the value of breg
end

Verilog Parallel Blocks


Verification
A parallel block shall have the following characteristics:
Verilog Switch TB -- Statements shall execute concurrently
Basic Constructs -- Delay values for each statement shall be considered relative to the simulation time
of entering the block
-- Delay control can be used to provide time-ordering for assignments
-- Control shall pass out of the block when the last time-ordered statement executes
OpenVera
Constructs
Switch TB EXAMPLE:
fork
RVM Switch TB @enable_a
RVM Ethernet sample begin
#ta wa = 0;
#ta wa = 1;
#ta wa = 0;
Specman E end
Interview Questions @enable_b
begin
#tb wb = 1;
#tb wb = 0;
#tb wb = 1;
end
join

http://testbench.in/VT_09_BLOCK_STATEMENTS.html[9/26/2012 2:44:35 PM]


WWW.TESTBENCH.IN - Verilog Basic Constructs

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/VT_09_BLOCK_STATEMENTS.html[9/26/2012 2:44:35 PM]


WWW.TESTBENCH.IN - Verilog Basic Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS STRUCTURED PROCEDURES Index


Introduction
SystemVerilog Syntax
Verification All procedures in the Verilog HDL are specified within one of the following four Data Types
statements: Operators
Constructs -- initial construct Assignments
Interface -- always construct Control Constructs
-- Task Procedural Timing
OOPS Controls
-- Function
Randomization Structure
The initial and always constructs are enabled at the beginning of a simulation. The Block Statements
Functional Coverage
initial construct shall execute only once and its activity shall cease when the Structured Procedures
Assertion statement has finished. In contrast, the always construct shall execute repeatedly. Its
DPI activity shall cease only when the simulation is terminated. There shall be no implied Report a Bug or Comment
order of execution between initial and always constructs. The initial constructs need on This section - Your
UVM Tutorial not be scheduled and executed before the always constructs. There shall be no limit input is what keeps
to the number of initial and always constructs that can be defined in a module Testbench.in improving
VMM Tutorial
with time!
OVM Tutorial Initial
Easy Labs : SV
Easy Labs : UVM An initial block consists of a statement or a group of statements enclosed in begin...
Easy Labs : OVM end or a signle statement , which will be executed only once at simulation time 0. If
there is more than one block they execute concurrently and independently. The initial
Easy Labs : VMM block is normally used for initialisation, monitoring, generating wave forms (eg, clock
AVM Switch TB pulses) and processes which are executed once in a simulation. An example of
initialisation and wave generation is given below
VMM Ethernet sample
EXAMPLE:
        initial
Verilog         clock = 1'b0;  // variable initialization
Verification
        initial
Verilog Switch TB            begin  // multiple statements have to be grouped
Basic Constructs            alpha = 0;
           #10 alpha = 1;  // waveform generation
           #20 alpha = 0;
           #5  alpha = 1;
OpenVera            #7  alpha = 0;
Constructs            #10 alpha = 1;
Switch TB            #20 alpha = 0;
           end;
RVM Switch TB
RVM Ethernet sample Always

An always block is similar to the initial block, but the statements inside an always
Specman E block will repeated continuously, in a looping fashion, until stopped by $finish or
Interview Questions $stop.

NOTE: the $finish command actually terminates the simulation where as $stop.
merely pauses it and awaits further instructions. Thus $finish is the preferred
command unless you are using an interactive version of the simulator.

One way to simulate a clock pulse is shown in the example below. Note, this is not the
best way to simulate a clock. See the section on the forever loop for a better method.

EXAMPLE:
        module pulse;

http://testbench.in/VT_10_STRUCTURED_PROCEDURES.html[9/26/2012 2:44:45 PM]


WWW.TESTBENCH.IN - Verilog Basic Constructs

        reg clock;

        initial clock = 1'b0; // start the clock at 0


        always #10 clock = ~clock; // toggle every 10 time units
        initial #5000 $finish // end the simulation after 5000 time units

        endmodule

Tasks and functions can bu used to in much the same manner but there are some
important differences that must be noted.

Functions

A function is unable to enable a task however functions can enable other functions.
A function will carry out its required duty in zero simulation time.  
Within a function, no event, delay or timing control statements are permitted.
In the invocation of a function their must be at least one argument to be passed.
Functions will only return a single value and can not use either output or inout
statements.
Functions are synthesysable.
Disable statements canot be used.
Function canot have numblocking statements.

EXAMPLE:function

module  function_calling(a, b,c); 
                  
input a, b ; 
output c; 
wire c; 
    
function  myfunction; 
input a, b; 
begin 
 myfunction = (a+b); 
end 
endfunction 

assign c =  myfunction (a,b); 


          
endmodule 

Task

Tasks are capable of enabling a function as well as enabling other versions of a Task
Tasks also run with a zero simulation however they can if required be executed in a
non zero simulation time.
Tasks are allowed to contain any of these statements.
A task is allowed to use zero or more arguments which are of type output, input or
inout.
A Task is unable to return a value but has the facility to pass multiple values via the
output and inout statements.
Tasks are not synthesisable.
Disable statements can be used.

EXAMPLE:task
module traffic_lights; 
reg clock, red, amber, green; 
parameter on = 1, off = 0, red_tics = 350, 
amber_tics = 30, green_tics = 200; 
// initialize colors.

http://testbench.in/VT_10_STRUCTURED_PROCEDURES.html[9/26/2012 2:44:45 PM]


WWW.TESTBENCH.IN - Verilog Basic Constructs

initial red = off; 
initial amber =

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/VT_10_STRUCTURED_PROCEDURES.html[9/26/2012 2:44:45 PM]


WWW.TESTBENCH.IN - Vera Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INTRODUCTION Index


Introduction
SystemVerilog Data Types
Verification Introduction Linked List
Operators Part 1
Constructs Operators Part 2
Interface OpenVera is an intuitive easy to learn language that combines the familiarity and Operators Part 3
strengths of HDLs, C++ and Java, with additional constructs targeted at functional Operator Precedence
OOPS Control Statements
verification making it ideal for developing testbenches, assertions and properties.
Randomization OpenVera accelerates the creation of a verification environment by providing high- Procedures And Methods
level constructs specifically designed for verification of complex SoCs. Designers Interprocess
Functional Coverage Fork Join
create testbenches and assertions using OpenVera and EDA vendors create tools that
Assertion are automatically interoperable. Shadow Variables
Fork Join Control
DPI Wait Var
UVM Tutorial Comments In Openvera: Event Sync
Event Trigger
VMM Tutorial Semaphore
In OpenVera supports two tytes of comments.
OVM Tutorial # One line comment : Starts with Regions
Mailbox
Easy Labs : SV
     // and ends at the end of the line. Timeouts
Easy Labs : UVM Oop
# Block comments   : Starts with Casting
Easy Labs : OVM
Randomization
Easy Labs : VMM     /* and ends with */ Randomization Methods
AVM Switch TB Constraint Block
Constraint Expression
VMM Ethernet sample Numbers In Openvera: Variable Ordaring
Aop
In OpenVera,numbers can be represented in two formats. Predefined Methods
Verilog # Simple integer number.  Ex:   1, 50, + 20 ,- 33,- 3_3. String Methods
# base ' size notaion .   Ex:   1'b0,2'00,'haf,3`d555. Queue Methods
Verification
Dut Communication
Verilog Switch TB Underscore _ are ignored. Functional Coverage
Basic Constructs X and x are unknown and Z and z are high impedence values.
Report a Bug or Comment
on This section - Your
input is what keeps
OpenVera Testbench.in improving
Constructs with time!
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/OV_01_INTRODUCTION.html[9/26/2012 2:44:54 PM]


WWW.TESTBENCH.IN - Vera Constructs

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OV_01_INTRODUCTION.html[9/26/2012 2:44:54 PM]


WWW.TESTBENCH.IN - Vera Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS DATA TYPES Index


Basic Data Types: Introduction
SystemVerilog Data Types
Verification OpenVera’s basic data types are: Linked List
Operators Part 1
Constructs Operators Part 2
Integer                  
Interface Operators Part 3
Register                   Operator Precedence
OOPS String                     Control Statements
Randomization
Event                     Procedures And Methods
Enumerated Types           Interprocess
Functional Coverage Virtual Ports             Fork Join
Assertion Arrays                     Shadow Variables
Smart Queues               Fork Join Control
DPI Wait Var
Class                    
UVM Tutorial Event Sync
Standalone Coverage Group Event Trigger
VMM Tutorial Semaphore
OVM Tutorial Regions
Integer : Mailbox
Easy Labs : SV
Timeouts
Easy Labs : UVM  Integers are signed variables.For 32 bit mechine,range is between -231 and 231 -1.An Oop
integer may become X (unknown) when it is not initialized or when an undefined value Casting
Easy Labs : OVM is stored. Randomization
Easy Labs : VMM Randomization Methods
Register : Constraint Block
AVM Switch TB
Constraint Expression
VMM Ethernet sample Registers are unsigned variables with the value 0, 1, z, or x.Registers can be declared Variable Ordaring
with multiple bit widths. Aop
Predefined Methods
value condition           String Methods
Verilog  0    logic 0             Queue Methods
Verification  1    logic 1             Dut Communication
Verilog Switch TB  z    high impedance       Functional Coverage
 x    unknown            
Basic Constructs
Report a Bug or Comment
on This section - Your
String:
input is what keeps
OpenVera Testbench.in improving
A string is a sequence of characters enclosed by double quotes.OpenVera has
Constructs with time!
stringmethods for mamuplulating the charecters.
Switch TB
RVM Switch TB
    string a;
    string b = "Hi";
RVM Ethernet sample     string c = b;

Event :
Specman E
A event can be triggered explicitly. It can be used in an event expression to control
Interview Questions the execution of procedural statements.

Enumerated Types :

Enumerated types are a user-defined list of named integer constants. They can either
be defined in the global name space, or in a class.Elements within enumerated type
definitions are numbered consecutively, starting from 0.Each element may have an
optional explicit value assigned to it.

 Default numbering    
  Ex :  enum colors {red, green, blue, yellow, white, black};

http://testbench.in/OV_02_DATA_TYPES.html[9/26/2012 2:45:02 PM]


WWW.TESTBENCH.IN - Vera Constructs

 Explicit numbering  
  Ex :  enum instructions {add=10, sub, div, mul=4, jmp};
 Class Scope enumration
 Ex : class Bus { enum TRAFFIC = PCI, AHB, USB; }

Virtual Ports :

A virtual port is a user-defined data type that contains a set of port signal members
grouped together under a given user-defined port name.

 port rcv_port
 {
   frame_n;
   valid_n;
   busy;
   packet;
 }
Arrays :

 OpenVera has one dimentional and multidimentional arrays.


There are four different types of arrays.

Fixed-Size Arrays:

Arrays whose size is fixed at compilation time are called fixed tsize arrays.The access
time is constant regardless of the number of elements in an array.Multi-dimensional
arrays are fixed-size arrays with multiple dimensions.

    integer array_ex[5];   // 1D array of size 5


    integer matrix [2][5]; // 2d array of size 2 x 5
    integer x[2][2]={{0,1},{2,3}}; // Array initilization

Dynamic Arrays :

The size of dynamic arrays can be allocated and resized at runtime.

    integer array_ex[*];

new[] : The new[] operator is used to set or change the size of dynamic
arrays during runtime.

    integer packetA[*], packetB[*]; // Declare 2 arrays.


    packetA = new[100]; // Create packetA.
    packetB = new[100] (packetA); // create packetB and initia

Associative Arrays :

 When the size of the collection is unknown or the data space is sparse, associative
array are used.Associative arrays do not have any storage allocated until it is used,
and the index expression is not restricted to integral expressions, but can be of any
type.

    integer regular[]; // bit indexed associative arrays


    integer regular[bit];
    integer map[string]; 

Smart Queues :

http://testbench.in/OV_02_DATA_TYPES.html[9/26/2012 2:45:02 PM]


WWW.TESTBENCH.IN - Vera Constructs

Smart Queue is a sequence / deque / vector of homogeneous elements. Smart queues


can be used to model a last in, first out buffer or first in, first out buffer. This
supports insertion and deletion of elements from random locations using an index.

    integer queue_of_int[$]; //declare Smart Queue of integers


    queue_of_int.push_front(1234); //inseqting 1234 into queue

Class :

 The user-defined data type, class, is composed of data members of valid OpenVera
data types (known as properties) and tasks or functions (known as methods) for
manipulating the data members.The properties and methods, taken together, define
the contents and capabilities of a class instance or object.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OV_02_DATA_TYPES.html[9/26/2012 2:45:02 PM]


WWW.TESTBENCH.IN - Vera Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS LINKED LIST Index


Linked List: Introduction
SystemVerilog Data Types
Verification OpenVera supports Linked list.It also supports object based Linked list also.First Linked List
declare the Linked list type and then take instances of it.OpenVera has many Operators Part 1
Constructs methodes to operate on this instancess. Operators Part 2
Interface Operators Part 3
List Definitions: Operator Precedence
OOPS Control Statements
Randomization List :- A list is a doubly linked list, where every element has a predecessor and Procedures And Methods
successor. It is a sequence that supports both forward and backward traversal, as well Interprocess
Functional Coverage Fork Join
as amortized constant time insertion and removal of elements at the beginning, end,
Assertion or middle. Shadow Variables
Fork Join Control
DPI Wait Var
Container :- A container is a collection of objects of the same type .Containers are
UVM Tutorial objects that contain and manage other objects and provide iterators that allow the Event Sync
contained objects (elements) to be addressed. A container has methods for accessing Event Trigger
VMM Tutorial Semaphore
its elements. Every container has an associated iterator type that can be used to
OVM Tutorial iterate through the container´s elements. Regions
Mailbox
Easy Labs : SV
Cterator :- Iterators provide the interface to containers. They also provide a means to Timeouts
Easy Labs : UVM traverse the container elements. Iterators are pointers to nodes within a list. If an Oop
iterator points to an object in a range of objects and the iterator is incremented, the Casting
Easy Labs : OVM
iterator then points to the next object in the range. Randomization
Easy Labs : VMM Randomization Methods
AVM Switch TB The following procedure shouws how to creat List and use it: Constraint Block
1)Creat List: Constraint Expression
VMM Ethernet sample Variable Ordaring
MakeVeraList(data_type);
Aop
Predefined Methods
2)Declare Lists String Methods
Verilog VeraList_data_type list1; Queue Methods
Verification
Dut Communication
Verilog Switch TB 3)Declare List Iterators Functional Coverage
VeraListIterator_data_type iterator1;
Basic Constructs
Report a Bug or Comment
on This section - Your
List Methods: input is what keeps
OpenVera Testbench.in improving
Constructs
size()      : The size() method returns the number of elements in the list container. with time!
empty()     :The empty() method returns 1 if the number of elements in the list
Switch TB container is 0:
RVM Switch TB clear()     :The clear() method removes all the elements of the specified list.
erase()     :The erase() method removes the indicated element.
RVM Ethernet sample push_front():The push_front() method inserts data at the front of the list.
push_back() :The push_back() method inserts data at the end of the list.
pop_front() :The pop_front() method removes the first element of the list.
Specman E pop_back()  :The pop_back() method removes the last element of the list.
insert()    :The insert() method inserts data before the indicated position:
Interview Questions insert_range() :The insert_range() method inserts elements in a given range before
the indicated position.
start()     :The start() method returns an iterator pointing to the first element in the
list.
finish()    :The finish() method returns an iterator pointing to the very end of the list.
next()      :The next() method moves the iterator so that it points to the next item in
the list.
prev()      :The prev() method moves the iterator so that it points to the previous item
in the list.
eq()        :The eq() method compares two iterators.
neq()       :The neq() method compares two iterators.

http://testbench.in/OV_03_LINKED_LIST.html[9/26/2012 2:45:12 PM]


WWW.TESTBENCH.IN - Vera Constructs

front()     :The front() method returns the first element in the list.
back()      :The back() method returns the last element in the list.
data()      :The data() method returns the data stored at a particular location:

EXAMPLE:Linked list
#include <VeraListProgram.vrh>
#include <ListMacros.vrh>

MakeVeraList(integer);
program main{

    VeraList_integer List1;
    VeraListIterator_integer  itor;

    List1 = new();
    printf (" size of list is %d \n",List1.size());
    List1.push_back(10);
    List1.push_front(22);
    printf (" size of list is %d \n",List1.size());
    printf (" poping from list : %d \n",List1.front());
    printf (" poping from list : %d \n",List1.front());
    List1.pop_front();
    List1.pop_front();
    printf (" size of list is %d \n",List1.size());
    List1.push_back(5);
    List1.push_back(55);
    List1.push_back(555);
    List1.push_back(5555);
    printf (" size of list is %d \n",List1.size());
    
    itor = List1.start();
    printf (" startn of list %d \n",itor.data());
    itor.next();
    printf (" second element of list is %d \n",itor.data());
    itor.next();
    printf (" third element of list is %d \n",itor.data());
    itor.next();
    printf (" fourth element of list is %d \n",itor.data());
    
    itor = List1.erase(itor);
    printf (" after erasing element,the itor element of list is %d \n",itor.data());
    itor.prev();
    printf(" prevoious element is %d \n",itor.data());
    
    printf (" END OF PROGRAM\n");
}

RESULTS:

 size of list is 0
 size of list is 2
 poping from list : 22
 poping from list : 22
 size of list is 0
 size of list is 4
 startn of list 5
 second element of list is 55

http://testbench.in/OV_03_LINKED_LIST.html[9/26/2012 2:45:12 PM]


WWW.TESTBENCH.IN - Vera Constructs

 third element of list is 555


 fourth element of list is 5555
 after erasing element,the itor element of list is x
 prevoious element is 555
 END OF PROGRAM

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OV_03_LINKED_LIST.html[9/26/2012 2:45:12 PM]


WWW.TESTBENCH.IN - Vera Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS OPERATORS PART 1 Index


Operators : Introduction
SystemVerilog Data Types
Verification   Concatenation Linked List
Operators Part 1
Constructs   Arithmetic Operators Operators Part 2
  Relational Operators Operators Part 3
Interface
  Equality Operators Operator Precedence
OOPS   Logical Operators Control Statements
Randomization   Bit-wise Operators Procedures And Methods
  Reduction Operators Interprocess
Functional Coverage Fork Join
  Shift Operators
Assertion Shadow Variables
  Increment and Decrement Operators
Fork Join Control
DPI   Conditional Operator Wait Var
UVM Tutorial Event Sync
Concatenation : Event Trigger
VMM Tutorial Semaphore
OVM Tutorial
 {} concatenation right of assignment. Regions
´{} concatenation left of assignment. Mailbox
Easy Labs : SV
Timeouts
Easy Labs : UVM Oop
Casting
Easy Labs : OVM EXAMPLE :Concatenation   Randomization
Easy Labs : VMM program main {                               Randomization Methods
    bit [4:0] a;                                 Constraint Block
AVM Switch TB     bit b,c,d;                                   Constraint Expression
VMM Ethernet sample     b = 0;                                       Variable Ordaring
    c = 1;                                       Aop
    d = 1;                                       Predefined Methods
    a = {b,c,0,0,d};                             String Methods
Verilog     `{b,c,d} = 3'b111;                           Queue Methods
Verification     printf(" a %b b %b c %b d %b ",a,b,c,d);     Dut Communication
Verilog Switch TB } Functional Coverage
Basic Constructs  RESULTS
Report a Bug or Comment
on This section - Your
a 00001 b 1 c 1 d 1  
input is what keeps
OpenVera Testbench.in improving
              
Constructs with time!
 
Switch TB Arithmetic:
RVM Switch TB
# -                unary arithmetic (negative)
RVM Ethernet sample # +, -, *, /       binary arithmetic
# %                modulus

Specman E
Interview Questions  EXAMPLE :Arithmetic    
 program main {                            
      integer a,b;                              
      b = 10;                                  
      a = 22;                                  
                                                
      printf(" -(nagetion)   is %0d  \n",-(a) ); 
      printf(" a + b  is %0d    \n",a+b);      
      printf(" a - b  is %0d    \n",a-b);      
      printf(" a * b  is %0d    \n",a*b);      
      printf(" a / b  is %0d    \n",a/b);      

http://testbench.in/OV_04_OPERATORS_PART_1.html[9/26/2012 2:45:22 PM]


WWW.TESTBENCH.IN - Vera Constructs

      printf(" a modulus b  is %0d    \n",a%b); 


                                                
 }                                        

 RESULTS

  -(nagetion)   is -22      
  a + b  is 32              
  a - b  is 12              
  a * b  is 220            
  a / b  is 2              
  a modules b is 2          

      

Relational:

# > >= < <=        relational

EXAMPLE :Relational
program main {
    integer a,b;
    b = 10;
    a = 22;
    
    printf(" a < b  is %0d    \n",a < b);
    printf(" a > b  is %0d    \n",a >b);
    printf(" a <= b  is %0d    \n",a <= b);
    printf(" a >= b  is %0d    \n",a >= b);

}
RESULTS

 a < b  is 0
 a > b  is 1
 a <= b  is 0
 a >= b  is 1

Equality:

==               logical equality


!=               logical inequality
===              case equality
!==              case inequality
=?=              wildcard equality
!?=              wildcard inequality

EXAMPLE :logical Equality


    reg[3:0] a;
    reg[7:0] x, y, z;
    a = 4'b0101;
    x = 8'b1000_0101;
    y = 8'b0000_0101;
    z = 8'b0xx0_0101;

http://testbench.in/OV_04_OPERATORS_PART_1.html[9/26/2012 2:45:22 PM]


WWW.TESTBENCH.IN - Vera Constructs

    if (x == a)
        printf("x equals a is TRUE.\n");
    if (y == a)
        printf("y equals a is TRUE.\n");
    if (z == a)
        printf("z equals a is TRUE.\n");
RESULTS

y equals a is TRUE.

EXAMPLE : Case equality


program main {
reg a_1,a_0,a_x,a_z;
reg b_1,b_0,b_x,b_z;
a_1 = 'b1;a_0 = 'b0;a_x = 'bx;a_z = 'bz;
b_1 = 'b1;b_0 = 'b0;b_x = 'bx;b_z = 'bz;
printf("--------------------------\n");
printf (" ==    0    1    x    z  \n");
printf("--------------------------\n");
printf (" 0     %b   %b   %b   %b \n",a_0 == b_0,a_0 == b_1,a_0 == b_x,a_0 == b_z);
printf (" 1     %b   %b   %b   %b \n",a_1 == b_0,a_1 == b_1,a_1 == b_x,a_1 == b_z);
printf (" x     %b   %b   %b   %b \n",a_x == b_0,a_x == b_1,a_x == b_x,a_x == b_z);
printf (" z     %b   %b   %b   %b \n",a_z == b_0,a_z == b_1,a_z == b_x,a_z == b_z);
printf("--------------------------\n");
printf("--------------------------\n");
printf (" ===   0    1    x    z  \n");
printf("--------------------------\n");
printf (" 0     %b   %b   %b   %b \n",a_0 === b_0,a_0 === b_1,a_0 === b_x,a_0 === b_z);
printf (" 1     %b   %b   %b   %b \n",a_1 === b_0,a_1 === b_1,a_1 === b_x,a_1 === b_z);
printf (" x     %b   %b   %b   %b \n",a_x === b_0,a_x === b_1,a_x === b_x,a_x === b_z);
printf (" z     %b   %b   %b   %b \n",a_z === b_0,a_z === b_1,a_z === b_x,a_z === b_z);
printf("--------------------------\n");
printf("--------------------------\n");
printf (" =?=   0    1    x    z  \n");
printf("--------------------------\n");
printf (" 0     %b   %b   %b   %b \n",a_0 =?= b_0,a_0 =?= b_1,a_0 =?= b_x,a_0 =?= b_z);
printf (" 1     %b   %b   %b   %b \n",a_1 =?= b_0,a_1 =?= b_1,a_1 =?= b_x,a_1 =?= b_z);
printf (" x     %b   %b   %b   %b \n",a_x =?= b_0,a_x =?= b_1,a_x =?= b_x,a_x =?= b_z);
printf (" z     %b   %b   %b   %b \n",a_z =?= b_0,a_z =?= b_1,a_z =?= b_x,a_z =?= b_z);
printf("--------------------------\n");
printf("--------------------------\n");
printf (" !=    0    1    x    z  \n");
printf("--------------------------\n");
printf (" 0     %b   %b   %b   %b \n",a_0 != b_0,a_0  != b_1,a_0  != b_x,a_0  != b_z);
printf (" 1     %b   %b   %b   %b \n",a_1 != b_0,a_1  != b_1,a_1  != b_x,a_1  != b_z);
printf (" x     %b   %b   %b   %b \n",a_x != b_0,a_x  != b_1,a_x  != b_x,a_x  != b_z);
printf (" z     %b   %b   %b   %b \n",a_z != b_0,a_z  != b_1,a_z  != b_x,a_z  != b_z);
printf("--------------------------\n");
printf("--------------------------\n");
printf (" !==   0    1    x    z  \n");
printf("--------------------------\n");
printf (" 0     %b   %b   %b   %b \n",a_0 !== b_0,a_0 !== b_1,a_0 !== b_x,a_0 !== b_z);
printf (" 1     %b   %b   %b   %b \n",a_1 !== b_0,a_1 !== b_1,a_1 !== b_x,a_1 !== b_z);
printf (" x     %b   %b   %b   %b \n",a_x !== b_0,a_x !== b_1,a_x !== b_x,a_x !== b_z);
printf (" z     %b   %b   %b   %b \n",a_z !== b_0,a_z !== b_1,a_z !== b_x,a_z !== b_z);
printf("--------------------------\n");
printf("--------------------------\n");
printf (" !?=   0    1    x    z  \n");
printf("--------------------------\n");
printf (" 0     %b   %b   %b   %b \n",a_0 !?= b_0,a_0 !?= b_1,a_0 !?= b_x,a_0 !?= b_z);
printf (" 1     %b   %b   %b   %b \n",a_1 !?= b_0,a_1 !?= b_1,a_1 !?= b_x,a_1 !?= b_z);
printf (" x     %b   %b   %b   %b \n",a_x !?= b_0,a_x !?= b_1,a_x !?= b_x,a_x !?= b_z);
printf (" z     %b   %b   %b   %b \n",a_z !?= b_0,a_z !?= b_1,a_z !?= b_x,a_z !?= b_z);
printf("--------------------------\n");
}

RESULTS

--------------------------
 ==    0    1    x    z
--------------------------
 0     1   0   x   x
 1     0   1   x   x
 x     x   x   x   x

http://testbench.in/OV_04_OPERATORS_PART_1.html[9/26/2012 2:45:22 PM]


WWW.TESTBENCH.IN - Vera Constructs

 z     x   x   x   x


--------------------------
--------------------------
 ===   0    1    x    z
--------------------------
 0     1   0   0   0
 1     0   1   0   0
 x     0   0   1   0
 z     0   0   0   1
--------------------------
--------------------------
 =?=   0    1    x    z
--------------------------
 0     1   0   1   1
 1     0   1   1   1
 x     1   1   1   1
 z     1   1   1   1
--------------------------
--------------------------
 !=    0    1    x    z
--------------------------
 0     0   1   x   x
 1     1   0   x   x
 x     x   x   x   x
 z     x   x   x   x
--------------------------
--------------------------
 !==   0    1    x    z
--------------------------
 0     0   1   1   1
 1     1   0   1   1
 x     1   1   0   1
 z     1   1   1   0
--------------------------
--------------------------
 !?=   0    1    x    z
--------------------------
 0     0   1   0   0
 1     1   0   0   0
 x     0   0   0   0
 z     0   0   0   0
--------------------------

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OV_04_OPERATORS_PART_1.html[9/26/2012 2:45:22 PM]


WWW.TESTBENCH.IN - Vera Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS OPERATORS PART 2 Index


Logical : Introduction
SystemVerilog Data Types
Verification # !                logical negation Linked List
# &&               logical and Operators Part 1
Constructs # ||               logical or Operators Part 2
Interface Operators Part 3
Operator Precedence
OOPS Control Statements
EXAMPLE : Logical
Randomization program main { Procedures And Methods
reg a_1,a_0,a_x,a_z; Interprocess
Functional Coverage Fork Join
reg b_1,b_0,b_x,b_z;
Assertion a_1 = 'b1;a_0 = 'b0;a_x = 'bx;a_z = 'bz; Shadow Variables
b_1 = 'b1;b_0 = 'b0;b_x = 'bx;b_z = 'bz; Fork Join Control
DPI Wait Var
printf("--------------------------\n");
UVM Tutorial printf (" &&   0   1   x   z  \n"); Event Sync
printf("--------------------------\n"); Event Trigger
VMM Tutorial Semaphore
printf (" 0     %b   %b   %b   %b \n",a_0 && b_0,a_0 && b_1,a_0 && b_x,a_0 && b_z);
OVM Tutorial printf (" 1     %b   %b   %b   %b \n",a_1 && b_0,a_1 && b_1,a_1 && b_x,a_1 && b_z); Regions
printf (" x     %b   %b   %b   %b \n",a_x && b_0,a_x && b_1,a_x && b_x,a_x && b_z); Mailbox
Easy Labs : SV
printf (" z     %b   %b   %b   %b \n",a_z && b_0,a_z && b_1,a_z && b_x,a_z && b_z); Timeouts
Easy Labs : UVM printf("--------------------------\n"); Oop
printf("--------------------------\n"); Casting
Easy Labs : OVM
printf (" ||   0   1   x   z  \n"); Randomization
Easy Labs : VMM printf("--------------------------\n"); Randomization Methods
AVM Switch TB printf (" 0     %b   %b   %b   %b \n",a_0 || b_0,a_0 || b_1,a_0 || b_x,a_0 || b_z); Constraint Block
printf (" 1     %b   %b   %b   %b \n",a_1 || b_0,a_1 || b_1,a_1 || b_x,a_1 || b_z); Constraint Expression
VMM Ethernet sample printf (" x     %b   %b   %b   %b \n",a_x || b_0,a_x || b_1,a_x || b_x,a_x || b_z); Variable Ordaring
printf (" z     %b   %b   %b   %b \n",a_z || b_0,a_z || b_1,a_z || b_x,a_z || b_z); Aop
printf("--------------------------\n"); Predefined Methods
Verilog printf("--------------------------\n"); String Methods
printf (" !   0   1   x   z  \n"); Queue Methods
Verification
printf("--------------------------\n"); Dut Communication
Verilog Switch TB printf ("     %b   %b   %b   %b \n",!b_0,!b_1,!b_x,!b_z); Functional Coverage
Basic Constructs printf("--------------------------\n");
} Report a Bug or Comment
RESULTS on This section - Your
input is what keeps
OpenVera -------------------------- Testbench.in improving
Constructs  &&   0   1   x   z with time!
Switch TB --------------------------
 0     0   0   0   0
RVM Switch TB  1     0   1   0   1
RVM Ethernet sample  x     0   0   0   0
 z     0   1   0   1
--------------------------
--------------------------
Specman E  ||   0   1   x   z
Interview Questions --------------------------
 0     0   1   0   1
 1     1   1   1   1
 x     0   1   0   1
 z     1   1   1   1
--------------------------
--------------------------
 !   0   1   x   z
--------------------------
     1   0   x   x
--------------------------

http://testbench.in/OV_05_OPERATORS_PART_2.html[9/26/2012 2:45:32 PM]


WWW.TESTBENCH.IN - Vera Constructs

Bitwise :

# ~                bitwise negation (unary)


# &                bitwise and (binary)
# &~               bitwise nand (binary)
# |                bitwise or (binary)
# |~               bitwise nor (binary)
# ^                bitwise exclusive or (binary)
# ^~               bitwise exclusive nor (binary)

EXAMPLE : Bitwise
program main {
reg a_1,a_0,a_x,a_z;
reg b_1,b_0,b_x,b_z;
a_1 = 'b1;a_0 = 'b0;a_x = 'bx;a_z = 'bz;
b_1 = 'b1;b_0 = 'b0;b_x = 'bx;b_z = 'bz;

printf("--------------------------\n");
printf (" ~   0   1   x   z  \n");
printf("--------------------------\n");
printf ("     %b   %b   %b   %b \n",~b_0,~b_1,~b_x,~b_z);
printf("--------------------------\n");
printf("--------------------------\n");
printf (" &   0   1   x   z  \n");
printf("--------------------------\n");
printf (" 0     %b   %b   %b   %b \n",a_0 & b_0,a_0 & b_1,a_0 & b_x,a_0 & b_z);
printf (" 1     %b   %b   %b   %b \n",a_1 & b_0,a_1 & b_1,a_1 & b_x,a_1 & b_z);
printf (" x     %b   %b   %b   %b \n",a_x & b_0,a_x & b_1,a_x & b_x,a_x & b_z);
printf (" z     %b   %b   %b   %b \n",a_z & b_0,a_z & b_1,a_z & b_x,a_z & b_z);
printf("--------------------------\n");
printf("--------------------------\n");
printf (" &~   0   1   x   z  \n");
printf("--------------------------\n");
printf (" 0     %b   %b   %b   %b \n",a_0 &~ b_0,a_0 &~ b_1,a_0 &~ b_x,a_0 &~ b_z);
printf (" 1     %b   %b   %b   %b \n",a_1 &~ b_0,a_1 &~ b_1,a_1 &~ b_x,a_1 &~ b_z);
printf (" x     %b   %b   %b   %b \n",a_x &~ b_0,a_x &~ b_1,a_x &~ b_x,a_x &~ b_z);
printf (" z     %b   %b   %b   %b \n",a_z &~ b_0,a_z &~ b_1,a_z &~ b_x,a_z &~ b_z);
printf("--------------------------\n");
printf("--------------------------\n");
printf (" |   0   1   x   z  \n");
printf("--------------------------\n");
printf (" 0     %b   %b   %b   %b \n",a_0 | b_0,a_0 | b_1,a_0 | b_x,a_0 | b_z);
printf (" 1     %b   %b   %b   %b \n",a_1 | b_0,a_1 | b_1,a_1 | b_x,a_1 | b_z);
printf (" x     %b   %b   %b   %b \n",a_x | b_0,a_x | b_1,a_x | b_x,a_x | b_z);
printf (" z     %b   %b   %b   %b \n",a_z | b_0,a_z | b_1,a_z | b_x,a_z | b_z);
printf("--------------------------\n");
printf (" |~   0   1   x   z  \n");
printf("--------------------------\n");
printf (" 0     %b   %b   %b   %b \n",a_0 |~ b_0,a_0 |~ b_1,a_0 |~ b_x,a_0 |~ b_z);
printf (" 1     %b   %b   %b   %b \n",a_1 |~ b_0,a_1 |~ b_1,a_1 |~ b_x,a_1 |~ b_z);
printf (" x     %b   %b   %b   %b \n",a_x |~ b_0,a_x |~ b_1,a_x |~ b_x,a_x |~ b_z);
printf (" z     %b   %b   %b   %b \n",a_z |~ b_0,a_z |~ b_1,a_z |~ b_x,a_z |~ b_z);
printf("--------------------------\n");
printf("--------------------------\n");
printf (" ^   0   1   x   z  \n");
printf("--------------------------\n");

http://testbench.in/OV_05_OPERATORS_PART_2.html[9/26/2012 2:45:32 PM]


WWW.TESTBENCH.IN - Vera Constructs

printf (" 0     %b   %b   %b   %b \n",a_0 ^ b_0,a_0 ^ b_1,a_0 ^ b_x,a_0 ^ b_z);
printf (" 1     %b   %b   %b   %b \n",a_1 ^ b_0,a_1 ^ b_1,a_1 ^ b_x,a_1 ^ b_z);
printf (" x     %b   %b   %b   %b \n",a_x ^ b_0,a_x ^ b_1,a_x ^ b_x,a_x ^ b_z);
printf (" z     %b   %b   %b   %b \n",a_z ^ b_0,a_z ^ b_1,a_z ^ b_x,a_z ^ b_z);
printf("--------------------------\n");
printf (" ^~   0   1   x   z  \n");
printf("--------------------------\n");
printf (" 0     %b   %b   %b   %b \n",a_0 ^~ b_0,a_0 ^~ b_1,a_0 ^~ b_x,a_0 ^~ b_z);
printf (" 1     %b   %b   %b   %b \n",a_1 ^~ b_0,a_1 ^~ b_1,a_1 ^~ b_x,a_1 ^~ b_z);
printf (" x     %b   %b   %b   %b \n",a_x ^~ b_0,a_x ^~ b_1,a_x ^~ b_x,a_x ^~ b_z);
printf (" z     %b   %b   %b   %b \n",a_z ^~ b_0,a_z ^~ b_1,a_z ^~ b_x,a_z ^~ b_z);
printf("--------------------------\n");
}
RESULTS

--------------------------
 ~   0   1   x   z
--------------------------
     1   0   x   x
--------------------------
--------------------------
 &   0   1   x   z
--------------------------
 0     0   0   0   0
 1     0   1   x   x
 x     0   x   x   x
 z     0   x   x   x
--------------------------
--------------------------
 &~   0   1   x   z
--------------------------
 0     1   1   1   1
 1     1   0   x   x
 x     1   x   x   x
 z     1   x   x   x
--------------------------
--------------------------
 |   0   1   x   z
--------------------------
 0     0   1   x   x
 1     1   1   1   1
 x     x   1   x   x
 z     x   1   x   x
--------------------------
 |~   0   1   x   z
--------------------------
 0     1   0   x   x
 1     0   0   0   0
 x     x   0   x   x
 z     x   0   x   x
--------------------------
--------------------------
 ^   0   1   x   z
--------------------------
 0     0   1   x   x
 1     1   0   x   x
 x     x   x   x   x
 z     x   x   x   x
--------------------------
 ^~   0   1   x   z
--------------------------
 0     1   0   x   x
 1     0   1   x   x
 x     x   x   x   x
 z     x   x   x   x
--------------------------

Reduction :

# &                unary and
# ~&               unary nand
# |                unary or
# ~|               unary nor

http://testbench.in/OV_05_OPERATORS_PART_2.html[9/26/2012 2:45:32 PM]


WWW.TESTBENCH.IN - Vera Constructs

# ^                unary exclusive or
# ~^               unary exclusive nor

EXAMPLE : Reduction
program main {
reg [3:0] a_1,a_0,a_01xz,a_1xz,a_0xz,a_0dd1,a_even1;
a_1     =  4'b1111 ;  
a_0     =  4'b0000 ;
a_01xz  =  4'b01xz ;
a_1xz   =  4'b11xz ;
a_0xz   =  4'b00xz ; 
a_0dd1  =  4'b1110 ;
a_even1 =  4'b1100 ;

printf("-------------------------------------------\n");
printf("     a_1   a_0   a_01xz   a_1xz     a_0xz  \n");
printf("-------------------------------------------\n");
printf("&     %b     %b     %b       %b       %b    \n",&a_1,&a_0,&a_01xz,&a_1xz,&a_0xz);
printf("|     %b     %b     %b       %b       %b    \n",|a_1,|a_0,|a_01xz,|a_1xz,|a_0xz);
printf("~&    %b     %b     %b       %b      
%b    \n",~&a_1,~&a_0,~&a_01xz,~&a_1xz,~&a_0xz);
printf("~|    %b     %b     %b       %b      
%b    \n",~|a_1,~|a_0,~|a_01xz,~|a_1xz,~|a_0xz);
printf("-------------------------------------------\n");
printf("          a_ood1   a_even1  a_1xz\n");
printf("-------------------------------------------\n");
printf(" ^           %b       %b        %b      \n",^a_0dd1,^a_even1,^a_1xz);
printf(" ~^          %b       %b        %b      \n",~^a_0dd1,~^a_even1,~^a_1xz);
printf("-------------------------------------------\n");

}
RESULTS

-------------------------------------------
     a_1   a_0   a_01xz   a_1xz     a_0xz
-------------------------------------------
&     1     0     0       x       0
|     1     0     1       1       x
~&    0     1     1       x       1
~|    0     1     0       0       x
-------------------------------------------
          a_ood1   a_even1  a_1xz
-------------------------------------------
 ^           1       0        x
 ~^          0       1        x
-------------------------------------------

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OV_05_OPERATORS_PART_2.html[9/26/2012 2:45:32 PM]


WWW.TESTBENCH.IN - Vera Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS OPERATORS PART 3 Index


Shift : Introduction
SystemVerilog Data Types
Verification # <<               left shift Linked List
# >>               right shift Operators Part 1
Constructs Operators Part 2
Interface EXAMPLE :Shift Operators Part 3
program main { Operator Precedence
OOPS Control Statements
   reg [3:0] a_1,a_0;
Randomization    a_1     =  4'b1100 ;   Procedures And Methods
   a_0     =  4'b0011 ; Interprocess
Functional Coverage Fork Join
Assertion printf(" << by 1  a_1  is %b a_0 is %b \n ",a_1 << 1,a_0 << 1); Shadow Variables
printf(" >> by 2  a_1  is %b a_0 is %b \n ",a_1 >> 2,a_0 >> 2); Fork Join Control
DPI Wait Var
printf(" >> by 2  a_1  is %b a_0 is %b \n ",a_1 >> 2,a_0 >> 2);
UVM Tutorial printf(" << by 1  a_1  is %b a_0 is %b \n ",a_1 << 1,a_0 << 1); Event Sync
  Event Trigger
VMM Tutorial Semaphore
}
OVM Tutorial RESULTS Regions
Mailbox
Easy Labs : SV
 << by 1  a_1  is 1000 a_0 is 0110 Timeouts
Easy Labs : UVM   >> by 2  a_1  is 0011 a_0 is 0000 Oop
  >> by 2  a_1  is 0011 a_0 is 0000 Casting
Easy Labs : OVM
  << by 1  a_1  is 1000 a_0 is 0110 Randomization
Easy Labs : VMM Randomization Methods
AVM Switch TB Constraint Block
Bit-Reverse : Constraint Expression
VMM Ethernet sample Variable Ordaring
><               bit reverse Aop
Predefined Methods
Verilog EXAMPLE : Bit-reverse String Methods
program main { Queue Methods
Verification
    reg [3:0] a_1,a_0; Dut Communication
Verilog Switch TB     a_1     =  4'b1100 ;   Functional Coverage
Basic Constructs     
    printf(" >< a_1  is %b  \n ",><a_1 ); Report a Bug or Comment
} on This section - Your
RESULTS input is what keeps
OpenVera Testbench.in improving
Constructs >< a_1  is 0011 with time!
Switch TB
RVM Switch TB Increment And Decrement :
RVM Ethernet sample
++               increment
--               decrement
Specman E
EXAMPLE : Increment and Decrement
Interview Questions program main {
    integer a_1,a_0;
    a_1  = 20 ;  
    a_0  = 20 ;
    a_1 ++ ;
    a_0 -- ;
    printf (" a_1 is %d a_0 is %d ",a_1,a_0);
}
RESULTS

a_1 is 21 a_0 is 19

http://testbench.in/OV_06_OPERATORS_PART_3.html[9/26/2012 2:45:42 PM]


WWW.TESTBENCH.IN - Vera Constructs

Conditional :

?:               conditional

EXAMPLE : Conditional
program main {
    integer i,j,sub;
    for (i=0; i<3; i++)
    for (j=3; j>0; j--){
        sub = (i>j) ? i-j : j-i;
        printf("i = %0d\t j = %0d\tsub = %0d\n", i,j,sub);
    }
}
RESULTS

i= 0    j = 3  sub = 3
i= 0    j = 2  sub = 2
i= 0    j = 1  sub = 1
i= 1    j = 3  sub = 2
i= 1    j = 2  sub = 1
i= 1    j = 1  sub = 0
i= 2    j = 3  sub = 1
i= 2    j = 2  sub = 0
i= 2    j = 1  sub = 1

Set

in !in dist

EXAMPLE : Set
program main {
    integer i;
    i = 20;
    if( i in {10,20,30})
        printf(" I is in 10 20 30 ");
}
RESULTS

I is in 10 20 30

Replication :

  { number {}}

EXAMPLE : Replication
program main {
    reg [5:0]  i;
    i = { 3{2'b10}};
    printf(" I is %b ",i);
}

RESULTS

I is 101010

http://testbench.in/OV_06_OPERATORS_PART_3.html[9/26/2012 2:45:42 PM]


WWW.TESTBENCH.IN - Vera Constructs

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OV_06_OPERATORS_PART_3.html[9/26/2012 2:45:42 PM]


WWW.TESTBENCH.IN - Vera Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS OPERATOR PRECEDENCE Index


Operator Precedence : Introduction
SystemVerilog Data Types
Verification Linked List
  ()                            Highest precedence Operators Part 1
Constructs Operators Part 2
  ++ -- Operators Part 3
Interface   & ~& | ~| ^ ~^ ~ >< - Operator Precedence
OOPS   (unary) Control Statements
Randomization   * / % Procedures And Methods
  + - Interprocess
Functional Coverage Fork Join
  << >>
Assertion   < <= > >= in !in dist Shadow Variables
Fork Join Control
DPI   =?= !?= == != === !==
Wait Var
  & &~ Event Sync
UVM Tutorial
  ^ ^~ Event Trigger
VMM Tutorial   | |~ Semaphore
OVM Tutorial   && Regions
  || Mailbox
Easy Labs : SV
  ?: Timeouts
Easy Labs : UVM   = += -= *= /= %= Oop
Casting
Easy Labs : OVM   <<= >>= &= |= ^= ~&= ~|= ~^=  Lowest precedence Randomization
Easy Labs : VMM Randomization Methods
AVM Switch TB Constraint Block
Constraint Expression
VMM Ethernet sample Variable Ordaring
Aop
Predefined Methods
Verilog String Methods
Queue Methods
Verification
Dut Communication
Verilog Switch TB Functional Coverage
Basic Constructs
Report a Bug or Comment
on This section - Your
input is what keeps
OpenVera Testbench.in improving
Constructs with time!
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/OV_07_OPERATOR_PRECEDENCE.html[9/26/2012 2:45:49 PM]


WWW.TESTBENCH.IN - Vera Constructs

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OV_07_OPERATOR_PRECEDENCE.html[9/26/2012 2:45:49 PM]


WWW.TESTBENCH.IN - Vera Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS CONTROL STATEMENTS Index


Sequential Statements: Introduction
SystemVerilog Data Types
Verification Statements inside sequential control constructs are executed sequentially. Linked List
Operators Part 1
Constructs Operators Part 2
if-else Statement  :  The if-else statement is the general form of selection
Interface statement. Operators Part 3
Operator Precedence
OOPS Control Statements
case Statement     :  The case statement provides for multi-way branching. Procedures And Methods
Randomization
Interprocess
Functional Coverage repeat loop        :  Repeat statements can be used to repeat the execution of a Fork Join
statement or statement block a fixed number of times. Shadow Variables
Assertion
Fork Join Control
DPI   for loop           :  The for construct can be used to create loops.   Wait Var
UVM Tutorial Event Sync
  while loop         :  The loop iterates while the condition is true. Event Trigger
VMM Tutorial Semaphore
OVM Tutorial   do-while           :  condition is checked after loop iteration.     Regions
Mailbox
Easy Labs : SV
  foreach            :ech construct specifies iteration over the elements of an single Timeouts
Easy Labs : UVM dimensional fixed-size arrays, dynamic arrays and SmartQs.     Oop
Casting
Easy Labs : OVM
  Loop Control       :  The break and continue statements are used for flow control Randomization
Easy Labs : VMM within loops.       Randomization Methods
AVM Switch TB Constraint Block
Constraint Expression
VMM Ethernet sample Variable Ordaring
EXAMPLE : if
program main { Aop
   integer i; Predefined Methods
Verilog    i = 20; String Methods
   if( i == 20) Queue Methods
Verification
   printf(" I is equal to %d ",i); Dut Communication
Verilog Switch TB    else Functional Coverage
Basic Constructs    printf(" I is not equal to %d ",i);
Report a Bug or Comment
}  on This section - Your
RESULTS input is what keeps
OpenVera Testbench.in improving
Constructs I is equal to 20 with time!
Switch TB
RVM Switch TB
RVM Ethernet sample EXAMPLE : case and repeat
program main {
integer i;
    
Specman E     repeat(10){
Interview Questions         i = random();
        case(1) {
        (i<0)   :printf(" i is less than zero i==%d\n",i);
        (i>0)   :printf(" i is grater than zero i=%d\n",i);
        (i == 0):printf(" i is equal to zero i=%d\n",i);
        }
    }
}
RESULTS

 i is grater than zero i=69120

http://testbench.in/OV_08_CONTROL_STATEMENTS.html[9/26/2012 2:45:58 PM]


WWW.TESTBENCH.IN - Vera Constructs

 i is grater than zero i=475628600


 i is grater than zero i=1129920902
 i is grater than zero i=773000284
 i is grater than zero i=1730349006
 i is grater than zero i=1674352583
 i is grater than zero i=1662201030
 i is grater than zero i=2044158707
 i is grater than zero i=1641506755
 i is grater than zero i=797919327

EXAMPLE : forloop
program for_loop
{
    integer count, i;
    for(count = 0, i=0; i*count<50; i++, count++)
    printf("Value i = %0d\n", i);
}

RESULTS

Value i = 0
Value i = 1
Value i = 2
Value i = 3
Value i = 4
Value i = 5
Value i = 6
Value i = 7

EXAMPLE : whileloop
program while_loop{
    integer operator=0;
    while (operator<5){
        operator += 1;
        printf("Operator is %0d\n", operator);
    }
}
RESULTS

Operator is 1
Operator is 2
Operator is 3
Operator is 4
Operator is 5

EXAMPLE : dowhile
program test
{
    integer i = 0;
    do
    {
        printf("i = %0d \n", i);
        i++;
    } while (i < 10);
}
RESULTS

http://testbench.in/OV_08_CONTROL_STATEMENTS.html[9/26/2012 2:45:58 PM]


WWW.TESTBENCH.IN - Vera Constructs

i= 0
i= 1
i= 2
i= 3
i= 4
i= 5
i= 6
i= 7
i= 8
i= 9

EXAMPLE : foeach
program example{
    string names[$]={"Hello", "Vera"};
    foreach (names, i) {
        printf("Value at index %0d is %0s\n", i, names[i]);
    }
}
RESULTS

Value at index 0 is Hello


Value at index 1 is Vera

EXAMPLE : randcase
program rand_case{
    integer i;
    repeat(10){
       randcase
       {
       10: i=1;
       20: i=2;
       50: i=3;
       }
    printf(" i is %d \n",i);}
}
RESULTS

 i is 3
 i is 2
 i is 3
 i is 3
 i is 3
 i is 3
 i is 1
 i is 1
 i is 1
 i is 2

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OV_08_CONTROL_STATEMENTS.html[9/26/2012 2:45:58 PM]


WWW.TESTBENCH.IN - Vera Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PROCEDURES AND METHODS Index


Procedures And Methods : Introduction
SystemVerilog Data Types
Verification OpenVera supports two means of encapsulating program fragments: Linked List
functions and tasks. All functions and tasks are re-entrant and Operators Part 1
Constructs therefore can be called recursively. Operators Part 2
Interface Operators Part 3
Function : Operator Precedence
OOPS Control Statements
Functions are provided for implementing operations containing arguments passed to
Randomization the function and one return value.Functions can return values of any valid data type Procedures And
as well as data structures. Methods
Functional Coverage Interprocess
Assertion Task     : Fork Join
Tasks are identical to functions except they do not return a value. Shadow Variables
DPI Fork Join Control
UVM Tutorial Subroutine Arguments : Wait Var
OpenVera provides two means of accessing arguments in functions and tasks: pass by Event Sync
VMM Tutorial Event Trigger
value and pass by reference.
OVM Tutorial Semaphore
Regions
Easy Labs : SV
Pass By Value : Mailbox
Easy Labs : UVM Timeouts
Pass by value is the default method through which arguments are passed into Oop
Easy Labs : OVM
functions and tasks. Each subroutine retains a local copy of the argument. If the Casting
Easy Labs : VMM arguments are changed within the subroutine declaration, the changes do not affect Randomization
AVM Switch TB the caller. Randomization Methods
Constraint Block
VMM Ethernet sample Constraint Expression
EXAMPLE : pass by value Variable Ordaring
program main{ Aop
Verilog     integer i; Predefined Methods
    i=0; String Methods
Verification
    fork  Queue Methods
Verilog Switch TB     pass(i); Dut Communication
    display(); Functional Coverage
Basic Constructs
    join
    printf("End of Program at %d\n",get_time(LO) ); Report a Bug or Comment
} on This section - Your
OpenVera input is what keeps
Constructs task pass(int i) { Testbench.in improving
     delay(10); with time!
Switch TB
     i = 1;
RVM Switch TB      printf(" i is changed to %d at %d\n",i,get_time(LO) );
RVM Ethernet sample      delay(10);
     i = 2;
     printf(" i is changed to %d at %d\n",i,get_time(LO) );
}
Specman E
Interview Questions task display(){
     delay(15);
     printf(" i is %d at %d\n",i,get_time(LO));
     delay(10);
     printf(" i is %d at %d\n",i,get_time(LO));
}

RESULTS

 i is changed to 1 at 10
 i is 0 at 15

http://testbench.in/OV_09_PROCEDURES_AND_METHODS.html[9/26/2012 2:46:07 PM]


WWW.TESTBENCH.IN - Vera Constructs

 i is changed to 2 at 20
 i is 0 at 25
End of Program at 25

Pass By Reference :

In pass by reference functions and tasks directly access the specified variables passed
as arguments.Its like passing pointer of the variable.

EXAMPLE : pass by reference


program main{
    integer i;
    i=0;
    fork 
    pass(i);
    display();
    join
    printf("End of Program at %d\n",get_time(LO) );
}

task pass(var int i) {
    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) );
}

task display(){
    delay(15);
    printf(" i is %d at %d\n",i,get_time(LO));
    delay(10);
    printf(" i is %d at %d\n",i,get_time(LO));
}

RESULTS

 i is changed to 1 at 10
 i is 1 at 15
 i is changed to 2 at 20
 i is 2 at 25
End of Program at 25

Default Arguments:

To handle common cases or allow for unused arguments, OpenVera allows you to
define default values for each scalar argument.When the subroutine is called, you can
omit an argument that has a default defined for it. Use an asterisk (*) as a
placeholder in the subroutine call.

EXAMPLE : Default Arguments:


task display(integer i = 0, integer k, reg[5:0] data = 6'b0)
{
    printf(" i si %d k is %d , datat is %b \n",i,k,data);
}

http://testbench.in/OV_09_PROCEDURES_AND_METHODS.html[9/26/2012 2:46:07 PM]


WWW.TESTBENCH.IN - Vera Constructs

program main{
    integer i;
    i=0;
    display(1,4,6);
    display(*,4,*);
    display(*,8,4);
}

RESULTS

 i si 1 k is 4 , datat is 000110
 i si 0 k is 4 , datat is 000000
 i si 0 k is 8 , datat is 000100

Optional Arguments:

To allow subroutines to evolve over time without having to change all of the existing
calls, OpenVera supports optional arguments.Optional arguments must have default
values.Any number of additional optional arguments can be created.Parentheses are
used to determine the depth level of an optional argument.

EXAMPLE : optional arguments


task my_task(integer a, ((integer b=1)), (integer c=1)){
   printf (" a is %d, b is %d c is %d\n",a,b,c);
}

program main{
    integer i;
    i=0;
    my_task(1,2,3);
    my_task(1);
    my_task(1,2);
}

RESULTS

 a is 1, b is 2 c is 3
 a is 1, b is 1 c is 1
 a is 1, b is 2 c is 1

Subroutine Termination :
Normally, functions and tasks return control to the caller after the last statement of
the block is executed. OpenVera provides the return statement to manually pass
control back to the caller.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OV_09_PROCEDURES_AND_METHODS.html[9/26/2012 2:46:07 PM]


WWW.TESTBENCH.IN - Vera Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INTERPROCESS Index


Interprocess Synchronization And Communication : Introduction
SystemVerilog Data Types
Verification OpenVera supports set of synchronization and communication mechanisms, all of Linked List
which can be created and reclaimed dynamically. Operators Part 1
Constructs Operators Part 2
Interface fork and join Statement Operators Part 3
Operator Precedence
OOPS wait_var() Control Statements
Event Methods Procedures And Methods
Randomization
Semaphores Interprocess
Functional Coverage Regions Fork Join
Assertion Mailboxes Shadow Variables
Timeout Limit Fork Join Control
DPI Wait Var
UVM Tutorial Event Sync
Event Trigger
VMM Tutorial Semaphore
OVM Tutorial Regions
Mailbox
Easy Labs : SV
Timeouts
Easy Labs : UVM Oop
Casting
Easy Labs : OVM
Randomization
Easy Labs : VMM Randomization Methods
AVM Switch TB Constraint Block
Constraint Expression
VMM Ethernet sample Variable Ordaring
Aop
Predefined Methods
Verilog String Methods
Queue Methods
Verification
Dut Communication
Verilog Switch TB Functional Coverage
Basic Constructs
Report a Bug or Comment
on This section - Your
input is what keeps
OpenVera Testbench.in improving
Constructs with time!
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/OV_10_INTERPROCESS.html[9/26/2012 2:46:14 PM]


WWW.TESTBENCH.IN - Vera Constructs

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OV_10_INTERPROCESS.html[9/26/2012 2:46:14 PM]


WWW.TESTBENCH.IN - Vera Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS FORK JOIN Index


Fork Join: Introduction
SystemVerilog Data Types
Verification Fork/join blocks provide the primary mechanism for creating concurrent Linked List
processes.The all | any | none options specify when the code after the fork/join block Operators Part 1
Constructs executes.The default is all. Operators Part 2
Interface Operators Part 3
all :: The default is all. Code after the block executes after all of the concurrent Operator Precedence
OOPS Control Statements
processes are completed.
Randomization any :: When any is used, code after the block executes after any single concurrent Procedures And Methods
process is completed. Interprocess
Functional Coverage Fork Join
none :: When none is used, code after the block executes immediately, without
Assertion waiting for any of the processes to complete. Shadow Variables
Fork Join Control
DPI Wait Var
UVM Tutorial Event Sync
Event Trigger
VMM Tutorial Semaphore
OVM Tutorial Regions
Mailbox
Easy Labs : SV
Timeouts
Easy Labs : UVM Oop
Casting
Easy Labs : OVM
Randomization
Easy Labs : VMM Randomization Methods
AVM Switch TB Constraint Block
Constraint Expression
VMM Ethernet sample Variable Ordaring
Aop
Predefined Methods
Verilog String Methods
Queue Methods
Verification
Dut Communication
Verilog Switch TB Functional Coverage
Basic Constructs
Report a Bug or Comment
on This section - Your
input is what keeps
OpenVera Testbench.in improving
Constructs with time!
Switch TB EXAMPLE : fork/join none
RVM Switch TB
program main {
RVM Ethernet sample  delay(10);

Specman E     printf(" BEFORE fork  time = %d \n",get_time(LO) ); 


    fork {
Interview Questions          delay (20);
         printf("time = %d delay 20 \n ",get_time(LO) );
         }
        {
         delay(10);
         printf("time = %d delay 10 \n ",get_time(LO) );
         }
        {
         delay(5);
         printf("time = %d delay 5 \n ",get_time(LO) );
        }

http://testbench.in/OV_11_FORK_JOIN.html[9/26/2012 2:46:23 PM]


WWW.TESTBENCH.IN - Vera Constructs

      join none
 printf(" time = %d Outside the main fork \n",get_time(LO) );
delay(40);

RESULTS

 BEFORE fork  time = 10
 time = 10 Outside the main fork
 time = 15 delay 5
 time = 20 delay 10
 time = 30 delay 20

EXAMPLE : fork/join any

program main {
 
 delay(10);

    printf(" BEFORE fork  time = %d \n",get_time(LO) ); 


    fork {
         delay (20);
         printf("time = %d delay 20 \n ",get_time(LO) );
         }
        {
         delay(10);
         printf("time = %d delay 10 \n ",get_time(LO) );
         }
        {
         delay(5);
         printf("time = %d delay 5 \n ",get_time(LO) );
        }
      join any
 printf(" time = %d Outside the main fork \n",get_time(LO) );
delay(40);

RESULTS

BEFORE fork  time = 10
time = 15 delay 5
  time = 15 Outside the main fork
time = 20 delay 10
 time = 30 delay 20

EXAMPLE : fork/join all

program main {
                                                                                                                            
 delay(10);
                                                                                                                            
    printf(" BEFORE fork  time = %d \n",get_time(LO) );
    fork {
         delay (20);
         printf("time = %d delay 20 \n ",get_time(LO) );
         }
        {

http://testbench.in/OV_11_FORK_JOIN.html[9/26/2012 2:46:23 PM]


WWW.TESTBENCH.IN - Vera Constructs

         delay(10);
         printf("time = %d delay 10 \n ",get_time(LO) );
         }
        {
         delay(5);
         printf("time = %d delay 5 \n ",get_time(LO) );
        }
      join all
 printf(" time = %d Outside the main fork \n",get_time(LO) );
delay(40);
}

RESULTS

BEFORE fork  time = 10
time = 15 delay 5
time = 20 delay 10
time = 30 delay 20
time = 30 Outside the main fork

When defining a fork/join block, encapsulating the entire fork inside braces ({})
results in the entire block being treated as a single thread, and the code executes
consecutively.

EXAMPLE : sequential statement in fork/join

program main {
 delay(10);

    printf(" First fork  time = %d \n",get_time(LO) ); 


    fork {
         delay (20);
         printf("time = %d delay 20 \n ",get_time(LO),i);
         }
        {
         delay(10);
         printf("time = %d delay 10 \n ",get_time(LO),j);
         }
        {
         delay(5);
         printf("time = %d delay 5 \n ",get_time(LO),m);
         delay(2);
         printf("time = %d delay 2 \n ",get_time(LO),m);

        }
      join any
  printf(" time = %d Outside the main fork \n",get_time(LO) );

delay(40);

RESULTS

First fork  time = 10
time = 15 delay 5
time = 17 delay 2
time = 17 Outside the main fork
time = 20 delay 10
time = 30 delay 20

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/OV_11_FORK_JOIN.html[9/26/2012 2:46:23 PM]


WWW.TESTBENCH.IN - Vera Constructs

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OV_11_FORK_JOIN.html[9/26/2012 2:46:23 PM]


WWW.TESTBENCH.IN - Vera Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS SHADOW VARIABLES Index


Shadow Variables Introduction
SystemVerilog Data Types
Verification By default, all child processes have access to the parent´s variables.However, if Linked List
multiple processes independently use the same variable,races can occur. To avoid Operators Part 1
Constructs races within fork/join blocks, shadow variables should be used. Operators Part 2
Interface Operators Part 3
EXAMPLE : without shadow variable Operator Precedence
OOPS Control Statements
Randomization program main {  Procedures And Methods
call(); Interprocess
Functional Coverage Fork Join
delay(40);
Assertion printf(" END OF SIMUALTION \n"); Shadow Variables
} Fork Join Control
DPI Wait Var
UVM Tutorial task call(){ Event Sync
integer i; Event Trigger
VMM Tutorial Semaphore
delay(10);
OVM Tutorial for(i = 0; i < 3; i++) { Regions
    fork Mailbox
Easy Labs : SV
    { Timeouts
Easy Labs : UVM     delay(10);   Oop
     printf(" time = %0d: i is %0d \n",get_time(LO),i); Casting
Easy Labs : OVM
    } Randomization
Easy Labs : VMM    join none  Randomization Methods
AVM Switch TB } Constraint Block
} Constraint Expression
VMM Ethernet sample Variable Ordaring
Aop
RESULTS Predefined Methods
Verilog String Methods
time = 20: i is 3 Queue Methods
Verification
time = 20: i is 3 Dut Communication
Verilog Switch TB time = 20: i is 3 Functional Coverage
Basic Constructs END OF SIMUALTION
Report a Bug or Comment
on This section - Your
Look at the solution, i is 3 in all the threads. input is what keeps
OpenVera Testbench.in improving
Constructs EXAMPLE :with shadow variable with time!
Switch TB
program main { 
RVM Switch TB call();
RVM Ethernet sample delay(40);
printf(" END OF SIMUALTION \n");
}
Specman E task call(){
Interview Questions shadow integer i;  // using shadow variable
delay(10);
for(i = 0; i < 3; i++) {
    fork
    {
    delay(10);  
     printf(" time = %0d: i is %0d \n",get_time(LO),i);
    }
   join none 
}
}

http://testbench.in/OV_12_SHADOW_VARIABLES.html[9/26/2012 2:46:32 PM]


WWW.TESTBENCH.IN - Vera Constructs

RESULTS

time = 20: i is 0
time = 20: i is 1
time = 20: i is 2
END OF SIMUALTION

The solution shows that ,Using the shadow keyword forces the Vera compiler to create
a copy of the variable i local to each child process, which eliminates race conditions.
Any descendants of the child processes will also have a copy of the variable local to
that descendant.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OV_12_SHADOW_VARIABLES.html[9/26/2012 2:46:32 PM]


WWW.TESTBENCH.IN - Vera Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS FORK JOIN CONTROL Index


Fork And Join Control: Introduction
SystemVerilog Data Types
Verification Wait_chiled(): Linked List
Operators Part 1
Constructs  The wait_child() system task is used to ensure that all child processes are executed Operators Part 2
Interface before the Vera program terminates. Operators Part 3
Operator Precedence
OOPS Control Statements
EXAMPLE : without wait_var
Randomization Procedures And Methods
task me () { Interprocess
Functional Coverage Fork Join
   integer n ;
Assertion Shadow Variables
   for(n=0; n<10 ; n++) { Fork Join Control
DPI Wait Var
     fork
UVM Tutorial       {delay(10) Event Sync
     printf(" inside for.join none ,time = %0d \n",get_time(LO) ) ; Event Trigger
VMM Tutorial Semaphore
     }
OVM Tutorial      join none Regions
   } Mailbox
Easy Labs : SV
//   wait_child() ; Timeouts
Easy Labs : UVM printf(" END of task \n"); Oop
 } Casting
Easy Labs : OVM
Randomization
Easy Labs : VMM program main { Randomization Methods
AVM Switch TB   me() ; Constraint Block
printf(" END of program \n"); Constraint Expression
VMM Ethernet sample } Variable Ordaring
Aop
RESULTS Predefined Methods
Verilog String Methods
END of task Queue Methods
Verification
END of program Dut Communication
Verilog Switch TB Functional Coverage
Basic Constructs
The soluton shows that inside forkjoin state ments are not printed. Report a Bug or Comment
on This section - Your
EXAMPLE : with wait_var input is what keeps
OpenVera Testbench.in improving
Constructs task me () { with time!
Switch TB    integer n ;
RVM Switch TB    for(n=0; n<10 ; n++) {
RVM Ethernet sample      fork
     {delay(10)
     printf(" inside for.join none ,time = %0d \n",get_time(LO) ) ;
     }
Specman E      join none
Interview Questions    }
   wait_child() ;
printf(" END of task \n");
 }

program main {
  me() ;
printf(" END of program \n");
}

RESULTS

http://testbench.in/OV_13_FORK_JOIN_CONTROL.html[9/26/2012 2:46:39 PM]


WWW.TESTBENCH.IN - Vera Constructs

inside for.join none ,time = 10


 inside for.join none ,time = 10
 inside for.join none ,time = 10
 inside for.join none ,time = 10
 inside for.join none ,time = 10
 inside for.join none ,time = 10
 inside for.join none ,time = 10
 inside for.join none ,time = 10
 inside for.join none ,time = 10
 inside for.join none ,time = 10
 END of task
 END of program

Terminate:

The terminate statement terminates all active descendants of the current thread in
which it was called.If any of the child processes have other descendants, the
terminate command terminates them as well.
This example forks off several child processes within a task. After any of the child
processes is complete, the code continues to execute. Before the task is completed,
all remaining child processes are terminated.

EXAMPLE : without terminate

task task1() {
 delay(10);
    printf(" before fork  time = %d \n",get_time(LO) ); 
    fork {
         delay (20);
         printf("time = %d  delay 20\n ",get_time(LO) );
         }
        {
         delay(10);
         printf("time = %d  delay 10\n ",get_time(LO) );
         }
        {
         delay(5);
         printf("time = %d  delay 5\n ",get_time(LO) );
        }
      join any
    

 fork {
      delay(35);
      printf("time = %d delay 35\n ",get_time(LO) );
     }
    { delay(25)
     printf("time = %d delay 25\n ",get_time(LO) );
    }
    {delay(15)
     printf("time = %d delay 15\n ",get_time(LO) );
    }
 join none
// terminate;    
 delay(100);
}
 

http://testbench.in/OV_13_FORK_JOIN_CONTROL.html[9/26/2012 2:46:39 PM]


WWW.TESTBENCH.IN - Vera Constructs

program main {
 task1();
  printf(" Time = %d Task completed \n",get_time(LO) );
 }

RESULTS

before fork  time = 10
time = 15  delay 5
 time = 20  delay 10
 time = 30  delay 20
 time = 30 delay 15
 time = 40 delay 25
 time = 50 delay 35
 Time = 115 Task completed

EXAMPLE : with terminate

task task1() {
 delay(10);
    printf(" before fork  time = %d \n",get_time(LO) ); 
    fork {
         delay (20);
         printf("time = %d  delay 20\n ",get_time(LO) );
         }
        {
         delay(10);
         printf("time = %d  delay 10\n ",get_time(LO) );
         }
        {
         delay(5);
         printf("time = %d  delay 5\n ",get_time(LO) );
        }
      join any
    

 fork {
      delay(35);
      printf("time = %d delay 35\n ",get_time(LO) );
     }
    { delay(25)
     printf("time = %d delay 25\n ",get_time(LO) );
    }
    {delay(15)
     printf("time = %d delay 15\n ",get_time(LO) );
    }
 join none
 terminate;    
 delay(100);
}
 
program main {
 task1();
  printf(" Time = %d Task completed \n",get_time(LO) );
 }

RESULTS

before fork  time = 10
time = 15  delay 5
Time = 115 Task completed

Both the solutions ahow that the task is completed at time 115 .When teriminate is
not used, all the chaild process execute,when teriminate is use,all the chaild
processes are teriminated.

Suspend_thread:

The suspend_thread() system task is used to temporarily suspend the current thread.It
suspends the current thread and allows other ready concurrent threads to run. When

http://testbench.in/OV_13_FORK_JOIN_CONTROL.html[9/26/2012 2:46:39 PM]


WWW.TESTBENCH.IN - Vera Constructs

all ready threads have had one chance to block, the suspended thread resumes
execution.

EXAMPLE : without suspend_thread

program main { 
call();
delay(40);
printf(" END OF SIMUALTION \n");
}

task call(){
shadow integer i;  // using shadow variable
delay(10);
for(i = 0; i < 3; i++) {
    fork
    {
    delay(10);  
     printf(" time = %0d: i is %0d \n",get_time(LO),i);
     printf( " Suspending the thread \n");
    // suspend_thread();
     printf( " After Suspending the thread  \n");
     printf(" time = %0d: i is %0d \n",get_time(LO),i);
    
    }
   join none 
}
}

RESULTS

time = 20: i is 0
 Suspending the thread
 After Suspending the thread
 time = 20: i is 0
 time = 20: i is 1
 Suspending the thread
 After Suspending the thread
 time = 20: i is 1
 time = 20: i is 2
 Suspending the thread
 After Suspending the thread
 time = 20: i is 2
 END OF SIMUALTION

EXAMPLE : with suspend_thread

program main { 
call();
delay(40);
printf(" END OF SIMUALTION \n");
}

task call(){
shadow integer i;  // using shadow variable
delay(10);
for(i = 0; i < 3; i++) {
    fork
    {
    delay(10);  
     printf(" time = %0d: i is %0d \n",get_time(LO),i);
     printf( " Suspending the thread \n");
     suspend_thread();
     printf( " After Suspending the thread  \n");
     printf(" time = %0d: i is %0d \n",get_time(LO),i);
    
    }
   join none 
}

http://testbench.in/OV_13_FORK_JOIN_CONTROL.html[9/26/2012 2:46:39 PM]


WWW.TESTBENCH.IN - Vera Constructs

RESULTS

time = 20: i is 0
 Suspending the thread
 time = 20: i is 1
 Suspending the thread
 time = 20: i is 2
 Suspending the thread
 After Suspending the thread
 time = 20: i is 0
 After Suspending the thread
 time = 20: i is 1
 After Suspending the thread
 time = 20: i is 2
 END OF SIMUALTION

The solution shows that all the child threads are suspended until all the calls are
made and then reumed.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OV_13_FORK_JOIN_CONTROL.html[9/26/2012 2:46:39 PM]


WWW.TESTBENCH.IN - Vera Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS WAIT VAR Index


Wait_var: Introduction
SystemVerilog Data Types
Verification The wait_var() system task blocks the calling process until one of the variables in its Linked List
arguments list changes values.Only true value changes unblock the process. Operators Part 1
Constructs Reassigning the same value does not unblock. If more than one variable is specified, a Operators Part 2
Interface change to any of the variables unblocks the process. Operators Part 3
Operator Precedence
OOPS Control Statements
EXAMPLE : wait_var()
Randomization program main { Procedures And Methods
    call(); Interprocess
Functional Coverage Fork Join
    delay(40);
Assertion     printf(" END OF SIMUALTION \n"); Shadow Variables
} Fork Join Control
DPI Wait Var
UVM Tutorial task call(){ Event Sync
    reg[7:0] data ; Event Trigger
VMM Tutorial Semaphore
    integer i;
OVM Tutorial     fork Regions
    { Mailbox
Easy Labs : SV
        while(1)  Timeouts
Easy Labs : UVM         { wait_var(data); Oop
         printf("time = %0d has changed to: %d\n",get_time(LO),data); Casting
Easy Labs : OVM
        } Randomization
Easy Labs : VMM     } Randomization Methods
AVM Switch TB     { Constraint Block
        for (i=0;i<10;i++){ Constraint Expression
VMM Ethernet sample         data= random(); Variable Ordaring
        delay(10);} Aop
    } Predefined Methods
Verilog     join all String Methods
}  Queue Methods
Verification
Dut Communication
Verilog Switch TB Functional Coverage
Basic Constructs RESULTS
Report a Bug or Comment
time = 0 has changed to: 0 on This section - Your
time = 10 has changed to: 156 input is what keeps
OpenVera time = 20 has changed to: 14 Testbench.in improving
Constructs time = 30 has changed to: 12 with time!
Switch TB time = 40 has changed to: 06
time = 50 has changed to: 119
RVM Switch TB time = 60 has changed to: 82
RVM Ethernet sample time = 70 has changed to: 223
time = 80 has changed to: 115
time = 90 has changed to: 195
Specman E
Interview Questions

http://testbench.in/OV_14_WAIT_VAR.html[9/26/2012 2:46:48 PM]


WWW.TESTBENCH.IN - Vera Constructs

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OV_14_WAIT_VAR.html[9/26/2012 2:46:48 PM]


WWW.TESTBENCH.IN - Vera Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS EVENT SYNC Index


Introduction
SystemVerilog Event Methods: Data Types
Verification Linked List
Events are variables that synchronize concurrent processes. When a sync is called, a Operators Part 1
Constructs process blocks until another process sends a trigger to unblock it. Events act as the Operators Part 2
Interface go-between for triggers and syncs. Operators Part 3
Operator Precedence
OOPS Control Statements
sync()          ::This method synchronizes statement execution to one or more triggers.
Randomization Procedures And Methods
ALL   :::The ALL sync type suspends the process until all of the specified events are Interprocess
Functional Coverage Fork Join
triggered.
Assertion For example: Shadow Variables
Fork Join Control
DPI Wait Var
sync(ALL, event_a, event_b, event_c);
UVM Tutorial Event Sync
ANY   :::The ANY sync type suspends the process until any of the specified events is Event Trigger
VMM Tutorial Semaphore
triggered.
OVM Tutorial For example: Regions
Mailbox
Easy Labs : SV
sync(ANY, event_a, event_b, event_c); Timeouts
Easy Labs : UVM Oop
ORDER :::The ORDER sync type suspends the process until any of the specified events Casting
Easy Labs : OVM
is triggered. Randomization
Easy Labs : VMM For example: Randomization Methods
AVM Switch TB Constraint Block
sync(ORDER, event_a, event_b, event_c); Constraint Expression
VMM Ethernet sample Variable Ordaring
CHECK :::The CHECK sync type is called as a function. It does not suspend the thread. Aop
It returns a 1 if the trigger is ON and a 0 if it is not.This sync type can only be used Predefined Methods
Verilog with ON and OFF trigger types.This sync type can only be used with a single event per String Methods
call. Queue Methods
Verification
For example: Dut Communication
Verilog Switch TB Functional Coverage
Basic Constructs sync(CHECK,event_a);
Report a Bug or Comment
on This section - Your
EXAMPLE : sync ANY input is what keeps
OpenVera Testbench.in improving
Constructs #include "vera_defines.vrh" with time!
Switch TB program main { 
    event event1,event2;
RVM Switch TB     call();
RVM Ethernet sample     sync(ANY,event1,event2);
    printf(" time : %0d After sync \n",get_time(LO) );
    delay(40);
    printf(" END OF SIMUALTION \n");
Specman E }
Interview Questions
task call(){
    fork
    {
        delay(10);
        printf("time : %0d , triggering event1 \n",get_time(LO)) ;
        trigger(event1);
        delay(10);
        printf("time : %0d , triggering event1 \n",get_time(LO) );
        trigger(event2);
    }

http://testbench.in/OV_15_EVENT_SYNC.html[9/26/2012 2:46:57 PM]


WWW.TESTBENCH.IN - Vera Constructs

    join none
}

RESULTS

time : 10 , triggering event1


 time : 10 After sync
time : 20 , triggering event1
 END OF SIMUALTION

EXAMPLE : sync ALL

#include "vera_defines.vrh"
program main { 
   event event1,event2;
   call();
   sync(ALL,event1,event2);
   printf(" time : %0d After sync \n",get_time(LO) );
   delay(40);
   printf(" END OF SIMUALTION \n");
}

task call(){
    fork{
        delay(10);
        printf("time : %0d , triggering event1 \n",get_time(LO) );
        trigger(event1);
        delay(10);
        printf("time : %0d , triggering event1 \n",get_time(LO) );
        trigger(event2);
    }
    join none
}

RESULTS

time : 10 , triggering event1


time : 20 , triggering event1
 time : 20 After sync
 END OF SIMUALTION

EXAMPLE : sync ORDER

#include "vera_defines.vrh"
program main { 
    event event1,event2;
    call();
    sync(ORDER,event2,event1);
    printf(" time : %0d After sync \n",get_time(LO) );
    delay(40);
    printf(" END OF SIMUALTION \n");
}

task call(){
fork{

http://testbench.in/OV_15_EVENT_SYNC.html[9/26/2012 2:46:57 PM]


WWW.TESTBENCH.IN - Vera Constructs

    delay(10);
    printf("time : %0d , triggering event1 \n",get_time(LO) );
    trigger(event2);
    delay(10);
    printf("time : %0d , triggering event1 \n",get_time(LO) );
    trigger(event1);
    delay(10);
    printf("time : %0d , triggering event1 \n",get_time(LO) );
    trigger(event2);
}
join none
}

RESULTS

time : 10 , triggering event1


time : 20 , triggering event1
 time : 20 After sync
time : 30 , triggering event1
 END OF SIMUALTION

EXAMPLE : sync CHECK

#include "vera_defines.vrh"
program main { 
    event event1,event2;
    bit check_bit;
    call();
    check_bit = sync(CHECK,event1);
    printf(" time : %0d After sync check_bit is %d \n",get_time(LO),check_bit);
    delay(40);
    printf(" END OF SIMUALTION \n");
}

task call(){
fork{
    trigger(ON,event1);
    delay(10);
    printf("time : %0d , triggering event1 \n",get_time(LO) );
    trigger(event1);
    delay(10);
    printf("time : %0d , triggering event1 \n",get_time(LO) );
    trigger(event2);
}
join

RESULTS

time : 0 After sync check_bit is 1


time : 10 , triggering event1
time : 20 , triggering event1
END OF SIMUALTION

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OV_15_EVENT_SYNC.html[9/26/2012 2:46:57 PM]


WWW.TESTBENCH.IN - Vera Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS EVENT TRIGGER Index


Event Trigger: Introduction
SystemVerilog Data Types
Verification This task is used to change the state of an event. Triggering an event unblocks waiting Linked List
syncs, or blocks subsequent syncs. By default, all events are OFF. Operators Part 1
Constructs Operators Part 2
Interface ONE_SHOT ::: The ONE_SHOT trigger is the default trigger type. If you use a Operators Part 3
ONE_SHOT trigger, any process waiting for a trigger receives it.If there are no Operator Precedence
OOPS Control Statements
processes waiting for the trigger, the trigger is discarded.
Randomization Procedures And Methods
ONE_BLAST ::: ONE_BLAST triggers work just as ONE_SHOT triggers do with the Interprocess
Functional Coverage Fork Join
exception that they trigger any sync called within the simulation time, regardless of
Assertion whether or not it was called before the trigger was executed. If a ONE_BLAST trigger Shadow Variables
is used for the situation diagrammed previously, all the processes are unblocked Fork Join Control
DPI Wait Var
regardless of execution order.
UVM Tutorial Event Sync
HAND_SHAKE ::: HAND_SHAKE triggers unblock only one sync, even if multiple syncs Event Trigger
VMM Tutorial Semaphore
are waiting for triggers. It triggers the most recent pending sync, or queues requests.
OVM Tutorial If the order of triggering the unblocking of a sync is important, use a semaphore_get() Regions
and semaphore_put() around the sync to maintain order. If a sync has already been Mailbox
Easy Labs : SV
called and is waiting for a trigger, the HAND_SHAKE trigger unblocks the sync. If no Timeouts
Easy Labs : UVM sync has been called when the trigger occurs, the HAND_SHAKE trigger is stored. When Oop
a sync is called, the sync is immediately unblocked and the trigger is removed. Casting
Easy Labs : OVM
Randomization
Easy Labs : VMM EXAMPLE : ONE_SHOT Randomization Methods
AVM Switch TB #include "vera_defines.vrh" Constraint Block
program vshell Constraint Expression
VMM Ethernet sample { Variable Ordaring
     event event1; Aop
     fork Predefined Methods
Verilog         sync_then_trigger(); String Methods
        trigger_then_sync(); Queue Methods
Verification
     join all Dut Communication
Verilog Switch TB   Functional Coverage
Basic Constructs }
task sync_then_trigger() Report a Bug or Comment
{ on This section - Your
     printf("Sync_then_trigger syncing at time %d\n", get_time(LO) ); input is what keeps
OpenVera      sync(ALL,event1); Testbench.in improving
Constructs      printf("Sync_then_trigger synced  at time %d\n",get_time(LO) ); with time!
Switch TB      #50;
     printf("Sync_then_trigger triggering at time %d\n",get_time(LO) );
RVM Switch TB      trigger (ONE_SHOT, event1);
RVM Ethernet sample }
task trigger_then_sync()
{
     #20;
Specman E      printf("trigger_then_sync triggering at time %d\n",get_time(LO) );
Interview Questions      trigger(ONE_SHOT, event1);
     #10;
     printf("trigger_then_sync syncing at time %d\n",get_time(LO) );
     sync(ALL,event1);
     printf("trigger_then_sync synced at time %d\n",get_time(LO) );
}

RESULTS

Sync_then_trigger syncing at time 0


trigger_then_sync triggering at time 20

http://testbench.in/OV_16_EVENT_TRIGGER.html[9/26/2012 2:47:04 PM]


WWW.TESTBENCH.IN - Vera Constructs

Sync_then_trigger synced  at time 20


trigger_then_sync syncing at time 30
Sync_then_trigger triggering at time 70
trigger_then_sync synced at time 70

EXAMPLE :ONE_BLAST
#include "vera_defines.vrh"
program vshell
{
        event event1, event2, event3;
        fork 
            call_task1(); 
            call_task2(); 
        join none 
        #150;
printf(" END of program");
}

task call_task1 ()
{
        printf("In task call_task1 Sync all events at time %d\n",get_time(LO) );
        #30;
        sync(ALL,event2,event3);
        printf("In task call_task1 Synced at time %d\n", get_time(LO) );
}

task call_task2()
{
        printf("In task call_task2 triggering events at time %d\n",get_time(LO) );
        #40;
        trigger(ONE_BLAST, event2);
        #20;  
        printf("In task call_task2 event2 was triggered and task call_task2 is finished at
time %d \n", get_time(LO) );
}

RESULTS

In task call_task1 Sync all events at time 0


In task call_task2 triggering events at time 0
In task call_task2 event2 was triggered and task call_task2 is finished at time 60

EXAMPLE :HAND_SHAKE
#include "vera_defines.vrh"
program vshell {
   event my_event = ON;
   fork
         sync_event1();
         sync_event2();
         trigger_event1();
   join all
      
}        

task sync_event1() {
    printf("before sync_event1  at time %0d \n");
    sync(ALL,my_event);

http://testbench.in/OV_16_EVENT_TRIGGER.html[9/26/2012 2:47:04 PM]


WWW.TESTBENCH.IN - Vera Constructs

    printf("after sync_event1  at time %0d \n");


    printf("before trigger sync_event1  at time %0d  \n");
    trigger(ONE_BLAST,my_event);
}

task sync_event2() {
    printf("before sync_event2  at time %0d \n");
    sync(ALL,my_event);
    printf("after sync_event2  at time %0d \n");
    printf("before trigger sync_event2  at time %0d  \n");
    trigger(ONE_BLAST,my_event);
}

 task trigger_event1() {
    printf("before trigger_event1  at time %0d \n");
    trigger(HAND_SHAKE,my_event);
    printf("after trigger_event1  at time %0d \n");
    sync(ALL,my_event);
    printf("after sync trigger_event1 3 at time %0d \n");
}  
RESULTS

before sync_event1  at time


before sync_event2  at time
before trigger_event1  at time
after trigger_event1  at time
after sync_event1  at time
before trigger sync_event1  at time
after sync_event2  at time
before trigger sync_event2  at time
after sync trigger_event1 3 at time

Event Variables :

These variables serve as the link between triggers and syncs. They are a unique data
type with several important properties.

EXAMPLE : Event Variables


#include "vera_defines.vrh"

task T1 (event trigger_a){
    printf("\nT1 syncing at cycle=%0d",get_time(LO) );
    sync(ALL, trigger_a); // Blocked: proceed after receiving trigger
    printf("\nT1 event trigger_a received at cycle=%0d",get_time(LO) );
    delay(70);
    printf("\nT1 triggering trigger_a at cycle=%0d",get_time(LO) );
    trigger (trigger_a);
}
program trigger_play
{
    event trigger1;
    fork
        T1(trigger1);// start T1 and go on
    join none
    delay(80); // T1 is blocked waiting for
    fork
    {
        printf("\nPROGRAM triggering trigger1 @cycle=%0d",get_time(LO) );
        printf("\nPROGRAM This unblocks T1");
        trigger(trigger1); // unblock the waiting T1
    }
    {   delay(50);
        printf("\nPROGRAM syncing @cycle=%0d\n\n",get_time(LO) );
        sync (ALL, trigger1) ;// wait for T1 to unblock me
    }
    join
    wait_child();
    printf("Trigger play done!");
}

RESULTS

http://testbench.in/OV_16_EVENT_TRIGGER.html[9/26/2012 2:47:04 PM]


WWW.TESTBENCH.IN - Vera Constructs

T1 syncing at cycle=0
PROGRAM triggering trigger1 @cycle=80
PROGRAM This unblocks T1
T1 event trigger_a received at cycle=80
PROGRAM syncing @cycle=130

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OV_16_EVENT_TRIGGER.html[9/26/2012 2:47:04 PM]


WWW.TESTBENCH.IN - Vera Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS SEMAPHORE Index


Introduction
SystemVerilog Semaphore: Data Types
Verification Linked List
A semaphore is an operation used for mutual exclusion and synchronization. Operators Part 1
Constructs Conceptually, semaphores can be viewed as a bucket. When you allocate a Operators Part 2
Interface semaphore, you create a virtual bucket. Inside the bucket are a number of keys. No Operators Part 3
process can be executed without first having a key. So, if a specific process requires a Operator Precedence
OOPS Control Statements
key, only a finite number of occurrences of that process can be in progress
Randomization simultaneously. All others must wait until a key is returned to the virtual bucket. Procedures And Methods
Interprocess
Functional Coverage Fork Join
Semaphore Allocation ::
Assertion To allocate a semaphore, you must use the alloc() system function. Shadow Variables
Syntax : function integer alloc(SEMAPHORE, integer semaphore_id,integer Fork Join Control
DPI Wait Var
semaphore_count, integer key_count);
UVM Tutorial Event Sync
The alloc() function returns the base semaphore ID if the semaphores are successfully Event Trigger
VMM Tutorial Semaphore
created. Otherwise, it returns 0.
OVM Tutorial Regions
semaphore_id ::: Mailbox
Easy Labs : SV
is the ID number of the particular semaphore being created. It must be an integer Timeouts
Easy Labs : UVM value. You should generally use 0. When you Oop
use 0, a semaphore ID is automatically generated by the simulator. Using any other Casting
Easy Labs : OVM
number explicitly assigns an ID to the Randomization
Easy Labs : VMM semaphore being created. Randomization Methods
AVM Switch TB Constraint Block
semaphore_count::: Constraint Expression
VMM Ethernet sample specifies how many semaphore “buckets†you want to create. It must be an Variable Ordaring
integer value. Aop
Predefined Methods
Verilog key_count ::: String Methods
specifies the number of keys initially allocated to each semaphore “bucket†you Queue Methods
Verification
are creating. Dut Communication
Verilog Switch TB Functional Coverage
Basic Constructs Using Semaphore Keys ::
To check that there are enough keys left in the semaphore, you must use the Report a Bug or Comment
semaphore_get() system function. on This section - Your
Syntax : function integer semaphore_get(NO_WAIT | WAIT,integer semaphore_id, input is what keeps
OpenVera integer key_count); Testbench.in improving
Constructs with time!
Switch TB To put keys back into a semaphore, you must use the semaphore_put() system task.
RVM Switch TB
RVM Ethernet sample EXAMPLE : simaphore
program vshell {
    integer sema,get;
Specman E     sema = alloc(SEMAPHORE,1,3,2);
Interview Questions     
    if(!sema)
        error("Semaphore Allocation failed\n");
   repeat(3) {
        fork {
             printf("Before getting key 1\n");
             get = semaphore_get(NO_WAIT,sema,2);
             if(!get)
                   error(" No sempahore key for inject2 \n");
             else 
             printf(" Got Key from 1 \n");

http://testbench.in/OV_17_SEMAPHORE.html[9/26/2012 2:47:14 PM]


WWW.TESTBENCH.IN - Vera Constructs

                        
             semaphore_put(sema,2);
             printf(" Putting back key \n");
             delay(10);
             } 
             {
               printf("Before getting key 2\n");

             get = semaphore_get(NO_WAIT,sema +1,2);


            
             if(!get)
                   error(" No sempahore key for inject2 \n");
              else 
                    printf(" Got Key from 2 \n");

             semaphore_put(sema + 1,2);


             delay(10);
             } 
                
        join all
    }
     delay(1000); 
}      

RESULTS

Before getting key 1


 Got Key from 1
 Putting back key
Before getting key 2
 Got Key from 2
Before getting key 1
 Got Key from 1
 Putting back key
Before getting key 2
 Got Key from 2
Before getting key 1
 Got Key from 1
 Putting back key
Before getting key 2
 Got Key from 2

The number of keys in the bucket can increase if more keys are put into the bucket
than are removed. Therefore, key_count is not necessarily the maximum number of
keys in the bucket.

EXAMPLE:
program vshell {
integer sema,get;

sema = alloc(SEMAPHORE,0,1,1);

if(!sema)
   error("Semaphore Allocation failed\n");

http://testbench.in/OV_17_SEMAPHORE.html[9/26/2012 2:47:14 PM]


WWW.TESTBENCH.IN - Vera Constructs

printf("Before getting key 1\n");


get = semaphore_get(WAIT,sema,1);

if(!get)
    error(" No sempahore key for inject2 \n");
else
    printf(" Got Key from 1 \n");

semaphore_put(sema,1);
printf(" Putting back key \n");

semaphore_put(sema,1);
printf(" Putting back key \n");

printf("Before getting key 1\n");


get = semaphore_get(WAIT,sema,1);

if(!get)
    error(" No sempahore key for inject2 \n");
else
    printf(" Got Key from 1 \n");

printf("Before getting key 1\n");


get = semaphore_get(WAIT,sema,1);

if(!get)
   error(" No sempahore key for inject2 \n");
else
   printf(" Got Key from 1 \n");

delay(1000);

RESULTS:

Before getting key 1


 Got Key from 1
 Putting back key
 Putting back key
Before getting key 1
 Got Key from 1
Before getting key 1
 Got Key from 1

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OV_17_SEMAPHORE.html[9/26/2012 2:47:14 PM]


WWW.TESTBENCH.IN - Vera Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS REGIONS Index


Regions: Introduction
SystemVerilog Data Types
Verification A region is a mutual exclusion mechanism that guarantees that the requested values Linked List
are unique in the simulation. This feature is provided mostly for random type Operators Part 1
Constructs simulations that may depend on the uniqueness of specific values such as addresses or Operators Part 2
Interface data-IDs. Operators Part 3
Conceptually, regions can be viewed as a set of letters. First you allocate which Operator Precedence
OOPS Control Statements
letters are included in the set. These letters are the only letters from which words can
Randomization be made. If one person uses the letters to spell CAT, no one else can spell TIN Procedures And Methods
because the T is already in use. Once the T is returned, TIN can be created. Interprocess
Functional Coverage Fork Join
Effectively, this ensures that data sets are unique, and it eliminates concurrent
Assertion crossover. Shadow Variables
Fork Join Control
DPI Wait Var
UVM Tutorial To allocate a region, you must use the alloc() system function. Event Sync
Syntax : function integer alloc(REGION, integer region_id, integer region_count); Event Trigger
VMM Tutorial Semaphore
region_id is the ID number of the particular region being created. It must be an
OVM Tutorial integer value. You should generally use 0. When you use 0,Vera automatically Regions
generates a region ID. Mailbox
Easy Labs : SV
region_count specifies how many regions you want to create. It must be an integer Timeouts
Easy Labs : UVM value. Oop
Casting
Easy Labs : OVM
Randomization
Easy Labs : VMM The region_enter() system function checks to see if a particular region is in use. Randomization Methods
AVM Switch TB The region_exit() system task removes the specified values from the in-use state. Constraint Block
Constraint Expression
VMM Ethernet sample EXAMPLE:REGIONS Variable Ordaring
task CPU(integer id, integer grant, integer regID){ Aop
    integer data, address; Predefined Methods
Verilog     reg[31:0] randVar; String Methods
    repeat (10) Queue Methods
Verification
    { Dut Communication
Verilog Switch TB         randVar=random(); Functional Coverage
Basic Constructs         address=randVar[13:6];
        data=randVar[29:22]; Report a Bug or Comment
        region_enter(WAIT, regID, address); on This section - Your
        disp(address,data,grant); input is what keeps
OpenVera         region_exit(regID, address); Testbench.in improving
Constructs     } with time!
Switch TB }
RVM Switch TB task disp(integer add,integer data,integer id){
RVM Ethernet sample    delay(random());
   printf(" add %d data %d id %d\n",add,data,id);
}
Specman E program main {
Interview Questions    integer regID;
   regID=alloc(REGION, 0, 1);
   fork
      CPU(0, 2'b01, regID);
      CPU(1, 2'b10, regID);
   join

}
RESULTS

add 56 data 0 id 1

http://testbench.in/OV_18_REGIONS.html[9/26/2012 2:47:22 PM]


WWW.TESTBENCH.IN - Vera Constructs

 add 230 data 13 id 2


 add 31 data 156 id 1
 add 179 data 140 id 2
 add 159 data 135 id 1
 add 113 data 252 id 1
 add 149 data 142 id 2
 add 193 data 187 id 1
 add 77 data 221 id 2
 add 116 data 120 id 1
 add 215 data 198 id 2
 add 200 data 88 id 1
 add 192 data 35 id 2
 add 252 data 1 id 1
 add 199 data 254 id 2
 add 142 data 42 id 2
 add 49 data 204 id 1
 add 187 data 135 id 1
 add 172 data 46 id 2
 add 142 data 57 id 2

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OV_18_REGIONS.html[9/26/2012 2:47:22 PM]


WWW.TESTBENCH.IN - Vera Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS MAILBOX Index


Introduction
SystemVerilog Mailbox: Data Types
Verification Linked List
A mailbox is a mechanism to exchange messages between processes. Data can be sent Operators Part 1
Constructs to a mailbox by one process and retrieved by another. Conceptually, mailboxes behave Operators Part 2
Interface like real mailboxes. When a letter is delivered and put into the mailbox, you can Operators Part 3
retrieve the letter (and any data stored within). However, if the letter has not been Operator Precedence
OOPS Control Statements
delivered when you check the mailbox, you must choose whether to wait for the
Randomization letter or retrieve the letter on subsequent trips to the mailbox.Similarly, OpenVeraâ Procedures And Methods
€™s mailboxes allow you to transfer and retrieve data in a very controlled manner. Interprocess
Functional Coverage Fork Join
Assertion To allocate a mailbox, you must use the alloc() system function. Shadow Variables
Syntax : function integer alloc(MAILBOX, integer mailbox_id, integer mailbox_count); Fork Join Control
DPI Wait Var
mailbox_id is the ID number of the particular mailbox being created. It must be an
UVM Tutorial integer value. You should generally use 0. When you use 0, Vera automatically Event Sync
generates a mailbox ID. Event Trigger
VMM Tutorial Semaphore
mailbox_count specifies how many mailboxes you want to create. It must be an
OVM Tutorial integer value. Regions
The mailbox_put() system task sends data to the mailbox. Mailbox
Easy Labs : SV
The mailbox_get() system function returns data stored in a mailbox. Timeouts
Easy Labs : UVM Oop
Casting
Easy Labs : OVM
EXAMPLE : Mailbox Randomization
Easy Labs : VMM Randomization Methods
AVM Switch TB #include "vera_defines.vrh" Constraint Block
Constraint Expression
VMM Ethernet sample program vshell Variable Ordaring
{ Aop
    integer my_mailbox; Predefined Methods
Verilog String Methods
    my_mailbox = alloc(MAILBOX, 0, 1); Queue Methods
Verification
    if (my_mailbox) Dut Communication
Verilog Switch TB     { Functional Coverage
Basic Constructs         fork
            put_packets(); Report a Bug or Comment
            get_packets(); on This section - Your
        join none input is what keeps
OpenVera     } Testbench.in improving
Constructs with time!
Switch TB     delay(1000);
   printf("END of Program\n");
RVM Switch TB }
RVM Ethernet sample
task put_packets()
{
    integer i;
Specman E     
Interview Questions     for (i=0; i<10; i++)
    {
        delay(10);
        mailbox_put(my_mailbox,i);
            printf("Done putting packet %d @time %d\n",i, get_time(LO) );
      
    }
}

task get_packets()
{

http://testbench.in/OV_19_MAILBOX.html[9/26/2012 2:47:31 PM]


WWW.TESTBENCH.IN - Vera Constructs

    integer ret;
    bit [63:0] packet;

    while (1)
    {
        ret = mailbox_get(WAIT, my_mailbox, packet, CHECK);
        if (ret > 0)
            printf("Got packet %d @time %d\n", packet, get_time(LO) );
    }
}

RESULTS

Done putting packet 0 @time 10


Got packet 0 @time 10
Done putting packet 1 @time 20
Got packet 1 @time 20
Done putting packet 2 @time 30
Got packet 2 @time 30
Done putting packet 3 @time 40
Got packet 3 @time 40
Done putting packet 4 @time 50
Got packet 4 @time 50
Done putting packet 5 @time 60
Got packet 5 @time 60
Done putting packet 6 @time 70
Got packet 6 @time 70
Done putting packet 7 @time 80
Got packet 7 @time 80
Done putting packet 8 @time 90
Got packet 8 @time 90
Done putting packet 9 @time 100
Got packet 9 @time 100

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OV_19_MAILBOX.html[9/26/2012 2:47:31 PM]


WWW.TESTBENCH.IN - Vera Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS TIMEOUTS Index


Timeouts: Introduction
SystemVerilog Data Types
Verification A process will wait forever in semaphore, region and mailbox if the waiting resources Linked List
are not available. However, the system task timeout() can be used to set a time limit. Operators Part 1
Constructs Operators Part 2
Interface These are examples of timeout statements: Operators Part 3
Operator Precedence
OOPS Control Statements
timeout(SEMAPHORE, 100);
Randomization timeout(REGION, 50, 2); Procedures And Methods
timeout(EVENT, 20); Interprocess
Functional Coverage Fork Join
timeout(myevent, 300);
Assertion Shadow Variables
Fork Join Control
DPI Wait Var
UVM Tutorial Event Sync
Event Trigger
VMM Tutorial Semaphore
OVM Tutorial Regions
Mailbox
Easy Labs : SV
Timeouts
Easy Labs : UVM Oop
Casting
Easy Labs : OVM
Randomization
Easy Labs : VMM Randomization Methods
AVM Switch TB Constraint Block
Constraint Expression
VMM Ethernet sample Variable Ordaring
Aop
Predefined Methods
Verilog String Methods
Queue Methods
Verification
Dut Communication
Verilog Switch TB Functional Coverage
Basic Constructs
Report a Bug or Comment
on This section - Your
input is what keeps
OpenVera Testbench.in improving
Constructs with time!
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/OV_20_TIMEOUTS.html[9/26/2012 2:47:39 PM]


WWW.TESTBENCH.IN - Vera Constructs

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OV_20_TIMEOUTS.html[9/26/2012 2:47:39 PM]


WWW.TESTBENCH.IN - Vera Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS OOP Index


Introduction
SystemVerilog Object Oriented Programming : Data Types
Verification Linked List
Object oriented programming (OOP) involves the development of applications with Operators Part 1
Constructs modular, reusable components.The object-oriented paradigm is built on three Operators Part 2
Interface important principles: Operators Part 3
Operator Precedence
OOPS Control Statements
 Encapsulation
Randomization  Inheritance Procedures And Methods
 Polymorphism Interprocess
Functional Coverage Fork Join
Assertion Encapsulation : Encapsulation is the principle of grouping together common Shadow Variables
functionality and features into a code object.I Fork Join Control
DPI Wait Var
nheritance   : Inheritance is the principle of transferring the functionality and
UVM Tutorial features of a parent to a child. Since the child is an autonomous unit, the properties Event Sync
and methods inherited by the child can be modified or added to without affecting the Event Trigger
VMM Tutorial Semaphore
parent.
OVM Tutorial Polymorphism  : Polymorphism allows the redefining of methods for derived classes Regions
while enforcing a common interface. Mailbox
Easy Labs : SV
Timeouts
Easy Labs : UVM Creating an object: Oop
To create an object (i.e., an instance) of a declared class, there are two steps. First, Casting
Easy Labs : OVM
declare a handle to the class (a handle is a reference to the class instance, or object) Randomization
Easy Labs : VMM Randomization Methods
AVM Switch TB class_name handle_name; Constraint Block
Constraint Expression
VMM Ethernet sample Then, call the new() class method: Variable Ordaring
Aop
handle_name = new(); Predefined Methods
Verilog String Methods
or simple Queue Methods
Verification
Dut Communication
Verilog Switch TB class_name handle_name = new(); Functional Coverage
Basic Constructs
new() is a default implementation which simply allocates memory for the object and Report a Bug or Comment
returns a handle to the object. on This section - Your
input is what keeps
OpenVera Assignment : Testbench.in improving
Constructs with time!
Switch TB Packet p1;
p1 = new();
RVM Switch TB Packet p2;
RVM Ethernet sample p2 = p1;
In this case, there is still only one object. This single object can be referred to with
either variable, p1 or p2.
Specman E
Interview Questions The following code:

p2 = new p1;

makes a shallow copy of the object referenced by p1, and sets p2 to point to it. A
shallow copy creates a new object and copies the values of all properties from the
source object. It is a shallow copy because it does not make a copy of any nested
objects.

p2 = object_copy(p1); // creates a duplicate object of p, with the handle q .

http://testbench.in/OV_21_OOP.html[9/26/2012 2:47:48 PM]


WWW.TESTBENCH.IN - Vera Constructs

EXAMPLE : copy

class A{
   integer j;
   task new(){ j=5;}
}
class B{
   integer i;
   A a;
   task new() {i = 1;}
}
task test(){
   B b1 = new(); // Create an object of class B
   B b2;         //Create a null variable of class B
   b1.a = new;   //Create an object of class A
   b2 = new b1;  // Create an object that is a copy of b1,
                 //but only copies the handle a, not the object
                 //referenced by a.
   b2.i = 10;    // i is changed in b2, but not b1
   printf("i in b2 = %0d\n", b2.i);// i equals 10
   printf("i in b1 = %0d\n", b1.i);// i equals 1
                  //where as:
   b2.a.j = 50;   // Change j in the object referenced
                  // by a. j is shared by both b1 and b2
   printf("j is %0d in b1 and %d in b2\n", b1.a.j, b2.a.j);
}
program shallow_copy{
   test();
}

RESULTS

i in b2 = 10
i in b1 = 1
j is 50 in b1 and 50 in b2

Properties:

The properties in a class may be of the following atomic types or may


be arrays of these types.
 reg
 reg [msb:0]
 integer
 string
 event
 class type
 enum type
A property declaration may be preceded by one of these keywords:
 local
 public
 protected
public is the default protection level for class members. Using public when declaring a
property allows global access to that member via class_name.member. In contrast, a
member designated as local isone that is only visible from within the class itself. A
protected property is not visible outside of the class scope, but it is visible to peer
objects and can be inherited by subclasses.

http://testbench.in/OV_21_OOP.html[9/26/2012 2:47:48 PM]


WWW.TESTBENCH.IN - Vera Constructs

This:

The this keyword is used to unambiguously refer to properties or methods of the


current instance. For example, the following declaration is a common, way to write
an initialization task:

EXAMPLE : this
class Demo
{
    integer x;
    task new (integer x)
    {
       this.x = x;
    }
}

program main {
   Demo D;
   D = new(10);
   printf(" D.x is %d \n",D.x);
}
RESULTS

D.x is 10

The x is now both a property of the class and an argument to the task new(). In the
task new(), an unqualified reference to x will be resolved by looking at the innermost
scope, in this case the subroutine argument declaration. To access the instance
property,we qualify it with this to refer to the current instance.

Class Extensions :

Subclasses and Inheritance :


OpenVera's OOP implementation provides the capability of inheriting from a base class
and extending its capabilities within a
subclass. This concept is called inheritance. When one inherits from a class into
another, the original class definition is not changed, however the new subclass
contains all the properties and methods of the base class and then can optionally add
additional properties and methods.

EXAMPLE : Inheritance
class A {
   task disp_a (){
      printf(" This is class A ");
   }
}

class EA extends A {
    task disp_ea (){
       printf(" This is Extended class A ");
    }
}

program main {
    EA my_ea;
    my_ea = new();
    
    my_ea.disp_a();
    my_ea.disp_ea();
}
RESULTS

This is class A  


This is Extended class A

Polymorphism :

Polymorphism allows the redefining of methods for derived classes while enforcing a

http://testbench.in/OV_21_OOP.html[9/26/2012 2:47:48 PM]


WWW.TESTBENCH.IN - Vera Constructs

common interface.To achieve polymorphism the 'virtual' identifier must be used when
defining the base class and method(s) within that class. A virtual class is a class which
serves as a template for the construction of derived classes. One cannot create an
instance of a virtual class.

EXAMPLE :  Polymorphism
class A {
   virtual task disp (){
      printf(" This is class A ");
   }
}

class EA extends A {
   task disp (){
      printf(" This is Extended class A ");
   }
}

program main {
   EA my_ea;
   A my_a;
   my_ea = new();
   my_a = my_ea;
   my_ea.disp();
   my_a.disp();
}

RESULTS

 This is Extended class A


 This is Extended class A

Super:

The super keyword is used from within a derived class to refer to properties of the
parent class. It is necessary to use super when the property of the derived class has
been overridden, and cannot be accessed directly.

EXAMPLE :
class A {
   virtual task disp (){
       printf(" This is class A \n");
   }
}

class EA extends A {
    task disp (){
       super.disp();
       printf(" This is Extended class A \n");
    }
}

program main {
    EA my_ea;
    my_ea = new();
    my_ea.disp();
}

RESULTS

This is class A
This is Extended class A

Abstract Class:

A set of classes can be created that can be viewed as all being derived from a
common base class.If base class is not supposed to be used to creat an object,then it
has to be declared as abstract class using keyword virtual.

EXAMPLE:
virtual class BasePacket{

http://testbench.in/OV_21_OOP.html[9/26/2012 2:47:48 PM]


WWW.TESTBENCH.IN - Vera Constructs

   function integer send(bit[31:0] data){
   }
}
class EtherPacket extends BasePacket{
   function integer send(bit[31:0] data){
      // body of the function
      ...
   }
}

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OV_21_OOP.html[9/26/2012 2:47:48 PM]


WWW.TESTBENCH.IN - Vera Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS CASTING Index


Introduction
SystemVerilog The cast_assign() system function assigns values to variables that might not ordinarily Data Types
Verification be valid because of type checking rules. Linked List
Syntax : function integer cast_assign(scalar dest_var, scalar source_exp [,CHECK]); Operators Part 1
Constructs Operators Part 2
Interface When the cast_assign() system function is called without CHECK, the function assigns Operators Part 3
the source expression to the destination variable. If the assignment is illegal, a fatal Operator Precedence
OOPS Control Statements
runtime error occurs. When the cast_assign() system function is called with CHECK
Randomization specified, the function makes the assignment and returns a 1 if the casting is Procedures And Methods
successful. If the casting is unsuccessful, the function does not make the assignment Interprocess
Functional Coverage Fork Join
and returns a 0.
Assertion Shadow Variables
EXAMPLE: Fork Join Control
DPI Wait Var
class base {
UVM Tutorial Event Sync
    virtual task pri(){ Event Trigger
VMM Tutorial Semaphore
        printf(" BASE CLASS STATEMENT\n");
OVM Tutorial     } Regions
} Mailbox
Easy Labs : SV
Timeouts
Easy Labs : UVM class EX_1 extends base { Oop
    task pri(){ Casting
Easy Labs : OVM
        printf(" EX1 CLASS STATEMENT\n"); Randomization
Easy Labs : VMM     } Randomization Methods
AVM Switch TB } Constraint Block
Constraint Expression
VMM Ethernet sample Variable Ordaring
program main{ Aop
    base b; Predefined Methods
Verilog     EX_1 e1; String Methods
     Queue Methods
Verification
     Dut Communication
Verilog Switch TB     b = new(); Functional Coverage
Basic Constructs     if(cast_assign(e2,b))
       printf("casting done \n"); Report a Bug or Comment
    else  on This section - Your
       printf(" casting failed \n"); input is what keeps
OpenVera     e2.pri(); Testbench.in improving
Constructs     printf(" END OF SIMULATION \n"); with time!
Switch TB }
RVM Switch TB
RVM Ethernet sample RESULTS:
casting done
 BASE CLASS STATEMENT
Specman E  END OF SIMULATION
Interview Questions

http://testbench.in/OV_22_CASTING.html[9/26/2012 2:47:58 PM]


WWW.TESTBENCH.IN - Vera Constructs

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OV_22_CASTING.html[9/26/2012 2:47:58 PM]


WWW.TESTBENCH.IN - Vera Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS RANDOMIZATION Index


Constrained Random Verification Introduction
SystemVerilog Data Types
Verification Openvera allowses object-oriented programiming for random stimulus generation Linked List
subjected to specified constraints. Operators Part 1
Constructs During randomization, variables declared as rand and randc inside class are only Operators Part 2
Interface considered for randomization.Built-in randomized() method is called to generate new Operators Part 3
random values for there variable. Operator Precedence
OOPS Control Statements
Randomization EXAMPLE: Procedures And Methods
class Simple{ Interprocess
Functional Coverage Fork Join
    rand integer Var;
Assertion } Shadow Variables
program main { Fork Join Control
DPI Wait Var
    Simple
UVM Tutorial obj;                                                                                                                             Event Sync
    obj = new(); Event Trigger
VMM Tutorial Semaphore
    repeat(10)
OVM Tutorial     if(obj.randomize()) Regions
        printf(" Randomization sucsessfull : Var = %0d \n",obj.Var); Mailbox
Easy Labs : SV
    else Timeouts
Easy Labs : UVM         printf("Randomization failed\n"); Oop
Casting
Easy Labs : OVM
} Randomization
Easy Labs : VMM RESULTS: Randomization Methods
AVM Switch TB Constraint Block
 Randomization sucsessfull : Var = -2147414528 Constraint Expression
VMM Ethernet sample  Randomization sucsessfull : Var = -1671855048 Variable Ordaring
 Randomization sucsessfull : Var = 1129920902 Aop
 Randomization sucsessfull : Var = -1374483364 Predefined Methods
Verilog  Randomization sucsessfull : Var = 1730349006 String Methods
 Randomization sucsessfull : Var = 1674352583 Queue Methods
Verification
 Randomization sucsessfull : Var = -485282618 Dut Communication
Verilog Switch TB  Randomization sucsessfull : Var = -103324941 Functional Coverage
Basic Constructs  Randomization sucsessfull : Var = 1641506755
 Randomization sucsessfull : Var = -1349564321 Report a Bug or Comment
on This section - Your
input is what keeps
OpenVera Testbench.in improving
Constructs Random Varible Declaration: with time!
Switch TB
Varibles declared as rand and randc are only randomized.All other varible are
RVM Switch TB considered as state varibles.
RVM Ethernet sample
EXAMPLE
class ex{
    rand [3:0] var1;
Specman E     randc [3:0] var2;
Interview Questions     rand integer var3;
}

Fixed Arrays,dynamic arrays,associative arrays and queues can be declared as rand


and randc ,all their elements are treated as rand and randc.Individual array elements
can also be constrained,in this ,index expression must be constant.For dynamic
arryas,the size of the array length can be constrained.Non integral data types like real
are not allowed for random varible declaration.

Rand Modifier :

http://testbench.in/OV_23_RANDOMIZATION.html[9/26/2012 2:48:07 PM]


WWW.TESTBENCH.IN - Vera Constructs

Variables declared with the rand keyword are standard random variables.
When ther are no other control on distrubution,these variables are uniformly
distributed.
Uniformly distribution is only on the valid values.

EXAMPLE
class rand_cl{
    rand bit [0:2] Var;
    constraint limit_c { Var < 4;}
}
program rand_p{
    rand_cl obj;
    integer count_0, count_1, count_2, count_3;
    count_0 = 0;count_1 = 0;count_2 = 0;count_3 = 0;
    obj =  new();
    repeat(10000)
    {
        void = obj.randomize();
        if( obj.Var == 0) count_0 ++;
        else if( obj.Var == 1) count_1 ++;
        else if( obj.Var == 2) count_2 ++;
        else if( obj.Var == 3) count_3 ++;
    }
    printf(" count_0 = %0d , count_1 = %0d, count_2 = %0d, count_3 = %0d
",count_0, count_1, count_2, count_3);
}

RESULTS:

 count_0 = 2501 , count_1 = 2553, count_2 = 2558, count_3 = 2388

Simulation results shou that the rand variable is distrubuted uniformly.

Randc Modifier :

Varibles declared as randc, randomly iterates over all the values in the range and no
value is repeated with in an iteration.
Iteration sequences are not same.Bit and enumarated types can be randc variables.To
reduce memory requirements, implementations can impose a limit on the maximum
size of a randc variable,but it should be no less than 8 bits.

EXAMPLE
class rand_c{
   randc bit [1:0]Vari;
}

program rand_cp{
    rand_c obj;
    integer i;
    obj = new();
    for(i=0;i<20;i++)
    {
        void = obj.randomize();
        printf("%0d_",obj.Vari);
        if(i%4==3)
           printf("\n");
    }

http://testbench.in/OV_23_RANDOMIZATION.html[9/26/2012 2:48:07 PM]


WWW.TESTBENCH.IN - Vera Constructs

RESULTS

1_2_0_3_
3_2_0_1_
3_1_2_0_
2_0_3_1_
1_3_2_0_

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OV_23_RANDOMIZATION.html[9/26/2012 2:48:07 PM]


WWW.TESTBENCH.IN - Vera Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS RANDOMIZATION METHODS Index


Randomization Built-In Methods Introduction
SystemVerilog Data Types
Verification openvera has randomize(),pre_randomize() and post_randomize() built-in function for Linked List
randomization. Operators Part 1
Constructs Calling randomize() causes new values to be selected for all of the random variables Operators Part 2
Interface in an object. Operators Part 3
To perform operations immediately before or after randomization,pre_randomize() Operator Precedence
OOPS Control Statements
and post_randomize() are used.
Randomization Procedures And Methods
Interprocess
Functional Coverage Fork Join
Randomize()
Assertion Shadow Variables
Every class has a virtual  predefined function randomize() ,which is provided for Fork Join Control
DPI Wait Var
generating a new value.Randomization function returns 1 if the solver finds a valid
UVM Tutorial solution.We cannot override this predefined function. Event Sync
It is strongly recomemded to check the return value of randomize function.Constraint Event Trigger
VMM Tutorial Semaphore
solver never fails after one sucessful randomization,if solution space is not
OVM Tutorial changed.For every randomization call,Check the return value ,solver may fail due to Regions
dynamically changing the constraints. Mailbox
Easy Labs : SV
In the following example,there is no solution for Var < 100 and Var > 200,so the Timeouts
Easy Labs : UVM randomization failes. Oop
The best way to check for randomization return value is by using assertion. Casting
Easy Labs : OVM
assert(obj.randomize()); Randomization
Easy Labs : VMM Randomization Methods
AVM Switch TB EXAMPLE Constraint Block
Constraint Expression
VMM Ethernet sample class Simple{ Variable Ordaring
    rand integer Var; Aop
    constraint c { Var < 100 ; Var > 200 ; } Predefined Methods
Verilog } String Methods
program main{ Queue Methods
Verification
    Simple obj;                                                                                                                   Dut Communication
Verilog Switch TB     obj = new(); Functional Coverage
Basic Constructs     if(obj.randomize())
        printf(" Randomization sucsessfull : Var = %0d ",obj.Var); Report a Bug or Comment
    else on This section - Your
        printf("Randomization failed"); input is what keeps
OpenVera } Testbench.in improving
Constructs with time!
Switch TB RESULTS:
RVM Switch TB Constraint failure
RVM Ethernet sample

Pre_randomize And Post_randomize


Specman E Every class contains pre_randomize() and post_randomize() methods, which are
Interview Questions automatically called
by randomize() before and after computing new random values.When randomize() is
called,it first invokes the pre_randomize,then randomize() then if the randomization
is sucesusful,then only post_randomize is invoked.

EXAMPLE:
class simple{
   task pre_randomize{
       printf(" PRE_RANDOMIZATION ");
   }
   task post_randomize{

http://testbench.in/OV_24_RANDOMIZATION_METHODS.html[9/26/2012 2:48:14 PM]


WWW.TESTBENCH.IN - Vera Constructs

       printf(" PRE_RANDOMIZATION ");


   }
}
program main{
                                                                                                                          
   simple obj = new();
   void = obj.randomize();
}                                                                                                                            
RESULTS:

 PRE_RANDOMIZATION  PRE_RANDOMIZATION

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OV_24_RANDOMIZATION_METHODS.html[9/26/2012 2:48:14 PM]


WWW.TESTBENCH.IN - Vera Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS CONSTRAINT BLOCK Index


Constraint Block Introduction
SystemVerilog Data Types
Verification Constraint block contains declarative state ments which restrict the range of varable Linked List
or defines the relation between variables.Constraint programming is a pwerful mehod Operators Part 1
Constructs that lets users build generic ,resuble objects that can  be extended or more Operators Part 2
Interface constrained later.Constraint solver can only support 2 stet variables.Constraint solver Operators Part 3
fails only if there is no solution which satisfies all the constraints.constraint block can Operator Precedence
OOPS Control Statements
also have nonrandom variables,but atleast one random variable is needed for
Randomization randomization. Procedures And Methods
Constraints are tied to objects.This allows inheritance,hirarchical Interprocess
Functional Coverage Fork Join
constraints,controlling the constraints of specific object.
Assertion Shadow Variables
EXAMPLE: Fork Join Control
DPI Wait Var
class Base{
UVM Tutorial    rand integer Var; Event Sync
   constraint range { Var < 100 ; Var > 0 ;} Event Trigger
VMM Tutorial Semaphore
}
OVM Tutorial Regions
class Extended extends Base{ Mailbox
Easy Labs : SV
  constraint range { Var < 100 ; Var > 50 ;} // Overrighting the Base class constraints. Timeouts
Easy Labs : UVM } Oop
Casting
Easy Labs : OVM
program inhe{ Randomization
Easy Labs : VMM    Extended obj; Randomization Methods
AVM Switch TB    integer i; Constraint Block
   obj = new(); Constraint Expression
VMM Ethernet sample    for(i=0 ; i < 100 ; i++) Variable Ordaring
      if(obj.randomize()) Aop
          printf(" Randomization sucsessfull : Var = %0d ",obj.Var); Predefined Methods
Verilog       else String Methods
          printf("Randomization failed"); Queue Methods
Verification
} Dut Communication
Verilog Switch TB Functional Coverage
Basic Constructs RESULTS:
Report a Bug or Comment
 Randomization sucsessfull : Var = 57 on This section - Your
 Randomization sucsessfull : Var = 82 input is what keeps
OpenVera  Randomization sucsessfull : Var = 68   Testbench.in improving
Constructs Randomization sucsessfull : Var = 81   with time!
Switch TB Randomization sucsessfull : Var = 90
RVM Switch TB
RVM Ethernet sample Inline Constraints

Inline constraints allows to add extra constraints to allready existing conrtints which
are declared inside class.If you have constraints already defined for variavle var,
Specman E solver solves those constraints wlong with the inline constraints.
Interview Questions
EXAMPLE

class inline{
    rand integer Var;
    constraint default_c { Var > 0 ; Var < 100;}
}

program inline_p{
   inline obj;
   obj = new();

http://testbench.in/OV_25_CONSTRAINT_BLOCK.html[9/26/2012 2:48:23 PM]


WWW.TESTBENCH.IN - Vera Constructs

   void =  obj.randomize() with { Var == 50;} ;
   printf(" Randodmize sucessful Var %d ",obj.Var);
}
RESULTS:

Randomization sucsessfull : Var = 50

Disabling Constraint Block

openvera supports to change the status of constraint block dynamically.To change the
staus of a Constraint block,built in constraint_mode() method is used.By default all
the constraint blocks are active.
When it is called as task,the arguments to the task determines the operation to be
performed.

0  OFF  Sets the specified constraint block to inactive


        so that it is not enforced by subsequent calls
        to the randomize() method.
1  ON   Sets the specified constraint block to active so
        that it is considered on subsequent calls to the
        randomize() method.

When it is called as function,it returns the active status of the specified constrant
block.

EXAMPLE:
class rand_mo{
   rand integer Var1;
   rand integer Var2;
   constraint Var_1 { Var1 == 20;}
   constraint Var_2 { Var2 == 10;}
}

program rand_mo_p{
   rand_mo obj = new();
   void = obj.randomize();
   printf(" Var1 : %d   Var2 : %d \n",obj.Var1,obj.Var2);
   void = obj.constraint_mode(0,"Var_1");
   void = obj.randomize();
   printf(" Var1 : %d   Var2 : %d \n",obj.Var1,obj.Var2);
   void = obj.constraint_mode(0,"Var_2");
   void = obj.randomize();
   printf(" Var1 : %d   Var2 : %d \n",obj.Var1,obj.Var2);
}
RESULTS:

 Var1 : 20   Var2 : 10


 Var1 : 1923838927   Var2 : 10
 Var1 : 1447386075   Var2 : -875228050

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/OV_25_CONSTRAINT_BLOCK.html[9/26/2012 2:48:23 PM]


WWW.TESTBENCH.IN - Vera Constructs

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OV_25_CONSTRAINT_BLOCK.html[9/26/2012 2:48:23 PM]


WWW.TESTBENCH.IN - Vera Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS CONSTRAINT EXPRESSION Index


Constraint Expressions Introduction
SystemVerilog Data Types
Verification A constraint_expression is any Openvera expression or one of the constraint specific Linked List
operators, -> (Implication) and dist. Operators Part 1
Constructs Operators Part 2
Interface Set Membership Operators Part 3
Operator Precedence
OOPS
A set membership is a list of expressions or a range.This operator searches for the Control Statements
Randomization existences of the value in the specified expression or range and returns 1 if it is Procedures And Methods
existing. Interprocess
Functional Coverage Fork Join
Assertion EXAMPLE: Shadow Variables
class set_mem{ Fork Join Control
DPI Wait Var
   rand integer Var;
UVM Tutorial    constraint range { Var in {0,1,{50,60},{90,100}}; } Event Sync
   task post_randomize(){ Event Trigger
VMM Tutorial Semaphore
      printf("%0d__",Var);
OVM Tutorial    } Regions
} Mailbox
Easy Labs : SV
Timeouts
Easy Labs : UVM program set_mem_p{ Oop
   set_mem obj=new(); Casting
Easy Labs : OVM
   repeat(10) Randomization
Easy Labs : VMM    void = obj.randomize(); Randomization Methods
AVM Switch TB } Constraint Block
Constraint Expression
VMM Ethernet sample RESULTS: Variable Ordaring
Aop
1__51__93__1__0__56__0__94__1__0__ Predefined Methods
Verilog String Methods
Queue Methods
Verification
If you want to define a range which is outside the set,use nagation. Dut Communication
Verilog Switch TB EXAMPLE: Functional Coverage
Basic Constructs class set_mem{
   rand bit [0:2] Var; Report a Bug or Comment
   constraint range { !( Var in {0,1,5,6};)} on This section - Your
   task post_randomize(){ input is what keeps
OpenVera       printf("%0d__",Var); Testbench.in improving
Constructs    } with time!
Switch TB }
                                                                                                                            
RVM Switch TB program set_mem_p{
RVM Ethernet sample    set_mem obj=new();
   repeat(10)
   void = obj.randomize();
}
Specman E
Interview Questions RESULTS:

2__7__2__4__7__3__3__4__2__7__

Weighted Distribution

There are two types of distribution operators.


The := operator assigns the specified weight to the item or, if the item is a range, to
every value in the range.
The :/ operator assigns the specified weight to the item or, if the item is a range, to

http://testbench.in/OV_26_CONSTRAINT_EXPRESSION.html[9/26/2012 2:48:33 PM]


WWW.TESTBENCH.IN - Vera Constructs

the range as a whole. If


there are n values in the range, the weight of each value is range_weight / n.

Var dist { 10 := 1; 20 := 2 ; 30 := 2 }

The probabulity of having 10,20,30 is in the ration of 1,2,2 respectively.

Var dist { 10 := 1; 20 := 2 ; [30:32] := 2 }

The probabulity of having 10,20,30,31,32 is in the ration of 1,2,2,2,2 respectively.


If you use the := operator each element of the range has the assigned weight.
If you want to weight for the whole group,use :/ and the weight is distributed equally
for each element in that group.

Var dist { 10 := 1; 20 := 2 ; [30:32] :/ 2 }

The probabulity of having 10,20,30,31,32 is in the ration of 1,2,2/3,2/3,2/3


respectively.

To demonstrate the distribution property,hear is an example.

EXAMPLE:
class Dist{
rand integer Var;
    constraint range { Var dist { {0,1} := 50 , {2,7} := 50 }; }
}

program Dist_p{
   Dist obj;
   integer count_0, count_1, count_2, count_3, count_4, count_5, count_6, count_7;
   integer count_0_1 ,count_2_7 ;
   obj=new();
   count_0 = 0;count_1 = 0;count_2 = 0;count_3 = 0;
   count_4 = 0;count_5 = 0;count_6 = 0;count_7 = 0;
   count_0_1 = 0;count_2_7 = 0;
  
   for(int i=0; i< 10000; i++)
       if( obj.randomize())
       {
           if( obj.Var == 0) count_0 ++;
           else if( obj.Var == 1) count_1 ++;
           else if( obj.Var == 2) count_2 ++;
           else if( obj.Var == 3) count_3 ++;
           else if( obj.Var == 4) count_4 ++;
           else if( obj.Var == 5) count_5 ++;
           else if( obj.Var == 6) count_6 ++;
           else if( obj.Var == 7) count_7 ++;

           if( obj.Var inside {0,1} ) count_0_1 ++;


           else if( obj.Var inside {[2:7]} ) count_2_7 ++;
       }
  
   printf(" count_0 = %0d , count_1 = %0d, count_2 = %0d, count_3 = %0d, count_4 =
%0d, count_5 = %0d, count_6 = %0d, count_7= %0d
",count_0, count_1, count_2, count_3, count_4, count_5, count_6, count_7);
   printf(" count_0_1 = %0d ;count_2_7 = %0d ",count_0_1,count_2_7);
}

RESULTS:

http://testbench.in/OV_26_CONSTRAINT_EXPRESSION.html[9/26/2012 2:48:33 PM]


WWW.TESTBENCH.IN - Vera Constructs

count_0 = 2450 , count_1 = 2420, count_2 = 1114, count_3 = 1071, count_4 = 871,
count_5 = 812, count_6 = 621, count_7= 641
count_0_1 = 4870 ;count_2_7 = 5130

Now change the constraint to

constraint range { Var dist { {0,1} :/ 50 , {2,7} :/ 50 }; }

EXAMPLE:
class Dist{
    rand integer Var;
    constraint range { Var dist { {0,1} :/ 50 , {2,7} :/ 50 }; }
}

program Dist_p{
    Dist obj;
    integer count_0, count_1, count_2, count_3, count_4, count_5, count_6, count_7;
    integer count_0_1 ,count_2_7 ;
    obj=new();
    count_0 = 0;count_1 = 0;count_2 = 0;count_3 = 0;
    count_4 = 0;count_5 = 0;count_6 = 0;count_7 = 0;
    count_0_1 = 0;count_2_7 = 0;
    
    for(int i=0; i< 10000; i++)
       if( obj.randomize())
       {
           if( obj.Var == 0) count_0 ++;
           else if( obj.Var == 1) count_1 ++;
           else if( obj.Var == 2) count_2 ++;
           else if( obj.Var == 3) count_3 ++;
           else if( obj.Var == 4) count_4 ++;
           else if( obj.Var == 5) count_5 ++;
           else if( obj.Var == 6) count_6 ++;
           else if( obj.Var == 7) count_7 ++;

           if( obj.Var in {0,1} ) count_0_1 ++;


           else if( obj.Var in {2,7}} ) count_2_7 ++;
        }

      printf(" count_0 = %0d , count_1 = %0d, count_2 = %0d, count_3 = %0d, count_4 =
%0d, count_5 = %0d, count_6 = %0d, count_7= %0d
",count_0, count_1, count_2, count_3, count_4, count_5, count_6, count_7);
      printf(" count_0_1 = %0d ;count_2_7 = %0d ",count_0_1,count_2_7);
}
RESULTS:

count_0 = 1245 , count_1 = 1242, count_2 = 1211, count_3 = 1271, count_4 = 1287,
count_5 = 1212, count_6 = 1221, count_7= 1241
count_0_1 = 2487 ;count_2_7 = 7513

Both the reults show,how may times each value occured.

NOTE:If no wait is specified for items,the default weight is 1.


Weight 0 is also allowed.
NOTE:Variable declared as randc are not allowed int dist.

Implication

Implication operator can be used to predirect a relation.The syntax is expression ->


constraint set.
If the expression is true,then the constraint solver should satisfy the constraint set.
The booliean equvalant of a -> b is (!a || b).

rand bit a;
rand bit [3:0] b;
constraint c { (a == 0) -> (b == 1); }

The probabulity of a = 0 is 1/2**5,as bidirectional constraints are solved at once,the


solver pics the random value from the possible set of {a,b} which has 2**5 solutions.

http://testbench.in/OV_26_CONSTRAINT_EXPRESSION.html[9/26/2012 2:48:33 PM]


WWW.TESTBENCH.IN - Vera Constructs

EXAMPLE:
  class impli{
rand bit Var;
rand bit [3:0] b;
constraint c { (Var == 0) => (b == 1); }
}
                                                                                                                            
program impli_p{
impli obj;
integer count_0 ,count_1,i ;
obj=new();
count_0 = 0;count_1 = 0;
for(i=0; i< 10000; i++)
{
obj = new();
if( obj.randomize())
{
if( obj.Var == 0 ) count_0 ++;
else if( obj.Var == 1 ) count_1 ++;
}}
printf(" count_0 = %0d;count_1 = %0d;",count_0 ,count_1);


RESULTS:

 count_0 = 2047;count_1 = 7953

If..Else

Just like implication, if...else style constraints are bidirectional.Above example


applies hear too.

EXAMPLE:
class if_else{
rand bit a;
rand bit [3:0] b;
constraint c { if(a == 0) (b == 1); }
}
                                                                                                                            
program if_else_p{
if_else obj;
integer count_0 ,count_1 ;
obj=new();
count_0 = 0;count_1 = 0;
for(int i=0; i< 10000; i++)
{
obj = new();
if( obj.randomize())
{
if( obj.Var == 0 ) count_0 ++;
else if( obj.Var == 1 ) count_1 ++;
}}
printf(" count_0 = %0d;count_1 = %0d;",count_0 ,count_1);
}
RESULTS

 count_0 = 2047;count_1 = 7953

Iterative

Iterative constraints allow Constraining individual fixed-size, dynamic, associative, or


queue elements.
foreach construct specifies iteration over the elements of array.

EXAMPLE:
class Eth_pkt{
rand byte Payload[*] ;
constraint size_c { Payload.size() inside {[46:1500]}; }
constraint element_c { foreach ( Payload[ i ] )  Payload[ i ] inside {[50:100]}; }
}

http://testbench.in/OV_26_CONSTRAINT_EXPRESSION.html[9/26/2012 2:48:33 PM]


WWW.TESTBENCH.IN - Vera Constructs

program iterative{
 Eth_pkt obj;
obj = new();
for(int i=0;i< 10000;i++)
{
if(obj.randomize())
printf(" RANDOMIZATION DONE ");
}}

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OV_26_CONSTRAINT_EXPRESSION.html[9/26/2012 2:48:33 PM]


WWW.TESTBENCH.IN - Vera Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS VARIABLE ORDARING Index


Variable Ordaring Introduction
SystemVerilog Data Types
Verification openvera allows to control the order of randomization variables.The solution space Linked List
remains the same,but the probabulity of picking up the values changes.the syntax for Operators Part 1
Constructs variable ordering is "solve x before y".The exact meaning of this statement is "choos x Operators Part 2
Interface befor y"  as the this state ment if to guide the distribution,but not the solution space. Operators Part 3
Only rand variables are allowed. Operator Precedence
OOPS Control Statements
Randomization EXAMPLE: Procedures And Methods
class Var_order{ Interprocess
Functional Coverage Fork Join
rand bit a;
Assertion rand bit [3:0] b; Shadow Variables
constraint bidirectional { a -> b == 0; }} Fork Join Control
DPI Wait Var
UVM Tutorial The probabulity of a=1 is 1/2**5,as bidirectional constraints are solved at once,the Event Sync
solver pics the random value from the possible set of {a,b} which has 2**5 solutions.To Event Trigger
VMM Tutorial Semaphore
make the probability of a= 0 to 50% and a = 1 to 50% ,use
OVM Tutorial Regions
constraint order { solve Var1 before Var2 ;} Mailbox
Easy Labs : SV
Timeouts
Easy Labs : UVM This guides the solver to give highest priority to Var1 than Var2.This is explicit Oop
variable ordaring.The solver follows the implicit variable ordaring also,like randc are Casting
Easy Labs : OVM
solved before rand variables,in dynamix arrays size and elements are solved with two Randomization
Easy Labs : VMM constraints,and size is solved before element. Randomization Methods
AVM Switch TB Constraint Block
class var_order{ Constraint Expression
VMM Ethernet sample rand bit Var; Variable Ordaring
rand bit [3:0] b; Aop
constraint c { if(Var == 0) (b == 1); } Predefined Methods
Verilog constraint order { solve Var before b ;} String Methods
Queue Methods
Verification
} Dut Communication
Verilog Switch TB                                                                                                                              Functional Coverage
Basic Constructs program var_order_{
var_order obj; Report a Bug or Comment
integer count_0 ,count_1,i ; on This section - Your
obj=new(); input is what keeps
OpenVera count_0 = 0;count_1 = 0; Testbench.in improving
Constructs for(i=0; i< 10000; i++) with time!
Switch TB {
obj = new();
RVM Switch TB if( obj.randomize())
RVM Ethernet sample {
if( obj.Var == 0 ) count_0 ++;
else if( obj.Var == 1 ) count_1 ++;
}}
Specman E printf(" count_0 = %0d;count_1 = %0d;",count_0 ,count_1);
Interview Questions }
RESULTS:

 count_0 = 5120;count_1 = 4880

Too many explicit variable ordering may lead to circular dependency.The LRM says
that "Circular dependencies created by the implicit variable ordering shall result in an
error." and "circular dependency is not allowed".
But it does not put restriction on what to do if a explicit circular dependency

http://testbench.in/OV_27_VARIABLE_ORDARING.html[9/26/2012 2:48:42 PM]


WWW.TESTBENCH.IN - Vera Constructs

exists.Check with your tool,if explicit Circular dependency is existing,it may report
warning,it may fail solver or proceed by just ignoring the order.

EXAMPLE:
program Cir_Dip_p{
class Cir_Dep;
rand integer a,b,c;

constraint a_c { solve a before b ;}


constraint b_c { solve b before c ;}
constraint c_c { solve c before a ;}
}

Cir_Dip obj=new();
void = obj.randomize();
}

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OV_27_VARIABLE_ORDARING.html[9/26/2012 2:48:42 PM]


WWW.TESTBENCH.IN - Vera Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS AOP Index


Aspect Oriented Extensions : Introduction
SystemVerilog Data Types
Verification AOP is used in conjunction with object-oriented programming. By compartmentalizing Linked List
aspect code, cross-cutting concerns become easy to deal with. Aspects of a system Operators Part 1
Constructs can be changed, inserted or removed at compile time, and become reusable. Operators Part 2
Interface Operators Part 3
placement : Operator Precedence
OOPS Control Statements
The placement element specifies where code is woven into a method.
Randomization before inserts the code inside a method just Procedures And Methods
before  :: it begins any execution (that included execution of initializers) Interprocess
Functional Coverage
after   :: inserts code at each return statement and at the end of the method’s Fork Join
Assertion block, if it falls through without a return Shadow Variables
statement. Fork Join Control
DPI Wait Var
around  :: executes the code in place of the method’s original code.
UVM Tutorial Event Sync
Event Trigger
VMM Tutorial Semaphore
EXAMPLE : aop around
OVM Tutorial class aop { Regions
task disp(){ Mailbox
Easy Labs : SV
printf(" aop class "); Timeouts
Easy Labs : UVM ihop($ori_lin); Oop
} Casting
Easy Labs : OVM
} Randomization
Easy Labs : VMM Randomization Methods
AVM Switch TB extends eaop (aop){ Constraint Block
around task disp(){ Constraint Expression
VMM Ethernet sample printf("eaop class "); Variable Ordaring
} Aop
Predefined Methods
Verilog program main{ String Methods
aop obj; Queue Methods
Verification
obj = new(); Dut Communication
Verilog Switch TB obj.disp(); Functional Coverage
Basic Constructs }
Report a Bug or Comment
RESULTS on This section - Your
input is what keeps
OpenVera eaop class Testbench.in improving
Constructs with time!
Switch TB
EXAMPLE : aop before
RVM Switch TB class aop {
RVM Ethernet sample task disp(){
printf(" aop class ");
}
}
Specman E
Interview Questions extends eaop (aop){
before task disp(){
printf("eaop class ");
}

program main{
aop obj;
obj = new();
obj.disp();
}

http://testbench.in/OV_28_AOP.html[9/26/2012 2:48:52 PM]


WWW.TESTBENCH.IN - Vera Constructs

RESULTS

eaop class
aop class

EXAMPLE : aop after


class aop {
task disp(){
printf(" aop class ");
}
}

extends eaop (aop){
after task disp(){
printf("eaop class ");
}

program main{
aop obj;
obj = new();
obj.disp();
}

RESULTS

aop class
eaop class

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OV_28_AOP.html[9/26/2012 2:48:52 PM]


WWW.TESTBENCH.IN - Vera Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PREDEFINED METHODS Index


Predefined Methods: Introduction
SystemVerilog Data Types
Verification OpenVera Predefined Methods :: Linked List
# Class Methods Operators Part 1
Constructs # String Methods Operators Part 2
Interface # Smart Queue Methods Operators Part 3
# Functional Coverage Operator Precedence
OOPS Control Statements
Randomization OpenVera Class Methods :: Procedures And Methods
# new() Interprocess
Functional Coverage Fork Join
# Randomize Methods
Assertion # Object Print Shadow Variables
# Deep Object Compare Fork Join Control
DPI Wait Var
# Deep Object Copy
UVM Tutorial # Pack and Unpack by Class Methods Event Sync
Event Trigger
VMM Tutorial Semaphore
OVM Tutorial New(): Regions
Mailbox
Easy Labs : SV
In OpenVera, new() is a special method that allocates memory for an object and Timeouts
Easy Labs : UVM assigns a handle to that object. Oop
Casting
Easy Labs : OVM
EXAMPLE : new() Randomization
Easy Labs : VMM class Demo Randomization Methods
AVM Switch TB { Constraint Block
integer x; Constraint Expression
VMM Ethernet sample task new () Variable Ordaring
{printf (" Object of Demo is created ");} Aop
} Predefined Methods
Verilog String Methods
program main { Queue Methods
Verification
Demo D; Dut Communication
Verilog Switch TB D = new(); Functional Coverage
Basic Constructs }
RESULTS Report a Bug or Comment
on This section - Your
Object of Demo is created . input is what keeps
OpenVera Testbench.in improving
Constructs with time!
Switch TB Finalize()
RVM Switch TB When the garbage collector determines that there are no more references to an
RVM Ethernet sample object, it will implicitly call finalize() just before the memory occupied by an object
is reclaimed.

Specman E
Interview Questions Object_print

The entire object instance hierarchy can be sent to stdout or to a specified file using
the object_print() method. As the deep print routine recurses down the object
instance hierarchy, object members and array elements are indented as they are
printed. All the super object members are displayed with the same indentation.

EXAMPLE :object_print
#include <vera_defines.vrh>
enum colors {red, green, black, white};
class embed{

http://testbench.in/OV_29_PREDEFINED_METHODS.html[9/26/2012 2:49:02 PM]


WWW.TESTBENCH.IN - Vera Constructs

integer i;
colors col;
reg[3:0] bits_mem;
string str_mem;
}
class simple{
integer a,b,c,d; // integers
colors col; // enum
reg[3:0] abc; // bit vector
embed e;
string str; // string_var
}
program main{
simple abc = new;
abc.e = new;
abc.a = 123;
abc.b = 111111111;
abc.d = 12345;
abc.col = red;
abc.abc[3:0] = 4´b1100;
abc.object_print();

RESULTS

a : dec: 123
b : dec: 111111111
c:X
d : dec: 12345
col : ENUM:red
abc : hex: c
e : OBJECT of CLASS embed
i:X
col : ENUM:X
bits_mem : bin: xxxx
str_mem : NULL
str : NULL

Deep Object Compare

Object_compare() is a predefined function for all Vera classes that performs a


comparison of two objects of the same class type. The compiler generates errors for
invalid types.All members of the two objects are compared. This includes the
comparison of contained objects.

EXAMPLE : object_compare()
class MyClass
{integer A;
}
program object_compare_ex
{
MyClass object1, object2;
object1 = new(); 
object2 = object1.object_copy();

if(!object1.object_compare(object2) )
error("Object compare failed\n");
else
printf("Objects are the same\n");

http://testbench.in/OV_29_PREDEFINED_METHODS.html[9/26/2012 2:49:02 PM]


WWW.TESTBENCH.IN - Vera Constructs

}
RESULTS

printf("Objects are the same\n");

Deep Object Copy

object_copy() is defined as a virtual function that copies the contents of a source


object into a destination object. The object copy is deep, replicating the entire data
structure including contained objects and the super object.

EXAMPLE : object_copy()
MyClass src_obj, dest_obj;
src_obj = new();
dest_obj = src_obj.object_copy();// dest_obj and
// src_object are now duplicates
if (dest_obj == null) error("Copy failed\n");
else printf(" Copy done ");
RESULTS

Copy done

Pack And Unpack

Data packing is integrated into the object-oriented framework of OpenVera. OpenVera


defines several class methods that are used to pack and unpack data declared within
a class.
pre_pack and post_pack: OpenVera provides the pre_pack() and post_pack() methods.
These methods are called automatically before and after pack().
pre_unpack and post_unpack: OpenVera provides pre_unpack() and post_unpack()
methods. These called automatically before and after unpack().

EXAMPLE :
class Serial_Data_Type {
static integer total_inst_count = 0;
packed {
rand reg [19:0] bit_data;
string comment;
}
task new() {
integer status;
status = this.randomize();
if ( !status )
error ("Randomize failed!\n");
comment = psprintf("comment_%0d", total_inst_count) ;
printf("inst = %-9d , data = %-25b comment =
%0s\n",total_inst_count, bit_data, comment );
total_inst_count++ ;
} // new
}
program packed_test {
Serial_Data_Type sdata_arr[5];
reg data_stream[]; // does not have to be byte stream
integer i, offset, left, right;
printf ("\n\nPacking data ...........\n");
offset = 0; left = 0; right = 0;
for ( i = 0; i < 5; i++ ) {
sdata_arr[i] = new();
void = sdata_arr[i].pack (data_stream, offset, left,right );
} // for
printf ("\n\nUnpacking data in order .....\n");
offset = 0; left = 0; right = 0;
for ( i = 0; i < 5; i++ ) {
void = sdata_arr[i].unpack ( data_stream, offset,left, right );
printf("inst = %-9d , data = %-25b comment =
%0s\n", i, sdata_arr[i].bit_data, sdata_arr[i].comment );
} // for
} // packed_test
RESULTS

Packing data ...........

http://testbench.in/OV_29_PREDEFINED_METHODS.html[9/26/2012 2:49:02 PM]


WWW.TESTBENCH.IN - Vera Constructs

inst = 0         , data = 00010000111000000000      comment = comment_0


inst = 1         , data = 10011000010000111000      comment = comment_1
inst = 2         , data = 10010011100110000110      comment = comment_2
inst = 3         , data = 00110000110001011100      comment = comment_3
inst = 4         , data = 00110000011111001110      comment = comment_4
 
 
Unpacking data in order .....
inst = 0         , data = 00010000111000000000      comment = comment_0
inst = 1         , data = 10011000010000111000      comment = comment_1
inst = 2         , data = 10010011100110000110      comment = comment_2
inst = 3         , data = 00110000110001011100      comment = comment_3
inst = 4         , data = 00110000011111001110      comment = comment_4

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OV_29_PREDEFINED_METHODS.html[9/26/2012 2:49:02 PM]


WWW.TESTBENCH.IN - Vera Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS STRING METHODS Index


Introduction
SystemVerilog Vera provides a set of general methods to handle hidden values within string Data Types
Verification variables. Linked List
Operators Part 1
Constructs len()          : The len() function returns the length of the string as an integer. Operators Part 2
Interface getc()         : The getc() function returns an integer that is the ASCII equivalent to the Operators Part 3
character at specified location. Operator Precedence
OOPS Control Statements
tolower()      : The tolower() function changes upper case characters in a string to
Randomization lower case, and returns this new string. Procedures And Methods
toupper()      : The toupper() function changes lower case characters in a string to Interprocess
Functional Coverage Fork Join
upper case, and returns this new string.
Assertion putc()         : The putc() task assigns a given character to a specified location. Shadow Variables
get_status()   : The get_status() function returns the current status flag value as an Fork Join Control
DPI Wait Var
integer.
UVM Tutorial get_status_msg(): The get_status_msg() function returns a string describing the Event Sync
current status flag value. Event Trigger
VMM Tutorial Semaphore
compare()      : The compare() function compares two strings to determine if they are
OVM Tutorial identical or not. The comparison is case sensitive . If the strings are identical, a 0 is Regions
returned. Mailbox
Easy Labs : SV
icompare()     : The icompare() function is the same as compare() except that case is Timeouts
Easy Labs : UVM ignored. If the strings are identical, a 0 is returned. A non zero value is returned if Oop
they are not identical. Casting
Easy Labs : OVM
hash()         : The hash() function hashes (or encodes) the string and returns a non- Randomization
Easy Labs : VMM negative integer that is less than the size specified. Randomization Methods
AVM Switch TB substr()       : The substr() function returns the sub-string of characters between two Constraint Block
specified locations. Constraint Expression
VMM Ethernet sample search()       : The search() function searches for a pattern in the string and returns Variable Ordaring
the integer index to the beginning of the pattern. Aop
match()        : match() processes a regular expression pattern match. Predefined Methods
Verilog prematch()     :  prematch() returns the string before a match, based on the result of String Methods
the last match() function call. Queue Methods
Verification
postmatch()    : postmatch() returns the string after a match, based on the result of Dut Communication
Verilog Switch TB the last match() function call. Functional Coverage
Basic Constructs thismatch()    : thismatch() returns the matched string, based on the result of the last
match() function call. Report a Bug or Comment
backref()      : backref() returns matched patterns, based on the last match() function on This section - Your
call. input is what keeps
OpenVera atoi()         : atoi() returns the integer corresponding to the ASCII decimal Testbench.in improving
Constructs representation of a string. with time!
Switch TB itoa()         : The itoa() task converts an integer to an ASCII number in a string.
atooct()       : atooct() handles a string as an ASCII octal number and converts it to a
RVM Switch TB bit value.
RVM Ethernet sample atobin()       : atobin() handles a string as an ASCII binary number and converts it to a
bit value.

Specman E EXAMPLE : string


Interview Questions program main{
string str,str_1,str_2; 
str = "This is a string"; 
str_1 = str ;
printf("String length = %0d\n", str.len() );//
printf ("The fourth character is the letter %c.\n", str.getc(3) );
printf ("Lower case string is $s \n",str.tolower() );
printf ("Upper case string is $s \n",str.toupper() );
str.putc(0, "1");
printf (" Str after put 1 at 0 loc is %s \n",str);
printf (" Comparing str and str_1 resulted %d \n",str.compare(str_1) );

http://testbench.in/OV_30_STRING_METHODS.html[9/26/2012 2:49:12 PM]


WWW.TESTBENCH.IN - Vera Constructs

printf (" Substring from 2 to 4 of str is %s\n",str.substr(2,4) );


printf (" searching for 'is a' in str resulted in %d",str.search("is a") );
printf (" matching for 'is' in str resulted in %d",str.match("is") );
str_2 = "123";
printf ("After execute string.atoi method  = %d\n",str_2.atoi() );

RESULTS

String length = 16
The fourth character is the letter s.
Lower case string is this is a string
Upper case string is THIS IS A STRING
Str after put 1 at 0 loc is 1his is a string
Comparing str and str_1 resulted 0
Substring from 2 to 4 of str is is
searching for 'is a' in str resulted in 5
matching for 'is' in str resulted in 1
After execute string.atoi method  = 123

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OV_30_STRING_METHODS.html[9/26/2012 2:49:12 PM]


WWW.TESTBENCH.IN - Vera Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS QUEUE METHODS Index


Introduction
SystemVerilog OpenVera provides the following types of built-in methods for analyzing and Data Types
Verification manipulating smart queue elements. Linked List
# Add/Delete Operators Part 1
Constructs - delete() Operators Part 2
Interface - insert() Operators Part 3
# Order Operator Precedence
OOPS Control Statements
- reverse()
Randomization - rsort() Procedures And Methods
- sort() Interprocess
Functional Coverage Fork Join
- sum()
Assertion # Push/Pop Shadow Variables
- pop_back() Fork Join Control
DPI Wait Var
- pop_front()
UVM Tutorial - push_back() Event Sync
- push_front() Event Trigger
VMM Tutorial Semaphore
# Random
OVM Tutorial - pick() Regions
- pick_index() Mailbox
Easy Labs : SV
- unique() Timeouts
Easy Labs : UVM - unique_index() Oop
# Search Casting
Easy Labs : OVM
- find() Randomization
Easy Labs : VMM - find_index() Randomization Methods
AVM Switch TB - first() Constraint Block
- first_index() Constraint Expression
VMM Ethernet sample - last() Variable Ordaring
- last_index() Aop
- max() Predefined Methods
Verilog - max_index() String Methods
- min() Queue Methods
Verification
- min_index() Dut Communication
Verilog Switch TB # Size Functional Coverage
Basic Constructs - capacity()
- empty() Report a Bug or Comment
- reserve() on This section - Your
- size() input is what keeps
OpenVera Testbench.in improving
Constructs with time!
Switch TB EXAMPLE :
program main{
RVM Switch TB integer que[$];
RVM Ethernet sample printf(" size of queue %d \n",que.size());
que.push_back(10);
que.push_front(2);
printf(" pop_back is %d \n",que.pop_back());
Specman E printf(" pop_front is %d \n",que.pop_front());
Interview Questions
que.push_back(1);
que.push_back(2);
que.push_back(3);
printf(" size of queue %d \n",que.size());
que.insert(2,6);
printf(" pop_back is %d \n",que.pop_back());
printf(" pop_back is %d \n",que.pop_back());
}

RESULTS

http://testbench.in/OV_31_QUEUE_METHODS.html[9/26/2012 2:49:19 PM]


WWW.TESTBENCH.IN - Vera Constructs

 size of queue 0
 pop_back is 10
 pop_front is 2
 size of queue 3
 pop_back is 3
 pop_back is 6

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OV_31_QUEUE_METHODS.html[9/26/2012 2:49:19 PM]


WWW.TESTBENCH.IN - Vera Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS DUT COMMUNICATION Index


Connecting To Hdl: Introduction
SystemVerilog Data Types
Verification OpenVera can communicate to HDL in the following ways. Linked List
Operators Part 1
Constructs # Interface Declaration Operators Part 2
Interface # Interface Signal Connection Operators Part 3
# Virtual Port Signal Connection Operator Precedence
OOPS Control Statements
# signal_connect() System Function
Randomization # Referencing Signals Procedures And Methods
# Retrieving Signal Properties Interprocess
Functional Coverage Fork Join
# HDL Tasks
Assertion Shadow Variables
Fork Join Control
DPI Wait Var
Interface Declaration :
UVM Tutorial Event Sync
The interface specification is used to group Vera signals by clock domain. Each Event Trigger
VMM Tutorial Semaphore
interface may include, at most, one input signal of type CLOCK. The non-clock signals
OVM Tutorial defined in an interface are sampled and driven on the edges of this clock. If an input Regions
signal of type CLOCK is not designated, then the interface signals are synchronized Mailbox
Easy Labs : SV
using SystemClock. Timeouts
Easy Labs : UVM Oop
These are examples of signal declarations with various signal types: Casting
Easy Labs : OVM
Randomization
Easy Labs : VMM EXAMPLE : interface declaration Randomization Methods
AVM Switch TB interface abd { Constraint Block
input clk CLOCK; Constraint Expression
VMM Ethernet sample input [31:0] address PSAMPLE #-1; Variable Ordaring
inout [7:0] data PSAMPLE #-1 PHOLD #1; Aop
output rdy PHOLD #1; Predefined Methods
Verilog output sig_out PHOLD NHOLD #1; String Methods
inout [7:0] data PSAMPLE NSAMPLE #-1 PHOLD NHOLD #1; Queue Methods
Verification
} Dut Communication
Verilog Switch TB Functional Coverage
Basic Constructs
Direct Hdl Node Connection: Report a Bug or Comment
on This section - Your
A Vera interface signal can be connected to any user-specified HDL signal in a design input is what keeps
OpenVera using the hdl_node option. Testbench.in improving
Constructs with time!
Switch TB EXAMPLE : hdl_node
hdl_node CLOCK "hdl_path";
RVM Switch TB
RVM Ethernet sample Blocking And Non-Blocking Drives:

Blocking drives suspend Vera execution until the statement completes. Note that the
clock edge (NHOLD or PHOLD) that the drive signal is associated with is used for
Specman E counting synchronized edges during suspension. Once the statement completes, Vera
Interview Questions execution resumes.Non-blocking drives schedule the drive at a future synchronized
edge and Vera execution continues. When the specified synchronized edge occurs, the
drive is executed.

EXAMPLE : Blocking and Nonblocking


@2 ram_bus.data = 1; // blocking drive
a = b;
@2 ram_bus.data <= 1; // non-blocking drive
a = b;

http://testbench.in/OV_32_DUT_COMMUNICATION.html[9/26/2012 2:49:28 PM]


WWW.TESTBENCH.IN - Vera Constructs

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OV_32_DUT_COMMUNICATION.html[9/26/2012 2:49:28 PM]


WWW.TESTBENCH.IN - Vera Constructs

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS FUNCTIONAL COVERAGE Index


Introduction
SystemVerilog Functional Coverage : Data Types
Verification Linked List
Operators Part 1
Constructs OpenVera is able to monitor all states and state transitions, as well as changes to Operators Part 2
Interface variables and expressions.By setting up a number of monitor bins that correspond to Operators Part 3
states, transitions, and expression changes, Vera is able to track activity in the Operator Precedence
OOPS Control Statements
simulation. Each time a user-specified activity occurs, a counter associated with the
Randomization bin is incremented. Procedures And Methods
Interprocess
Functional Coverage Fork Join
Assertion Coverage Group Shadow Variables
Fork Join Control
DPI Wait Var
The coverage_group construct specifies the coverage model. It is defined either at the
UVM Tutorial top level (referred to as "standalone"), or defined in a class (referred to as Event Sync
"embedded") The syntax is the same for both. Event Trigger
VMM Tutorial Semaphore
OVM Tutorial EXAMPLE : Coverage group Regions
class MyClass Mailbox
Easy Labs : SV
{ Timeouts
Easy Labs : UVM bit [0:7] m_x, m_y; Oop
coverage_group cov1 Casting
Easy Labs : OVM
{ Randomization
Easy Labs : VMM sample_event = @(posedge CLOCK); Randomization Methods
AVM Switch TB sample m_x, m_y; Constraint Block
} Constraint Expression
VMM Ethernet sample } Variable Ordaring
Aop
Sample_event: Predefined Methods
Verilog String Methods
sample_event defines when (or frequency at which) the coverage objects are Queue Methods
Verification
sampled. Dut Communication
Verilog Switch TB Functional Coverage
Basic Constructs EXAMPLE : Sampling event
sample_event = wait_var(open_vera_variable); Report a Bug or Comment
sample_event = sync(ALL | ANY, some_OpenVera_event); on This section - Your
input is what keeps
OpenVera Testbench.in improving
Constructs Coverage_point with time!
Switch TB
Cover point define the points that are sampled by the coverage_group. They are
RVM Switch TB declared using the sample construct of a coverage_group.
RVM Ethernet sample
EXAMPLE : Cover point
class MyClass
{
Specman E bit [0:7] m_x, m_y;
Interview Questions coverage_group cov1
{
sample_event = @(posedge CLOCK);
sample m_x, m_y;
}
}

Cross Coverage :

cross coverage is crossing subsets of the coverage points being sampled by a


coverage_group. Crosses of coverage points of a coverage_group can be specified

http://testbench.in/OV_33_FUNCTIONAL_COVERAGE.html[9/26/2012 2:49:37 PM]


WWW.TESTBENCH.IN - Vera Constructs

using the cross construct.

EXAMPLE : cross coverage:


class MyClass
{
bit [0:7] m_x, m_y;
coverage_group cov1
{
sample_event = @(posedge CLOCK);
sample m_x, m_y;
cross cxy (m_x,m_y);
}
}

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OV_33_FUNCTIONAL_COVERAGE.html[9/26/2012 2:49:37 PM]


WWW.TESTBENCH.IN - Vera Switch TestBench

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS DUT SPECIFICATION Index


Dut Specification
SystemVerilog Rtl
Verification This DUT is a simple switch, which can drive the incoming packet to destination ports Top
based on the address contained in the packet. Interface
Constructs Packet
Interface The dut contain one input interface from which the packet enters the dut. It has four Packet Generator
output interfaces where the packet is driven out. Cfg Driver
OOPS Driver
Randomization Reciever
Scoreboard
Functional Coverage Env
Assertion
Report a Bug or Comment
DPI on This section - Your
UVM Tutorial input is what keeps
Testbench.in improving
VMM Tutorial
with time!
OVM Tutorial
Easy Labs : SV
Easy Labs : UVM
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

Verilog
Verification
Verilog Switch TB
Basic Constructs

Packet format:
OpenVera
Constructs Packet contains Header, data and frame check sequence. Packet width is 8 bits and
Switch TB the length of the packet can be between 4 bytes to 259 bytes.

RVM Switch TB Packet header:


RVM Ethernet sample Packet header contains three fields DA, SA and length.
DA: Destination address of the packet. It is 8 bits. The switch drives the packet to
respective ports based on this destination address of the packets.
SA: Source address of the packet from where it originate.
Specman E Length: This is the length of the data. It can be from 0 to 255.
Interview Questions
Data: Data should be in terms of bytes. It can be between 0 to 255 bytes.

FCS: This field contains the security check of the packet. It is calculated over the
header and data.

http://testbench.in/OS_01_DUT_SPECIFICATION.html[9/26/2012 2:49:44 PM]


WWW.TESTBENCH.IN - Vera Switch TestBench

Configuration:

Dut has four output ports. These output ports have to be configure to a address. Dut
matches the DA field of the packet with this configured port address and sends the
packet on to that port. To configure the dut, a memory interface is provided. The
address of the ports should be unique. It is 8 bits wide. Memory address (0,1,2,3)
contains the address of port(0,1,2,4) respectively.

Interface Specification:

The dut has one input Interface, from where the packet enters the dut and 4 output
interfaces from where the packet comes out and one memory interface, through the
port address can be configured.

Memory Interface:

Through memory interfaced output port address are configured. It accepts 8 bit data
to be written to memory. It has 8 bit address inputs. Address 0,1,2,3 contains the
address of the port 0,1,2,3 respectively. If the DA feild in the packet matches with
the confugured address of any port ,then the packet comes out of that  port.

Input Interface:

The status signal has to be high when data is when packet is sent on to the dut it has
to become low after sending last byte of the packet.
When the dut is busy, and if it is not in a position to accept any more data, it will
assert busy signal. Data which is sent during this busy signal is lost if input is driving
when busy is high

Output Interface:

There are 4 ports, each having data, ready and read signals.

When the data is ready to be sent out from the port, dut makes the ready signal high
indicating that data is ready to be sent.
If the read signal is made high when ready is high, then the data comes out of the
data signal.

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/OS_01_DUT_SPECIFICATION.html[9/26/2012 2:49:44 PM]


WWW.TESTBENCH.IN - Vera Switch TestBench

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OS_01_DUT_SPECIFICATION.html[9/26/2012 2:49:44 PM]


WWW.TESTBENCH.IN - Vera Switch TestBench

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS RTL Index


CODE: switch.v Dut Specification
SystemVerilog module fifo (clk, Rtl
Verification              reset, Top
             write_enb, Interface
Constructs              read, Packet
Interface              data_in, Packet Generator
             data_out, Cfg Driver
OOPS Driver
             empty,
Randomization              full); Reciever
input     clk; Scoreboard
Functional Coverage Env
input     reset;
Assertion input write_enb;
input read; Report a Bug or Comment
DPI on This section - Your
input  [7:0] data_in;
UVM Tutorial output [7:0] data_out; input is what keeps
output empty; Testbench.in improving
VMM Tutorial
output full; with time!
OVM Tutorial wire     clk;
Easy Labs : SV wire write_enb;
wire read;
Easy Labs : UVM wire   [7:0] data_in;
Easy Labs : OVM reg    [7:0] data_out;
wire empty;
Easy Labs : VMM wire full;
AVM Switch TB reg      [7:0] ram[0:25];
reg            tmp_empty;
VMM Ethernet sample reg            tmp_full;
integer        write_ptr;
integer        read_ptr;
Verilog    always@(negedge reset)
Verification    begin
      data_out  = 8'b0000_0000;
Verilog Switch TB       tmp_empty = 1'b1;
Basic Constructs       tmp_full  = 1'b0;
      write_ptr = 0;
      read_ptr  = 0;
   end
OpenVera
Constructs    assign empty = tmp_empty;
Switch TB    assign full  = tmp_full;
 always @(posedge clk) begin 
RVM Switch TB       if ((write_enb == 1'b1) &&  (tmp_full == 1'b0)) begin
RVM Ethernet sample          ram[write_ptr] = data_in;
         tmp_empty <= 1'b0;
         write_ptr = (write_ptr + 1) % 16;
         if ( read_ptr == write_ptr ) begin
Specman E             tmp_full <= 1'b1;
Interview Questions          end 
      end 

 if ((read == 1'b1) &&  (tmp_empty == 1'b0)) begin


         data_out <= ram[read_ptr];
         tmp_full <= 1'b0;
         read_ptr = (read_ptr + 1) % 16;
         if ( read_ptr == write_ptr ) begin
            tmp_empty <= 1'b1;
         end 
      end 

http://testbench.in/OS_02_RTL.html[9/26/2012 2:49:52 PM]


WWW.TESTBENCH.IN - Vera Switch TestBench

   end  
endmodule //fifo

module port_fsm (clk,


                 reset,
                 write_enb,
                 ffee,
                 hold,
                 data_status,
                 data_in,
                 data_out,
                 mem0,
                 mem1,
                 mem2,
                 mem3,
                 addr);
input      clk;
input      reset;
input   [7:0]   mem0;
input   [7:0]   mem1;
input   [7:0]   mem2;
input   [7:0]   mem3;
output[3:0]  write_enb;
input  ffee;
input      hold;
input      data_status;
input[7:0]  data_in;
output[7:0]  data_out;
output  [7:0]     addr;
reg [7:0]  data_out;
reg [7:0]  addr;
reg    [3:0] write_enb_r;
reg          fsm_write_enb;
reg    [3:0] state_r;
reg    [3:0] state;
reg    [7:0] parity;
reg    [7:0] parity_delayed;
reg          sus_data_in,error;

parameter ADDR_WAIT   = 4'b0000;


parameter DATA_LOAD   = 4'b0001;
parameter PARITY_LOAD = 4'b0010;
parameter HOLD_STATE  = 4'b0011;
parameter BUSY_STATE  = 4'b0100;

  always@(negedge reset)
  begin
       error            = 1'b0;
       data_out       = 8'b0000_0000;
       addr           = 8'b00000000;
       write_enb_r    = 3'b000;
       fsm_write_enb  = 1'b0;
       state_r        = 4'b0000;
       state          = 4'b0000;
       parity         = 8'b0000_0000;
       parity_delayed = 8'b0000_0000;
       sus_data_in    = 1'b0;
  end
  assign busy = sus_data_in;
  always @(data_status) begin : addr_mux
    if (data_status == 1'b1) begin
      case (data_in)
      mem0 :  begin
            write_enb_r[0] = 1'b1;
            write_enb_r[1] = 1'b0;
            write_enb_r[2] = 1'b0;
            write_enb_r[3] = 1'b0;
      end
      mem1 :  begin

http://testbench.in/OS_02_RTL.html[9/26/2012 2:49:52 PM]


WWW.TESTBENCH.IN - Vera Switch TestBench

        write_enb_r[0] = 1'b0;
        write_enb_r[1] = 1'b1;
        write_enb_r[2] = 1'b0;
        write_enb_r[3] = 1'b0;
       end
      mem2 :  begin
        write_enb_r[0] = 1'b0;
        write_enb_r[1] = 1'b0;
        write_enb_r[2] = 1'b1;
        write_enb_r[3] = 1'b0;
      end
      
      mem3 :  begin
        write_enb_r[0] = 1'b0;
        write_enb_r[1] = 1'b0;
        write_enb_r[2] = 1'b0;
        write_enb_r[3] = 1'b1;
     end
     default :write_enb_r = 3'b000;
    endcase
  //  $display(" data_inii %d ,mem0 %d ,mem1 %d ,mem2 %d
mem3",data_in,mem0,mem1,mem2,mem3);
     end //if
end //addr_mux;
 always @(posedge clk) begin : fsm_state
     state_r <= state;
  end //fsm_state;

  always @(state_r or data_status or ffee or hold or data_in)


  begin : fsm_core
  state = state_r;   //Default state assignment
      case (state_r)
        ADDR_WAIT :   begin
                  if ((data_status == 1'b1) &&
                      ((mem0 == data_in)||(mem1 == data_in)||(mem3
== data_in) ||(mem2 == data_in))) begin
                     if (ffee == 1'b1) begin
                       state = DATA_LOAD;
                     end
                     else begin
                       state = BUSY_STATE;
                     end //if
                   end //if;
                  sus_data_in = !ffee;
                  if ((data_status == 1'b1) &&
                      ((mem0 == data_in)||(mem1 == data_in)||(mem3
== data_in) ||(mem2 == data_in)) &&
                      (ffee == 1'b1)) begin
                          addr = data_in;
                          data_out  = data_in;
                          fsm_write_enb = 1'b1;
                        
                  end
                  else begin
                      fsm_write_enb = 1'b0;
                  end //if
                end // of case ADDR_WAIT
         PARITY_LOAD : begin
                  state = ADDR_WAIT;
                  data_out = data_in;
                  fsm_write_enb = 1'b0;
                end // of case PARITY_LOAD
         DATA_LOAD :   begin
              if ((data_status == 1'b1) &&
               (hold == 1'b0)) begin
                  state = DATA_LOAD;
              end
              else if ((data_status == 1'b0) &&
              (hold == 1'b0)) begin
                  state = PARITY_LOAD;
              end
              else begin
                  state = HOLD_STATE;
              end  //if

http://testbench.in/OS_02_RTL.html[9/26/2012 2:49:52 PM]


WWW.TESTBENCH.IN - Vera Switch TestBench

             sus_data_in = 1'b0;


             if ((data_status == 1'b1) &&
               (hold == 1'b0)) begin
                  data_out = data_in;
                  fsm_write_enb = 1'b1;
             end
             else if ((data_status == 1'b0) &&
              (hold == 1'b0)) begin
                  data_out = data_in;
                  fsm_write_enb = 1'b1;
             end
             else begin
             fsm_write_enb = 1'b0;
             end //if
        end  //end of case DATA_LOAD
       HOLD_STATE :  begin
             if (hold == 1'b1) begin
                  state = HOLD_STATE;
             end
             else if ((hold == 1'b0) && (data_status == 1'b0)) begin
                  state = PARITY_LOAD;
             end
             else begin
                  state = DATA_LOAD;
             end //if
             if (hold == 1'b1) begin
                   sus_data_in = 1'b1;
                   fsm_write_enb = 1'b0;
             end
             else begin
                   fsm_write_enb = 1'b1;
                   data_out = data_in;
             end //if
         end  //end of case HOLD_STATE
            BUSY_STATE :  begin
             if (ffee == 1'b0) begin
                   state = BUSY_STATE;
             end
             else begin
                   state = DATA_LOAD;
             end //if
             if (ffee == 1'b0) begin
                   sus_data_in = 1'b1;
             end
             else begin
                   addr = data_in; // hans
                   data_out  = data_in;
                   fsm_write_enb = 1'b1;
             end //if
         end  //end of case BUSY_STATE
   endcase
  end //fsm_core

  assign write_enb[0] = write_enb_r[0] & fsm_write_enb;
  assign write_enb[1] = write_enb_r[1] & fsm_write_enb;
  assign write_enb[2] = write_enb_r[2] & fsm_write_enb;
  assign write_enb[3] = write_enb_r[3] & fsm_write_enb;

endmodule //port_fsm
module switch (clk,
               reset,
               data_status,
               data,
               port0,
               port1,
               port2,
               port3,
               ready_0,
               ready_1,
               ready_2,
               ready_3,
               read_0,
               read_1,
               read_2,

http://testbench.in/OS_02_RTL.html[9/26/2012 2:49:52 PM]


WWW.TESTBENCH.IN - Vera Switch TestBench

               read_3,
               mem_en,
               mem_rd_wr,
               mem_add,
               mem_data);
input          clk;
input          reset;
input          data_status;
input    [7:0] data;
input mem_en;
input mem_rd_wr;
input [1:0] mem_add;
input  [7:0] mem_data;
output   [7:0] port0;
output   [7:0] port1;
output   [7:0] port2;
output   [7:0] port3;
output         ready_0;
output       ready_1;
output       ready_2;
output       ready_3;
input       read_0;
input       read_1;
input       read_2;
input       read_3;
wire   [7:0] data_out_0;
wire   [7:0] data_out_1;
wire   [7:0] data_out_2;
wire   [7:0] data_out_3;
wire ll0;
wire ll1;
wire ll2;
wire ll3;
wire empty_0;
wire empty_1;
wire empty_2;
wire empty_3;
wire ffee;
wire ffee0;
wire ffee1;
wire ffee2;
wire ffee3;
wire ld0;
wire ld1;
wire ld2;
wire ld3;
wire hold;
wire   [3:0] write_enb;
wire   [7:0] data_out_fsm;
wire   [7:0] addr;

reg  [7:0]mem[3:0];
wire reset;
  fifo queue_0 (.clk     (clk),
                .reset     (reset),
                .write_enb (write_enb[0]),
                .read  (read_0),
                .data_in   (data_out_fsm),
                .data_out  (data_out_0),
                .empty     (empty_0),
                .full      (ll0));

  fifo queue_1 (.clk     (clk),


                .reset     (reset),
                .write_enb (write_enb[1]),
                .read  (read_1),
                .data_in   (data_out_fsm),
                .data_out  (data_out_1),
                .empty     (empty_1),
                .full      (ll1));

  fifo queue_2 (.clk     (clk),


                .reset     (reset),
                .write_enb (write_enb[2]),

http://testbench.in/OS_02_RTL.html[9/26/2012 2:49:52 PM]


WWW.TESTBENCH.IN - Vera Switch TestBench

                .read  (read_2),
                .data_in   (data_out_fsm),
                .data_out  (data_out_2),
                .empty     (empty_2),
                .full      (ll2));

 fifo queue_3 (.clk     (clk),


                .reset     (reset),
                .write_enb (write_enb[3]),
                .read  (read_3),
                .data_in   (data_out_fsm),
                .data_out  (data_out_3),
                .empty     (empty_3),
                .full      (ll3));

  port_fsm in_port (.clk           (clk),


                    .reset           (reset),
                    .write_enb       (write_enb),
                    .ffee      (ffee),
                    .hold            (hold),
                    .data_status    (data_status),
                    .data_in         (data),
                    .data_out        (data_out_fsm),
                    .mem0            (mem[0]),
                    .mem1            (mem[1]),
                    .mem2            (mem[2]),
                    .mem3            (mem[3]),
                    .addr            (addr));
  assign port0 = data_out_0;   //make note assignment only for
                                  //consistency with vlog env
  assign port1 = data_out_1;
  assign port2 = data_out_2;
  assign port3 = data_out_3;
  
  assign ready_0 = ~empty_0;
  assign ready_1 = ~empty_1;
  assign ready_2 = ~empty_2;
  assign ready_3 = ~empty_3;

  assign ffee0 = (empty_0 | ( addr != mem[0])); 


  assign ffee1 = (empty_1 | ( addr != mem[1])); 
  assign ffee2 = (empty_2 | ( addr != mem[2])); 
  assign ffee3 = (empty_3 | ( addr != mem[3])); 

  assign ffee  = ffee0 & ffee1 & ffee2 & ffee3;

  assign ld0 = (ll0 & (addr == mem[0])); 


  assign ld1 = (ll1 & (addr == mem[1])); 
  assign ld2 = (ll2 & (addr == mem[2])); 
  assign ld3 = (ll3 & (addr == mem[3])); 

  assign hold   = ld0 | ld1 | ld2 | ld3;

always@(posedge clk)
begin

if(mem_en)
if(mem_rd_wr)
begin
mem[mem_add]=mem_data;
///$display("%d  %d %d %d %d",mem_add,mem[0],mem[1],mem[2],mem[3]);
end
end
endmodule //router

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/OS_02_RTL.html[9/26/2012 2:49:52 PM]


WWW.TESTBENCH.IN - Vera Switch TestBench

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OS_02_RTL.html[9/26/2012 2:49:52 PM]


WWW.TESTBENCH.IN - Vera Switch TestBench

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS TOP Index


Dut Specification
SystemVerilog Verification Environment: Rtl
Verification Top
This is simple verification environment. Interface
Constructs It has, packet, Packet generator, Driver, Scoreboard, Receiver, Coverage and Config Packet
Interface driver components. Packet Generator
Cfg Driver
OOPS Driver
Randomization Reciever
Scoreboard
Functional Coverage Env
Assertion
Report a Bug or Comment
DPI on This section - Your
UVM Tutorial input is what keeps
Testbench.in improving
VMM Tutorial
with time!
OVM Tutorial
Easy Labs : SV
Easy Labs : UVM
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

Verilog
Top Module:
Verification
Verilog Switch TB Top module contains the instance of the Dut and verification environment.
It also has the clock generator. For more information about clock generation, go
Basic Constructs through TB_CONCEPTS in this website.
Creat an Interface and make an instance of the interface file.
Connect the interface instance to dut.
OpenVera Creat an instance of the program block. Program block containg all the verification
Constructs component.
Switch TB CODE: top
RVM Switch TB module top();
//Declare clock signal
RVM Ethernet sample   reg          clock;
//Signals for Assertion and to view the class proprties in Waveform viewer  
  reg          pkt_status;
Specman E wire            data_status;
wire      [7:0] data_in;
Interview Questions wire     [3:0][7:0] data_out;
wire          [3:0] ready;
wire          [3:0] read;
wire         [7:0] mem_data;
wire         [1:0] mem_add;
wire  reset;
wire  mem_en;
wire  mem_rd_wr;

reg           SystemClock ;
assign  SystemClock = clock;

http://testbench.in/OS_03_TOP.html[9/26/2012 2:50:01 PM]


WWW.TESTBENCH.IN - Vera Switch TestBench

 tb vshell  ( .SystemClock          (SystemClock),
                  .\intf.clk            (clock),
                  .\intf.data_status   (data_status),
                  .\intf.data_in           (data_in),
                  .\intf.data_out_0       (data_out[0]),
                  .\intf.data_out_1       (data_out[1]),
                  .\intf.data_out_2       (data_out[2]),
                  .\intf.data_out_3       (data_out[3]),
                  .\intf.ready_0      (ready[0]),
                  .\intf.ready_1      (ready[1]),
                  .\intf.ready_2      (ready[2]),
                  .\intf.ready_3      (ready[3]),
                  .\intf.read_0      (read[0]),
                  .\intf.read_1      (read[1]),
                  .\intf.read_2      (read[2]),
                  .\intf.read_3      (read[3]),
                  .\intf.mem_data            (mem_data),
                  .\intf.mem_add            (mem_add),
                  .\intf.reset            (reset),
                  .\intf.mem_en            (mem_en),
                  .\intf.mem_rd_wr            (mem_rd_wr)

);

 switch switch1  (.clk          (clock),
                  .reset          (reset),
                  .data_status   (data_status),
                  .data           (data_in),
                  .port0       (data_out[0]),
                  .port1       (data_out[1]),
                  .port2       (data_out[2]),
                  .port3       (data_out[3]),
                  .ready_0     (ready[0]),
                  .ready_1     (ready[1]),
                  .ready_2     (ready[2]),
                  .ready_3     (ready[3]),
                  .read_0     (read[0]),
                  .read_1     (read[1]),
                  .read_2    (read[2]),
                  .read_3    (read[3]),
                  .mem_en         (mem_en),
                  .mem_rd_wr      (mem_rd_wr),
                  .mem_add        (mem_add),
                  .mem_data       (mem_data));

   initial begin
//If you are using always for clock generation, take care not have edge on time 0
   clock = 0;
   forever begin
   #5 clock = !clock;
   end
   end

  
endmodule //top

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/OS_03_TOP.html[9/26/2012 2:50:01 PM]


WWW.TESTBENCH.IN - Vera Switch TestBench

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OS_03_TOP.html[9/26/2012 2:50:01 PM]


WWW.TESTBENCH.IN - Vera Switch TestBench

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INTERFACE Index


Dut Specification
SystemVerilog Define vera shell interface. For the reciver component, use ports. Defing a port and Rtl
Verification connect four binds. Top
Interface
Constructs CODE:interface.vr Packet
Interface interface intf { Packet Generator
Cfg Driver
OOPS Driver
 input           clk                CLOCK              ;
Randomization output    data_status PHOLD       #1 ; Reciever
output[7:0]    data_in PHOLD       #1 ; Scoreboard
Functional Coverage Env
input  [7:0]    data_out_0 PSAMPLE     #-1   ;
Assertion input  [7:0]    data_out_1 PSAMPLE     #-1   ;
input  [7:0]    data_out_2 PSAMPLE     #-1   ; Report a Bug or Comment
DPI on This section - Your
input  [7:0]    data_out_3 PSAMPLE     #-1   ;
UVM Tutorial input is what keeps
input    ready_0 PSAMPLE     #-1   ; Testbench.in improving
VMM Tutorial
input    ready_1 PSAMPLE     #-1   ; with time!
OVM Tutorial input    ready_2 PSAMPLE     #-1   ;
Easy Labs : SV input    ready_3 PSAMPLE     #-1   ;
output   read_0 PHOLD       #1   ;
Easy Labs : UVM output   read_1 PHOLD       #1   ;
Easy Labs : OVM output   read_2 PHOLD       #1   ;
output   read_3 PHOLD       #1   ;
Easy Labs : VMM output    [7:0]   mem_data PHOLD       #1 ;
AVM Switch TB output     [1:0]   mem_add PHOLD       #1 ;
output reset PHOLD       #1 ;
VMM Ethernet sample output mem_en PHOLD       #1  ;
output mem_rd_wr PHOLD       #1 ;
 }
Verilog
Verification port rec_ports {
data_out;
Verilog Switch TB ready;
Basic Constructs read;
}

bind rec_ports rec_0 {
OpenVera data_out intf.data_out_0;
Constructs ready intf.ready_0;
Switch TB read intf.read_0;
}
RVM Switch TB
RVM Ethernet sample bind rec_ports rec_1 {
data_out intf.data_out_1;
ready intf.ready_1;
read intf.read_1;
Specman E }
Interview Questions
bind rec_ports rec_2 {
data_out intf.data_out_2;
ready intf.ready_2;
read intf.read_2;
}

bind rec_ports rec_3 {
data_out intf.data_out_3;
ready intf.ready_3;
read intf.read_3;

http://testbench.in/OS_04_INTERFACE.html[9/26/2012 2:50:09 PM]


WWW.TESTBENCH.IN - Vera Switch TestBench

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OS_04_INTERFACE.html[9/26/2012 2:50:09 PM]


WWW.TESTBENCH.IN - Vera Switch TestBench

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PACKET Index


Dut Specification
SystemVerilog Rtl
Verification Packet is a class with all the fields in the packet randomly. Top
Types of possible packets : Interface
Constructs Packet with DA with one of the configured port address.. Packet
Interface Packets with DA which has unconfigured address. Packet Generator
Packets with valid and invalid length. Cfg Driver
OOPS Driver
Packets with good and bad FCS.
Randomization Payload size types: SMALL, MEDIUM and LARGE Reciever
Scoreboard
Functional Coverage Env
Use Constraints to get valid da.
Assertion Put packet id as the first feild in data. This is for debugging. Looking at the id ,its
easy to identyfy the packet. Report a Bug or Comment
DPI on This section - Your
UVM Tutorial A method to unpack the data. When the reciver recives data, it is at low level. Using input is what keeps
unpack, da,sa,length,data and fcs feilds can be separated. Testbench.in improving
VMM Tutorial
with time!
OVM Tutorial
Easy Labs : SV CODE: packet.vr
////Define the enumerated types for packet payload size type
Easy Labs : UVM //typedef enum payload_size_t { SMALL, MEDIUM, LARGE } ;
Easy Labs : OVM //typedef enum packet_kind_t { GOOD, BAD };
Easy Labs : VMM class packet{
AVM Switch TB //Define the enumerated types for packet payload size type
enum payload_size_t = SMALL, MEDIUM, LARGE  ;
VMM Ethernet sample enum packet_kind_t =  GOOD, BAD ;

rand payload_size_t payload_size; // Control field for the payload size


Verilog rand packet_kind_t packet_kind;   // Control field for GOOD/BAD
Verification bit [7:0] uid;    // Unique id field to identify the packet    
cfg_drvr cfg;          
Verilog Switch TB rand bit [7:0] len;
Basic Constructs rand bit [7:0] da;
rand bit [7:0] sa;

bit [7:0] data[*];//Payload using Dynamic array,size is generated on the fly


OpenVera rand bit [7:0] parity;
Constructs bit [7:0] mem [4];
Switch TB
constraint addr_8bit {(da == mem[3])||(da == mem[0])||(da == mem[1])||(da
RVM Switch TB == mem[2]);}
RVM Ethernet sample
// Constrain the len according the payload_size control field
constraint len_size {
   (payload_size == SMALL  ) => len in  {5 : 6};
Specman E    (payload_size == MEDIUM ) => len in  {7 : 8};
Interview Questions    (payload_size == LARGE  ) => len in {9 : 10}; }

// May be assigned either a good or bad value,parity will be calculated in


portrandomize
constraint parity_type {
   (packet_kind == GOOD  ) => parity == 0;
   (packet_kind == BAD   ) => parity != 0;}

task pre_randomize(){

http://testbench.in/OS_05_PACKET.html[9/26/2012 2:50:17 PM]


WWW.TESTBENCH.IN - Vera Switch TestBench

this.mem[0]=cfg.mem[0];
this.mem[1]=cfg.mem[1];
this.mem[2]=cfg.mem[2];
this.mem[3]=cfg.mem[3];

//////////////////////////////////////////////////////////////
// parity_calc()
//
// Return the byte resulting from xor-ing among all data bytes
// and the byte resulting from concatenating addr and len
//////////////////////////////////////////////////////////////
function bit [7:0] parity_cal(){
integer i;
bit [7:0] result ;
result = 8'hff;
result = result ^ da;
result = result ^ sa;
result = result ^ len;
 data = new [len];
data[0] = uid ;
result = result ^ data[0];

for (i = 1;i<len;i++)
{
data[i] = random();
result = result ^ data[i];
}
parity_cal  = result;
}

//post randomize fun to cal parity


task  post_randomize(){
   parity = parity ^ parity_cal();
   printf("[PKT] da %h sa %h len %h parit %h \n",this.da,this.sa,this.len,this.parity);
}

//new task,uid is assigned when object is created


task new(bit [7:0] i,cfg_drvr cfg){
uid=i;
this.cfg = cfg;
}

//unpacking task for converting recived data to class properties


task byte_unpack(bit [7:0] bytes[$]){
      void = bytes.pop_front();
      printf("[UNPACKING] bytes size %d\n",bytes.size());
      foreach(bytes,i)
      printf("[UNPACKING] bytes %b :%0d\n",bytes[i],i);
      da = bytes.pop_front();
      sa = bytes.pop_front();
      len = bytes.pop_front();
      data = new [len];
      parity = bytes.pop_back();
      foreach (data,i) data[i] = bytes.pop_front();
          

http://testbench.in/OS_05_PACKET.html[9/26/2012 2:50:17 PM]


WWW.TESTBENCH.IN - Vera Switch TestBench

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OS_05_PACKET.html[9/26/2012 2:50:17 PM]


WWW.TESTBENCH.IN - Vera Switch TestBench

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PACKET GENERATOR Index


Dut Specification
SystemVerilog Rtl
Verification Use a class to build packet generator. Make an instance of this class. Packet generator Top
generator generates packets and sends to driver using mailbox. Mailboxis  is used to Interface
Constructs connect the packet generator and driver. Packet generator generates the packet and Packet
Interface randomizes the packet. Then the packet is put into mailbox. Always check whether Packet Generator
the randomization is sucessful and display a message. Cfg Driver
OOPS Driver
Randomization Reciever
CODE: gen.vr Scoreboard
Functional Coverage Env
class generator{
Assertion cfg_drvr cfg;
integer no_of_pkts; Report a Bug or Comment
DPI on This section - Your
packet cur_packet;
UVM Tutorial input is what keeps
task  new(cfg_drvr cfg){ Testbench.in improving
VMM Tutorial
this.cfg = cfg; with time!
OVM Tutorial }
Easy Labs : SV
task gen_pkts(){
Easy Labs : UVM  bit[7:0] l;
Easy Labs : OVM  l = 0;
no_of_pkts = 5;
Easy Labs : VMM        repeat (no_of_pkts)
AVM Switch TB        {
          l++;
VMM Ethernet sample
printf("[GENERATOR] l = %d \n",l);
           cur_packet = new(l,cfg);
Verilog  //Always check whether randomization is sucessesful or not
Verification            if ( cur_packet.randomize() == 1 )
             {
Verilog Switch TB              printf ("[GENERATOR] Randomization Sucessesfull.\n");
Basic Constructs //Drive the packet if Randomization is Sucessesfull
             mailbox_put(gen,cur_packet);
              }
            else
OpenVera              printf ("[GENERATOR] Randomization failed.\n");
Constructs              }
Switch TB            }
RVM Switch TB
RVM Ethernet sample
}

Specman E
Interview Questions

http://testbench.in/OS_06_PACKET_GENERATOR.html[9/26/2012 2:50:26 PM]


WWW.TESTBENCH.IN - Vera Switch TestBench

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OS_06_PACKET_GENERATOR.html[9/26/2012 2:50:26 PM]


WWW.TESTBENCH.IN - Vera Switch TestBench

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS CFG DRIVER Index


Dut Specification
SystemVerilog Rtl
Verification Cfg_driver generates unique address to the three output ports and writes in to dut Top
memory. Interface
Constructs Packet
Interface Packet Generator
CODE:cfg.vr Cfg Driver
OOPS Driver
class cfg_drvr{
Randomization // Declare port_address as randc Reciever
randc bit [7:0] port_address; Scoreboard
Functional Coverage Env
bit [7:0] mem [4];
Assertion task new();
task gen_add(); Report a Bug or Comment
DPI on This section - Your
task drive_add();
UVM Tutorial } input is what keeps
Testbench.in improving
VMM Tutorial
task cfg_drvr::new(){ with time!
OVM Tutorial printf("created cfg object \n");
Easy Labs : SV }
Easy Labs : UVM //task to randomize the port_address
Easy Labs : OVM task cfg_drvr::gen_add(){
if(this.randomize())
Easy Labs : VMM printf("[CFG_DRVR] Randomization done mem add is %h \n",port_address);
AVM Switch TB else
printf("[CFG_DRVR] Randomization failed \n");
VMM Ethernet sample }

//Task to drive the port address to dut


Verilog task cfg_drvr::drive_add(){
Verification integer i;
for(i = 0;i<4 ;i++)
Verilog Switch TB {
Basic Constructs intf.mem_en = 1;
@(posedge intf.clk);
intf.mem_rd_wr = 1;
this.gen_add();
OpenVera @(posedge intf.clk);
Constructs intf.mem_add = i;
Switch TB intf.mem_data = port_address;
mem[i] = port_address;
RVM Switch TB }
RVM Ethernet sample @(posedge intf.clk);
    intf.mem_en=0;
    intf.mem_rd_wr = 0;
    intf.mem_add = 0;
Specman E     intf.mem_data = 0;
Interview Questions
}

http://testbench.in/OS_07_CFG_DRIVER.html[9/26/2012 2:50:33 PM]


WWW.TESTBENCH.IN - Vera Switch TestBench

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OS_07_CFG_DRIVER.html[9/26/2012 2:50:33 PM]


WWW.TESTBENCH.IN - Vera Switch TestBench

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS DRIVER Index


Dut Specification
SystemVerilog Driver is a class.   Rtl
Verification Top
Define a task which gets the packet from mailbox and calls the drive packet. Interface
Constructs Packet
Interface Drive_packet is a task which drives the packet on to interface. Call the coverage Packet Generator
sample task. Cfg Driver
OOPS
Do packing of the packet generate ,so all the packets feilds which are at high level Driver
Randomization are converted in to lovel data. Reciever
Then drive the packet on to dut. Scoreboard
Functional Coverage Env
Add the sent packet to scoreboard expected packet queue.
Assertion
Report a Bug or Comment
DPI on This section - Your
CODE: driver.vr
UVM Tutorial input is what keeps
Testbench.in improving
VMM Tutorial
//Define driver as class,so this block can be ext}ed if needed with time!
OVM Tutorial
Easy Labs : SV class driver{ 
Easy Labs : UVM packet cur_packet;
Easy Labs : OVM
Easy Labs : VMM task new (){
AVM Switch TB void = this.randomize();
printf("created driver object\n ");
VMM Ethernet sample }

//Define task to generate the packet and call the drive task
Verilog task gen_and_drive(){
Verification  integer l;
 l = 0;
Verilog Switch TB printf("[DRIVER] NUMBER PACKETS %d\n ",gen_rator.no_of_pkts);
Basic Constructs         repeat (gen_rator.no_of_pkts)
       {
     void =  mailbox_get(WAIT, gen,cur_packet,CHECK); 
       @(posedge intf.clk);
OpenVera        drive_packet(cur_packet); 
Constructs        }
Switch TB        }
RVM Switch TB
RVM Ethernet sample
task    drive_packet(packet pkt) {
bit [7:0] pkt_packed[*];
integer i;
Specman E printf("[DRIVER] Starting to drive packet to intf %0d len %0d \n",pkt.da,pkt.len);
Interview Questions
//Do packing of generated packet
pkt_packed = new[pkt.len + 4];
pkt_packed[0] = pkt.da;
pkt_packed[1] = pkt.sa;
pkt_packed[2] = pkt.len;
 
foreach(pkt.data,i)
pkt_packed[i+3]=pkt.data[i];
pkt_packed[pkt.len+3]=pkt.parity; 
@(posedge intf.clk);

http://testbench.in/OS_08_DRIVER.html[9/26/2012 2:50:41 PM]


WWW.TESTBENCH.IN - Vera Switch TestBench

foreach(pkt_packed,i)
printf("[PKT drvr] pkt %h at %d\n",pkt_packed[i],i);
// Byte by byte packed data on to DUV
for (i=0;i<pkt.len+3;i++)
{
@ (posedge intf.clk);
intf.data_status = 1 ;
intf.data_in[7:0] = pkt_packed[i];
printf("[PKT drved] pkt %h at %d\n",pkt_packed[i],i);
}
@ (posedge intf.clk);
intf.data_status = 0 ;
intf.data_in[7:0] = pkt.parity ;
//Add the sent packet to scoreboard expected packet queue
score_board.add_exp_packet(pkt);
@(posedge intf.clk);
}

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OS_08_DRIVER.html[9/26/2012 2:50:41 PM]


WWW.TESTBENCH.IN - Vera Switch TestBench

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS RECIEVER Index


Dut Specification
SystemVerilog Rtl
Verification Receiver receives the packet and unpacks the packet and sends the unpacked packet Top
to scoreboard. Interface
Constructs Packet
Interface Reciver is a class. Declare a port . ports allows the reciver to communicate to dut. Packet Generator
Take four instancess of the reciver. Cfg Driver
OOPS Driver
Randomization CODE:receiver.vr Reciever
Scoreboard
Functional Coverage Env
class receiver{
Assertion static integer id;
cfg_drvr cfg; Report a Bug or Comment
DPI on This section - Your
rec_ports ports;
UVM Tutorial // declare  packet to store  received packet input is what keeps
packet rcv_packet; Testbench.in improving
VMM Tutorial
rand integer rcv_delay; with time!
OVM Tutorial integer port_num;
Easy Labs : SV
constraint rev_dela {rcv_delay in {1:5} ;}
Easy Labs : UVM
Easy Labs : OVM task new (cfg_drvr cfg,rec_ports ports){
this.ports = ports;
Easy Labs : VMM this.cfg = cfg;
AVM Switch TB id = 0;
void = this.randomize();
VMM Ethernet sample printf("[RECIVER] created reciver object\n ");
}

Verilog // Define a task to collect data and unpack


Verification       task collect_packets(){
//  Define queue of byte that will hold the received bytes
Verilog Switch TB   bit [7:0] temp;
Basic Constructs   integer i;
  bit [7:0] received_bytes[$] ;
          while(1) {
            
OpenVera              @(posedge ports.$ready);
Constructs             rcv_delay = random() % 10;
Switch TB              repeat (rcv_delay)@(posedge intf.clk);
              
RVM Switch TB                 while (ports.$ready) {
RVM Ethernet sample                 
                ports.$read = 1;

               @(posedge intf.clk);
Specman E                received_bytes.push_back(ports.$data_out);
Interview Questions               printf("[RECIVER] chanel valid 0 data %x num %d\n
",ports.$data_out,received_bytes.size());
               }
               ports.$read = 0;
              

 
repeat (1)@(posedge intf.clk);
rcv_packet=new(id,cfg);
id++;
printf("[RECIVER]pkt id is %d size is %d\n",id,received_bytes.size());

http://testbench.in/OS_09_RECIEVER.html[9/26/2012 2:50:49 PM]


WWW.TESTBENCH.IN - Vera Switch TestBench

//void =  received_bytes.pop_front();
//unpack the recived data
rcv_packet.byte_unpack(received_bytes);
//as queues are used,delete it
received_bytes.delete();

// call the scoreboard task to check the packets


score_board.checkpacket(rcv_packet);
}
}
}

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OS_09_RECIEVER.html[9/26/2012 2:50:49 PM]


WWW.TESTBENCH.IN - Vera Switch TestBench

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS SCOREBOARD Index


Dut Specification
SystemVerilog Rtl
Verification The expected packets are stored in scored board by driver. Top
When ever the receiver sends a actual packet on to score board, the score board gets Interface
Constructs the expected packet out from the storage, where the driver has stored expected Packet
Interface packets, using the packet id. Packet Generator
Then both expected packet and actual packet re compared. If any mismatch ,then the Cfg Driver
OOPS Driver
test failed is reported.
Randomization Reciever
CODE: scoreboard.vr Scoreboard
Functional Coverage Env
Assertion
class scoreboard{ Report a Bug or Comment
DPI on This section - Your
//Declare a queue of packet to store the expected packets
UVM Tutorial  packet exp_pkt[$]; input is what keeps
Testbench.in improving
VMM Tutorial
task add_exp_packet(packet packet_in){ with time!
OVM Tutorial exp_pkt.push_back(packet_in);
Easy Labs : SV }
Easy Labs : UVM task checkpacket(packet packet_out){
Easy Labs : OVM integer i;
packet packet_sent;
Easy Labs : VMM packet_sent=exp_pkt.pop_front();
AVM Switch TB if (packet_sent.da==packet_out.da && packet_sent.sa==packet_out.sa
&& packet_sent.len==packet_out.len && packet_sent.parity==packet_out.parity){
VMM Ethernet sample integer i;
printf("[SCOREBOARD]Data  sent = recived DA %h : %h :: SA  %h : %h :: len %h
:%h  parity %h :%h\n
Verilog ",packet_sent.da,packet_out.da,packet_sent.sa,packet_out.sa,packet_sent.len,packet_out.len, packet_sent.parity,packet_out.parity
Verification );
for (i=0;i<packet_sent.len -1 ;i++)
Verilog Switch TB {
Basic Constructs if(packet_sent.data[i]!=packet_out.data[i])
{
printf("[SCOREBOARD]ERROR data missmatch sent byte %h recived byte
%h\n",packet_sent.data[i],packet_out.data[i]);
OpenVera trigger(err) ;
Constructs }
Switch TB else
printf("[SCOREBOARD] sent byte %h recived byte
RVM Switch TB %h\n",packet_sent.data[i],packet_out.data[i]);
RVM Ethernet sample
}
}
else
Specman E {
Interview Questions printf("[SCOREBOARD][ERROR]Data mismatch sent != recived DA %h : %h :: SA  %h : %h
:: len %h :%h  parity %h :%h
\n",packet_sent.da,packet_out.da,packet_sent.sa,packet_out.sa,packet_sent.len,packet_out.len, packet_sent.parity,packet_out.parity
);

trigger(err);
}

http://testbench.in/OS_10_SCOREBOARD.html[9/26/2012 2:50:57 PM]


WWW.TESTBENCH.IN - Vera Switch TestBench

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OS_10_SCOREBOARD.html[9/26/2012 2:50:57 PM]


WWW.TESTBENCH.IN - Vera Switch TestBench

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS ENV Index


Dut Specification
SystemVerilog Rtl
Verification Its a program block named tb. Top
Define the coverage group for the generated packet Interface
Constructs creat abject of the coverage group Packet
Interface Use initial block to creat driver and recivers and scoreboards. Packet Generator
Call the tasks in these components. Cfg Driver
OOPS Driver
Impliment a logic for error count.
Randomization Define final block. THis prints whether the test is passed or failed. Reciever
Scoreboard
Functional Coverage Env
CODE:env.vr
Assertion program tb{
 reg         bad; Report a Bug or Comment
DPI on This section - Your
 event         err;
UVM Tutorial  integer no_of_errors;  input is what keeps
integer gen ; Testbench.in improving
VMM Tutorial
with time!
OVM Tutorial cfg_drvr cfg ;
Easy Labs : SV generator gen_rator ;
driver driver_obj ;
Easy Labs : UVM scoreboard score_board;
Easy Labs : OVM receiver receiver_obj_0 ;
receiver receiver_obj_1 ;
Easy Labs : VMM receiver receiver_obj_2 ;
AVM Switch TB receiver receiver_obj_3 ;
VMM Ethernet sample gen = alloc(MAILBOX,0,100);

cfg = new();
Verilog gen_rator= new(cfg);
Verification driver_obj = new();
score_board = new();
Verilog Switch TB
Basic Constructs receiver_obj_0 = new(cfg,rec_0);
receiver_obj_1 = new(cfg,rec_1);
receiver_obj_2 = new(cfg,rec_2);
receiver_obj_3 = new(cfg,rec_3);
OpenVera
Constructs no_of_errors = 0;
Switch TB // Reset the dut
   @(posedge intf.clk);
RVM Switch TB      intf.reset = 1;
RVM Ethernet sample     @(posedge intf.clk);
     intf.reset =0;

delay(100);
Specman E //// Configure the dut.
Interview Questions cfg.drive_add();
delay(100);
//// Generate the packets
gen_rator.gen_pkts();

fork
// Forking error counter task
error_counter();
// Fork task to Drive the packets
driver_obj.gen_and_drive();
//// Fork task to collect packets

http://testbench.in/OS_11_ENV.html[9/26/2012 2:51:07 PM]


WWW.TESTBENCH.IN - Vera Switch TestBench

receiver_obj_0.collect_packets();
receiver_obj_1.collect_packets();
receiver_obj_2.collect_packets();
receiver_obj_3.collect_packets();

join none
delay(10000);
printf("\n ***** END OF SIMULATION **** \n");
}

//Check for the error count


task final(){

if(no_of_errors > 0)
printf("\n************TEST FAILED with %d ERRORS************\n",no_of_errors);
else
printf("\n************TEST PASSED************\n");
}
task error_counter(){
while(1){
sync(ALL,err);
@(posedge intf.clk);
no_of_errors++;
}
}

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/OS_11_ENV.html[9/26/2012 2:51:07 PM]


WWW.TESTBENCH.IN - RVM Switch TB

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INTRODUCTION Index


Introduction
SystemVerilog A model of a system or component at an abstraction level higher than RTL in which Rtl
Verification Top
the interface is defined in terms of transactions, rather than signals is called tranction
level modelling. By abstracting out the details transaction level models run faster and Interface
Constructs can be written more easily. Transaction-level modeling is a high-level approach to Program Block
Interface model digital systems where details of communication among modules are separated Environment
from the details of the implementation of functional units or of the communication Packet
OOPS Configuration
architecture. Communication mechanisms such as busses or FIFOs are modeled as
Randomization channels, and are presented to modules using SystemVerilog interfaces. At the Driver
transaction level, the emphasis is more on the functionality of the data transfers - Reciever
Functional Coverage Scoreboard
what data are transferred to and from what locations - and less on their actual
Assertion implementation, that is, on the actual protocol used for data transfer. This approach
DPI makes it easier for reusability. Usually these tranctions are implimented using Report a Bug or Comment
subroutiens. Systemverilog supports tranctional level modelling. The following on This section - Your
UVM Tutorial example uses TLM in SystemVerilog. input is what keeps
Testbench.in improving
VMM Tutorial
Dut Specification: with time!
OVM Tutorial
Easy Labs : SV This DUT is a simple switch, which can drive the incoming packet to destination ports
based on the address contained in the packet.
Easy Labs : UVM
Easy Labs : OVM The dut contain one input interface from which the packet enters the dut. It has four
output interfaces where the packet is driven out.
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

Verilog
Verification
Verilog Switch TB
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

Packet format:

Packet contains Header, data and frame check sequence. Packet width is 8 bits and
the length of the packet can be between 4 bytes to 259 bytes.

Packet header:
Packet header contains three fields DA, SA and length.

http://testbench.in/RV_01_INTRODUCTION.html[9/26/2012 2:51:15 PM]


WWW.TESTBENCH.IN - RVM Switch TB

DA: Destination address of the packet. It is 8 bits. The switch drives the packet to
respective ports based on this destination address of the packets.
SA: Source address of the packet from where it originate.
Length: This is the length of the data. It can be from 0 to 255.

Data: Data should be in terms of bytes. It can be between 0 to 255 bytes.

FCS: This field contains the security check of the packet. It is calculated over the
header and data.

Configuration:

Dut has four output ports. These output ports have to be configure to a address. Dut
matches the DA field of the packet with this configured port address and sends the
packet on to that port. To configure the dut, a memory interface is provided. The
address of the ports should be unique. It is 8 bits wide. Memory address (0,1,2,3)
contains the address of port(0,1,2,4) respectively.

Interface Specification:

The dut has one input Interface, from where the packet enters the dut and 4 output
interfaces from where the packet comes out and one memory interface, through the
port address can be configured.

Memory Interface:

Through memory interfaced output port address are configured. It accepts 8 bit data
to be written to memory. It has 8 bit address inputs. Address 0,1,2,3 contains the
address of the port 0,1,2,3 respectively. If the DA feild in the packet matches with
the confugured address of any port ,then the packet comes out of that  port.

Input Interface:

The status signal has to be high when data is when packet is sent on to the dut it has
to become low after sending last byte of the packet. 2 clocks gap should be
maintained between packets.

Output Interface:

There are 4 ports, each having data, ready and read signals.

When the data is ready to be sent out from the port, dut makes the ready signal high
indicating that data is ready to be sent.
If the read signal is made high when ready is high, then the data comes out of the
data signal.

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/RV_01_INTRODUCTION.html[9/26/2012 2:51:15 PM]


WWW.TESTBENCH.IN - RVM Switch TB

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/RV_01_INTRODUCTION.html[9/26/2012 2:51:15 PM]


WWW.TESTBENCH.IN - RVM Switch TB

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS RTL Index


Introduction
SystemVerilog CODE:rtl.v Rtl
Verification module fifo (clk, Top
             reset, Interface
Constructs              write_enb, Program Block
Interface              read, Environment
             data_in, Packet
OOPS Configuration
             data_out,
Randomization              empty, Driver
             full); Reciever
Functional Coverage Scoreboard
input     clk;
Assertion input     reset;
input write_enb; Report a Bug or Comment
DPI on This section - Your
input read;
UVM Tutorial input  [7:0] data_in; input is what keeps
output [7:0] data_out; Testbench.in improving
VMM Tutorial
output empty; with time!
OVM Tutorial output full;
Easy Labs : SV wire     clk;
wire write_enb;
Easy Labs : UVM wire read;
Easy Labs : OVM wire   [7:0] data_in;
reg    [7:0] data_out;
Easy Labs : VMM wire empty;
AVM Switch TB wire full;
reg      [7:0] ram[0:25];
VMM Ethernet sample reg            tmp_empty;
reg            tmp_full;
integer        write_ptr;
Verilog integer        read_ptr;
Verification    always@(negedge reset)
   begin
Verilog Switch TB       data_out  = 8'b0000_0000;
Basic Constructs       tmp_empty = 1'b1;
      tmp_full  = 1'b0;
      write_ptr = 0;
      read_ptr  = 0;
OpenVera    end
Constructs
Switch TB    assign empty = tmp_empty;
   assign full  = tmp_full;
RVM Switch TB  always @(posedge clk) begin 
RVM Ethernet sample       if ((write_enb == 1'b1) &&  (tmp_full == 1'b0)) begin
         ram[write_ptr] = data_in;
         tmp_empty <= 1'b0;
         write_ptr = (write_ptr + 1) % 16;
Specman E          if ( read_ptr == write_ptr ) begin
Interview Questions             tmp_full <= 1'b1;
         end 
      end 

 if ((read == 1'b1) &&  (tmp_empty == 1'b0)) begin


         data_out <= ram[read_ptr];
         tmp_full <= 1'b0;
         read_ptr = (read_ptr + 1) % 16;
         if ( read_ptr == write_ptr ) begin
            tmp_empty <= 1'b1;
         end 

http://testbench.in/RV_02_RTL.html[9/26/2012 2:51:23 PM]


WWW.TESTBENCH.IN - RVM Switch TB

      end 
   end  
endmodule //fifo

module port_fsm (clk,


                 reset,
                 write_enb,
                 ffee,
                 hold,
                 data_status,
                 data_in,
                 data_out,
                 mem0,
                 mem1,
                 mem2,
                 mem3,
                 addr);
input      clk;
input      reset;
input   [7:0]   mem0;
input   [7:0]   mem1;
input   [7:0]   mem2;
input   [7:0]   mem3;
output[3:0]  write_enb;
input  ffee;
input      hold;
input      data_status;
input[7:0]  data_in;
output[7:0]  data_out;
output  [7:0]     addr;
reg [7:0]  data_out;
reg [7:0]  addr;
reg    [3:0] write_enb_r;
reg          fsm_write_enb;
reg    [3:0] state_r;
reg    [3:0] state;
reg    [7:0] parity;
reg    [7:0] parity_delayed;
reg          sus_data_in,error;

parameter ADDR_WAIT   = 4'b0000;


parameter DATA_LOAD   = 4'b0001;
parameter PARITY_LOAD = 4'b0010;
parameter HOLD_STATE  = 4'b0011;
parameter BUSY_STATE  = 4'b0100;

  always@(negedge reset)
  begin
       error            = 1'b0;
       data_out       = 8'b0000_0000;
       addr           = 8'b00000000;
       write_enb_r    = 3'b000;
       fsm_write_enb  = 1'b0;
       state_r        = 4'b0000;
       state          = 4'b0000;
       parity         = 8'b0000_0000;
       parity_delayed = 8'b0000_0000;
       sus_data_in    = 1'b0;
  end
  assign busy = sus_data_in;
  always @(data_status) begin : addr_mux
    if (data_status == 1'b1) begin
      case (data_in)
      mem0 :  begin
            write_enb_r[0] = 1'b1;
            write_enb_r[1] = 1'b0;
            write_enb_r[2] = 1'b0;
            write_enb_r[3] = 1'b0;
      end

http://testbench.in/RV_02_RTL.html[9/26/2012 2:51:23 PM]


WWW.TESTBENCH.IN - RVM Switch TB

      mem1 :  begin
        write_enb_r[0] = 1'b0;
        write_enb_r[1] = 1'b1;
        write_enb_r[2] = 1'b0;
        write_enb_r[3] = 1'b0;
       end
      mem2 :  begin
        write_enb_r[0] = 1'b0;
        write_enb_r[1] = 1'b0;
        write_enb_r[2] = 1'b1;
        write_enb_r[3] = 1'b0;
      end
      
      mem3 :  begin
        write_enb_r[0] = 1'b0;
        write_enb_r[1] = 1'b0;
        write_enb_r[2] = 1'b0;
        write_enb_r[3] = 1'b1;
     end
     default :write_enb_r = 3'b000;
    endcase
  //  $display(" data_inii %d ,mem0 %d ,mem1 %d ,mem2 %d
mem3",data_in,mem0,mem1,mem2,mem3);
     end //if
end //addr_mux;
 always @(posedge clk) begin : fsm_state
     state_r <= state;
  end //fsm_state;

  always @(state_r or data_status or ffee or hold or data_in)


  begin : fsm_core
  state = state_r;   //Default state assignment
      case (state_r)
        ADDR_WAIT :   begin
                  if ((data_status == 1'b1) &&
                      ((mem0 == data_in)||(mem1 == data_in)||(mem3
== data_in) ||(mem2 == data_in))) begin
                     if (ffee == 1'b1) begin
                       state = DATA_LOAD;
                     end
                     else begin
                       state = BUSY_STATE;
                     end //if
                   end //if;
                  sus_data_in = !ffee;
                  if ((data_status == 1'b1) &&
                      ((mem0 == data_in)||(mem1 == data_in)||(mem3
== data_in) ||(mem2 == data_in)) &&
                      (ffee == 1'b1)) begin
                          addr = data_in;
                          data_out  = data_in;
                          fsm_write_enb = 1'b1;
                        
                  end
                  else begin
                      fsm_write_enb = 1'b0;
                  end //if
                end // of case ADDR_WAIT
         PARITY_LOAD : begin
                  state = ADDR_WAIT;
                  data_out = data_in;
                  fsm_write_enb = 1'b0;
                end // of case PARITY_LOAD
         DATA_LOAD :   begin
              if ((data_status == 1'b1) &&
               (hold == 1'b0)) begin
                  state = DATA_LOAD;
              end
              else if ((data_status == 1'b0) &&
              (hold == 1'b0)) begin
                  state = PARITY_LOAD;
              end
              else begin
                  state = HOLD_STATE;

http://testbench.in/RV_02_RTL.html[9/26/2012 2:51:23 PM]


WWW.TESTBENCH.IN - RVM Switch TB

              end  //if
             sus_data_in = 1'b0;
             if ((data_status == 1'b1) &&
               (hold == 1'b0)) begin
                  data_out = data_in;
                  fsm_write_enb = 1'b1;
             end
             else if ((data_status == 1'b0) &&
              (hold == 1'b0)) begin
                  data_out = data_in;
                  fsm_write_enb = 1'b1;
             end
             else begin
             fsm_write_enb = 1'b0;
             end //if
        end  //end of case DATA_LOAD
       HOLD_STATE :  begin
             if (hold == 1'b1) begin
                  state = HOLD_STATE;
             end
             else if ((hold == 1'b0) && (data_status == 1'b0)) begin
                  state = PARITY_LOAD;
             end
             else begin
                  state = DATA_LOAD;
             end //if
             if (hold == 1'b1) begin
                   sus_data_in = 1'b1;
                   fsm_write_enb = 1'b0;
             end
             else begin
                   fsm_write_enb = 1'b1;
                   data_out = data_in;
             end //if
         end  //end of case HOLD_STATE
            BUSY_STATE :  begin
             if (ffee == 1'b0) begin
                   state = BUSY_STATE;
             end
             else begin
                   state = DATA_LOAD;
             end //if
             if (ffee == 1'b0) begin
                   sus_data_in = 1'b1;
             end
             else begin
                   addr = data_in; // hans
                   data_out  = data_in;
                   fsm_write_enb = 1'b1;
             end //if
         end  //end of case BUSY_STATE
   endcase
  end //fsm_core

  assign write_enb[0] = write_enb_r[0] & fsm_write_enb;
  assign write_enb[1] = write_enb_r[1] & fsm_write_enb;
  assign write_enb[2] = write_enb_r[2] & fsm_write_enb;
  assign write_enb[3] = write_enb_r[3] & fsm_write_enb;

endmodule //port_fsm
module switch (clk,
               reset,
               data_status,
               data,
               port0,
               port1,
               port2,
               port3,
               ready_0,
               ready_1,
               ready_2,
               ready_3,
               read_0,
               read_1,

http://testbench.in/RV_02_RTL.html[9/26/2012 2:51:23 PM]


WWW.TESTBENCH.IN - RVM Switch TB

               read_2,
               read_3,
               mem_en,
               mem_rd_wr,
               mem_add,
               mem_data);
input          clk;
input          reset;
input          data_status;
input    [7:0] data;
input mem_en;
input mem_rd_wr;
input [1:0] mem_add;
input  [7:0] mem_data;
output   [7:0] port0;
output   [7:0] port1;
output   [7:0] port2;
output   [7:0] port3;
output         ready_0;
output       ready_1;
output       ready_2;
output       ready_3;
input       read_0;
input       read_1;
input       read_2;
input       read_3;
wire   [7:0] data_out_0;
wire   [7:0] data_out_1;
wire   [7:0] data_out_2;
wire   [7:0] data_out_3;
wire ll0;
wire ll1;
wire ll2;
wire ll3;
wire empty_0;
wire empty_1;
wire empty_2;
wire empty_3;
wire ffee;
wire ffee0;
wire ffee1;
wire ffee2;
wire ffee3;
wire ld0;
wire ld1;
wire ld2;
wire ld3;
wire hold;
wire   [3:0] write_enb;
wire   [7:0] data_out_fsm;
wire   [7:0] addr;

reg  [7:0]mem[3:0];
wire reset;
  fifo queue_0 (.clk     (clk),
                .reset     (reset),
                .write_enb (write_enb[0]),
                .read  (read_0),
                .data_in   (data_out_fsm),
                .data_out  (data_out_0),
                .empty     (empty_0),
                .full      (ll0));

  fifo queue_1 (.clk     (clk),


                .reset     (reset),
                .write_enb (write_enb[1]),
                .read  (read_1),
                .data_in   (data_out_fsm),
                .data_out  (data_out_1),
                .empty     (empty_1),
                .full      (ll1));

  fifo queue_2 (.clk     (clk),


                .reset     (reset),

http://testbench.in/RV_02_RTL.html[9/26/2012 2:51:23 PM]


WWW.TESTBENCH.IN - RVM Switch TB

                .write_enb (write_enb[2]),
                .read  (read_2),
                .data_in   (data_out_fsm),
                .data_out  (data_out_2),
                .empty     (empty_2),
                .full      (ll2));

 fifo queue_3 (.clk     (clk),


                .reset     (reset),
                .write_enb (write_enb[3]),
                .read  (read_3),
                .data_in   (data_out_fsm),
                .data_out  (data_out_3),
                .empty     (empty_3),
                .full      (ll3));

  port_fsm in_port (.clk           (clk),


                    .reset           (reset),
                    .write_enb       (write_enb),
                    .ffee      (ffee),
                    .hold            (hold),
                    .data_status    (data_status),
                    .data_in         (data),
                    .data_out        (data_out_fsm),
                    .mem0            (mem[0]),
                    .mem1            (mem[1]),
                    .mem2            (mem[2]),
                    .mem3            (mem[3]),
                    .addr            (addr));
  assign port0 = data_out_0;   //make note assignment only for
                                  //consistency with vlog env
  assign port1 = data_out_1;
  assign port2 = data_out_2;
  assign port3 = data_out_3;
  
  assign ready_0 = ~empty_0;
  assign ready_1 = ~empty_1;
  assign ready_2 = ~empty_2;
  assign ready_3 = ~empty_3;

  assign ffee0 = (empty_0 | ( addr != mem[0])); 


  assign ffee1 = (empty_1 | ( addr != mem[1])); 
  assign ffee2 = (empty_2 | ( addr != mem[2])); 
  assign ffee3 = (empty_3 | ( addr != mem[3])); 

  assign ffee  = ffee0 & ffee1 & ffee2 & ffee3;

  assign ld0 = (ll0 & (addr == mem[0])); 


  assign ld1 = (ll1 & (addr == mem[1])); 
  assign ld2 = (ll2 & (addr == mem[2])); 
  assign ld3 = (ll3 & (addr == mem[3])); 

  assign hold   = ld0 | ld1 | ld2 | ld3;

always@(posedge clk)
begin

if(mem_en)
if(mem_rd_wr)
begin
mem[mem_add]=mem_data;
///$display("%d  %d %d %d %d",mem_add,mem[0],mem[1],mem[2],mem[3]);
end
end
endmodule //router

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/RV_02_RTL.html[9/26/2012 2:51:23 PM]


WWW.TESTBENCH.IN - RVM Switch TB

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/RV_02_RTL.html[9/26/2012 2:51:23 PM]


WWW.TESTBENCH.IN - RVM Switch TB

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS TOP Index


Introduction
SystemVerilog Rtl
Verification Top level module containts the design and testbench instance. Top module also Top
contains clock generator. There is no need to instantiate the top module. Interface
Constructs Testbench and dut instances are connected using wires. Program Block
Interface Environment
Packet
OOPS Configuration
Randomization Driver
Reciever
Functional Coverage Scoreboard
Assertion
Report a Bug or Comment
DPI on This section - Your
UVM Tutorial input is what keeps
Testbench.in improving
VMM Tutorial
with time!
OVM Tutorial
Easy Labs : SV
Easy Labs : UVM
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

CODE: top.v
module top();
Verilog
//Declare clock signal
Verification   reg          clock;
Verilog Switch TB //Signals for Assertion and to view the class proprties in Waveform viewer  
wire            data_status;
Basic Constructs wire      [7:0] data_in;
wire     [7:0] data_out[0:3];
wire          [3:0] ready;
OpenVera wire          [3:0] read;
Constructs wire         [7:0] mem_data;
wire         [1:0] mem_add;
Switch TB wire  reset;
RVM Switch TB wire  mem_en;
wire  mem_rd_wr;
RVM Ethernet sample
wire          SystemClock ;
assign  SystemClock = clock;
Specman E  main tb  ( .SystemClock          (SystemClock),
                  .\intf.clk            (clock),
Interview Questions                   .\intf.data_status   (data_status),
                  .\intf.data_in           (data_in),

                  .\intf.data_out_0       (data_out[0]),
                  .\intf.data_out_1       (data_out[1]),
                  .\intf.data_out_2       (data_out[2]),
                  .\intf.data_out_3       (data_out[3]),
                  .\intf.ready_0      (ready[0]),
                  .\intf.ready_1      (ready[1]),
                  .\intf.ready_2      (ready[2]),
                  .\intf.ready_3      (ready[3]),

http://testbench.in/RV_03_TOP.html[9/26/2012 2:51:32 PM]


WWW.TESTBENCH.IN - RVM Switch TB

                  .\intf.read_0      (read[0]),
                  .\intf.read_1      (read[1]),
                  .\intf.read_2      (read[2]),
                  .\intf.read_3      (read[3]),
                  .\intf.mem_data            (mem_data),
                  .\intf.mem_add            (mem_add),
                  .\intf.reset            (reset),
                  .\intf.mem_en            (mem_en),
                  .\intf.mem_rd_wr            (mem_rd_wr)

);

 switch switch1  (.clk          (clock),
                  .reset          (reset),
                  .data_status   (data_status),
                  .data           (data_in),
                  .port0       (data_out[0]),
                  .port1       (data_out[1]),
                  .port2       (data_out[2]),
                  .port3       (data_out[3]),
                  .ready_0     (ready[0]),
                  .ready_1     (ready[1]),
                  .ready_2     (ready[2]),
                  .ready_3     (ready[3]),
                  .read_0     (read[0]),
                  .read_1     (read[1]),
                  .read_2    (read[2]),
                  .read_3    (read[3]),
                  .mem_en         (mem_en),
                  .mem_rd_wr      (mem_rd_wr),
                  .mem_add        (mem_add),
                  .mem_data       (mem_data));

   initial begin
   clock = 0;
   forever begin
   #5 clock = !clock;
   end
   end

  
endmodule //top

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/RV_03_TOP.html[9/26/2012 2:51:32 PM]


WWW.TESTBENCH.IN - RVM Switch TB

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INTERFACE Index


Introduction
SystemVerilog Rtl
Verification Declare an inyerface. Declare ports for reciever block. Bind the four reciver port. Top
Interface
Constructs CODE:interface Program Block
Interface interface intf { Environment
Packet
OOPS Configuration
 input           clk                CLOCK              ;
Randomization output    data_status PHOLD       #1 ; Driver
output[7:0]    data_in PHOLD       #1 ; Reciever
Functional Coverage Scoreboard
input  [7:0]    data_out_0 PSAMPLE     #-1   ;
Assertion input  [7:0]    data_out_1 PSAMPLE     #-1   ;
input  [7:0]    data_out_2 PSAMPLE     #-1   ; Report a Bug or Comment
DPI on This section - Your
input  [7:0]    data_out_3 PSAMPLE     #-1   ;
UVM Tutorial input is what keeps
input    ready_0 PSAMPLE     #-1   ; Testbench.in improving
VMM Tutorial
input    ready_1 PSAMPLE     #-1   ; with time!
OVM Tutorial input    ready_2 PSAMPLE     #-1   ;
Easy Labs : SV input    ready_3 PSAMPLE     #-1   ;
output   read_0 PHOLD       #1   ;
Easy Labs : UVM output   read_1 PHOLD       #1   ;
Easy Labs : OVM output   read_2 PHOLD       #1   ;
output   read_3 PHOLD       #1   ;
Easy Labs : VMM output    [7:0]   mem_data PHOLD       #1 ;
AVM Switch TB output     [1:0]   mem_add PHOLD       #1 ;
output reset PHOLD       #1 ;
VMM Ethernet sample output mem_en PHOLD       #1  ;
output mem_rd_wr PHOLD       #1 ;
 }
Verilog
Verification port rec_ports {
data_out;
Verilog Switch TB ready;
Basic Constructs read;
}

bind rec_ports rec_0 {
OpenVera data_out intf.data_out_0;
Constructs ready intf.ready_0;
Switch TB read intf.read_0;
}
RVM Switch TB
RVM Ethernet sample bind rec_ports rec_1 {
data_out intf.data_out_1;
ready intf.ready_1;
read intf.read_1;
Specman E }
Interview Questions
bind rec_ports rec_2 {
data_out intf.data_out_2;
ready intf.ready_2;
read intf.read_2;
}

bind rec_ports rec_3 {
data_out intf.data_out_3;
ready intf.ready_3;
read intf.read_3;

http://testbench.in/RV_04_INTERFACE.html[9/26/2012 2:51:40 PM]


WWW.TESTBENCH.IN - RVM Switch TB

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/RV_04_INTERFACE.html[9/26/2012 2:51:40 PM]


WWW.TESTBENCH.IN - RVM Switch TB

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PROGRAM BLOCK Index


Introduction
SystemVerilog Testbench Program Rtl
Verification Top
Program block contains the instance of testbench environment class. Testcases goes Interface
Constructs hear. Call run() method of env instance. Program Block
Interface Environment
CODE:test Packet
OOPS Configuration
program main{
Randomization Driver
Environment env; Reciever
Functional Coverage Scoreboard
Assertion env = new();
env.run_t(); Report a Bug or Comment
DPI on This section - Your
UVM Tutorial printf(" END OF PROGRAM BLOCK \n"); input is what keeps
} Testbench.in improving
VMM Tutorial
with time!
OVM Tutorial
Easy Labs : SV
Easy Labs : UVM
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

Verilog
Verification
Verilog Switch TB
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/RV_05_PROGRAM_BLOCK.html[9/26/2012 2:51:48 PM]


WWW.TESTBENCH.IN - RVM Switch TB

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/RV_05_PROGRAM_BLOCK.html[9/26/2012 2:51:48 PM]


WWW.TESTBENCH.IN - RVM Switch TB

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS ENVIRONMENT Index


Introduction
SystemVerilog Rtl
Verification Enviroment class contains instancess of all the verification components. Environment Top
class is extension on rvm_env class. Interface
Constructs The testbench simulation needs some systamatic flow like reset,initilize etc. rvm_env Program Block
Interface base class has methods to support this simulation flow. Environment
The rvm_env class divides a simulation into the following steps, with corresponding Packet
OOPS Configuration
methods:
Randomization -- gen_cfg() : Randomize test configuration descriptor Driver
-- build() : Allocate and connect test environment components Reciever
Functional Coverage Scoreboard
-- reset_dut_t() : Reset the DUT
Assertion -- cfg_dut_t() : Download test configuration into the DUT
-- start_t() : Start components Report a Bug or Comment
DPI on This section - Your
-- wait_for_end_t() : End of test detection
UVM Tutorial -- stop_t() : Stop data generators and wait for DUT to drain input is what keeps
-- cleanup_t() : Check recorded statistics and sweep for lost data Testbench.in improving
VMM Tutorial
-- report() : Print final report with time!
OVM Tutorial
Easy Labs : SV
Easy Labs : UVM CODE:env.vr
Easy Labs : OVM //A top-level source file shall include all ancillary source files
#include <rvm_std_lib.vrh>
Easy Labs : VMM #include "Configuration.vr"
AVM Switch TB #include "packet.vr"
#include "ports.vr"
VMM Ethernet sample
`ifndef ENV_CLASS
`define ENV_CLASS
Verilog
Verification //A channel class shall be declared for any class derived from the bu_data class
Verilog Switch TB rvm_channel(packet)
Basic Constructs
//An instance of a rvm_channel object shall be used to pass transactions between two
transactors
OpenVera rvm_atomic_gen(packet,"packet")
Constructs
Switch TB #include "drvr.vr"
#include "rcvr.vr"
RVM Switch TB #include "score_board.vr"
RVM Ethernet sample
class Environment extends rvm_env {

//All simulation log output shall be done through the message service.
Specman E
Interview Questions   rvm_log              log;
   Configuration       cfg;
   packet              pkt;
   packet_atomic_gen   gen;

   packet_channel      gen2drv_chan;
   packet_channel      rcv2sb_chan;
   packet_channel      drv2sb_chan;
  
   drvr_xtor          drvr;
   rcvr_xtor           rcvr_0;

http://testbench.in/RV_06_ENVIRONMENT.html[9/26/2012 2:52:23 PM]


WWW.TESTBENCH.IN - RVM Switch TB

   rcvr_xtor           rcvr_1;
   rcvr_xtor           rcvr_2;
   rcvr_xtor           rcvr_3;
   scoreboard           sb;

   task new();

   virtual task gen_cfg();
   virtual task build();
   virtual task reset_dut_t();
   virtual task cfg_dut_t();
   virtual task start_t();
   virtual task wait_for_end_t();
   virtual task stop_t();
   virtual task cleanup_t();
   virtual task report();
}

task Environment::new(){
   super.new("Environment");
   this.log = new("ENV_LOG","0");
   this.cfg = new();
   rvm_note(this.log," ENV CREATED \n");
}

//The return value of the randomize() method shall be checked


//and an error be reported if it is FALSE

task Environment::gen_cfg(){
   super.gen_cfg();
   rvm_note(this.log," Starting... Gen_cfg \n");

   if (!cfg.randomize())
   rvm_fatal(this.log, "Configuration Randomization Failed!\n");
    cfg.display();
}

task  Environment::build() {
   super.build();
  rvm_note(this.log," Starting... build \n");
   pkt = new();
   pkt.do_cfg(cfg);
   gen = new("Generator","0");
   gen.stop_after_n_insts = 20;
   gen2drv_chan = new("gen2drv","0");
   rcv2sb_chan = new("rcv2sb","chan",10);
   drv2sb_chan = new("drv2sb","chan",10);
   gen.out_chan = this.gen2drv_chan;
   drvr = new("driver",0,gen2drv_chan,drv2sb_chan);
   rcvr_0 = new("reciver_0",0,rec_0,rcv2sb_chan);
   rcvr_1 = new("reciver_1",1,rec_1,rcv2sb_chan);
   rcvr_2 = new("reciver_2",2,rec_2,rcv2sb_chan);
   rcvr_3 = new("reciver_3",3,rec_3,rcv2sb_chan);
  sb = new(rcv2sb_chan,drv2sb_chan);
}

//Blocking methods shall have a name that ends with the "_t" suffix.

task Environment::reset_dut_t(){
   super.reset_dut_t();
   rvm_note(this.log," Starting... reset_dut \n");
    @(posedge intf.clk);
    intf.data_status  <= 0;
    intf.data_in      <= 0;
    intf.read_0       <= 0;

http://testbench.in/RV_06_ENVIRONMENT.html[9/26/2012 2:52:23 PM]


WWW.TESTBENCH.IN - RVM Switch TB

    intf.read_1       <= 0;
    intf.read_2       <= 0;
    intf.read_3       <= 0;
    intf.mem_data     <= 0;
    intf.mem_add      <= 0;
    intf.reset        <= 0;
    intf.mem_en       <= 0;
    intf.mem_rd_wr    <= 0; 
    @(posedge intf.clk);
    intf.reset     <= 1;
    @(posedge intf.clk);
    intf.reset     <= 0;
    @(posedge intf.clk);
    @(posedge intf.clk);
   rvm_note(this.log," Ending...  reset_dut \n");
}

//The generated value of the configuration descriptor shall be


//downloaded into the DUT in the rvm_env::cfg_dut_t() method

task Environment::cfg_dut_t(){
integer i;
   super.cfg_dut_t();
   rvm_note(this.log," Starting... cfg_dut \n");
   for(i = 0;i<4 ;i++)
   {
   intf.mem_en    <= 1;
   @(posedge intf.clk);
   intf.mem_rd_wr <= 1;
   @(posedge intf.clk);
   intf.mem_add   <= i;
   intf.mem_data  <= cfg.da_port[i];
   }
   @(posedge intf.clk);
    intf.mem_en    <= 0;
    intf.mem_rd_wr <= 0;
    intf.mem_add   <= 0;
    intf.mem_data  <= 0;

   rvm_note(this.log," Ending...  cfg_dut \n");

//The rvm_env::start_t() method shall start all transactors and generators


//The rvm_env::start_t() method should not block the execution thread

task Environment::start_t() {
   super.start_t();
   rvm_note(this.log," Starting... start \n");
   gen.start_xactor();
   drvr.start_xactor();
   rcvr_0.start_xactor();
   rcvr_1.start_xactor();
   rcvr_2.start_xactor();
   rcvr_3.start_xactor();
   sb.start_xactor();
}

task Environment::wait_for_end_t() {
   super.wait_for_end_t();
   rvm_note(this.log," Starting... wait_for_end \n");
  fork//watchdog
  {
   void = gen.notify.wait_for_t(gen.DONE);
   rvm_note(this.log," DONE:: packet_atomic_gen \n");
   repeat(100) @(posedge intf.clk);
   rvm_error(this.log," Watchdog timeout occured \n");
  }
  {
  while(sb.no_rcv_pkt != 20) @(posedge intf.clk);
   rvm_note(this.log," DONE:: total number of sent pkts are receved \n");
  

http://testbench.in/RV_06_ENVIRONMENT.html[9/26/2012 2:52:23 PM]


WWW.TESTBENCH.IN - RVM Switch TB

  }
  join any
   rvm_note(this.log," Ending ... wait_for_end \n");

task Environment::stop_t() {
   super.stop_t();
   rvm_note(this.log," Starting... stop \n");
   this.drvr.stop_xactor();
   this.rcvr_0.stop_xactor();
   this.rcvr_1.stop_xactor();
   this.rcvr_2.stop_xactor();
   this.rcvr_3.stop_xactor();
   this.sb.stop_xactor();
   rvm_note(this.log," Ending ... stop \n");

task Environment::cleanup_t() {
   super.cleanup_t();
   rvm_note(this.log," Starting... cleanup \n");
}

task Environment::report() {
   rvm_note(this.log," Starting... report \n");
   super.report();
   rvm_note(this.log," Ending...  report \n");
}

`endif

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/RV_06_ENVIRONMENT.html[9/26/2012 2:52:23 PM]


WWW.TESTBENCH.IN - RVM Switch TB

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PACKET Index


Introduction
SystemVerilog Rtl
Verification In Vera terminology packets are called tranctions. Tranctions contains the physical Top
data that are to be sent to dut. It also contains some more properties which help in Interface
Constructs building tranctions. Tranctions are built by extending rvm_data. rvm_data has set of Program Block
Interface standered methods like copy(),compare(),byte_pack(),byte_unp Environment
ack() etc. Packet
OOPS Configuration
Randomization CODE:packet.vr Driver
#ifndef PKT_CLASS Reciever
Functional Coverage Scoreboard
#define PKT_CLASS
Assertion
Report a Bug or Comment
DPI on This section - Your
UVM Tutorial input is what keeps
// Data units shall be modeled as objects Testbench.in improving
VMM Tutorial
class packet extends rvm_data { with time!
OVM Tutorial
Easy Labs : SV enum payload_size_t =  SMALL_P, MEDIUM_P, LARGE_P  ;
enum packet_kind_t  =  GOOD_P, BAD_P ;
Easy Labs : UVM rand packet_kind_t packet_kind ;
Easy Labs : OVM rand payload_size_t payload_size;//Control field for the payload size
Easy Labs : VMM
AVM Switch TB static  rvm_log log = new("packet", "class");
string msg;
VMM Ethernet sample
rand bit [7:0] len;
rand bit [7:0] da;
Verilog rand bit [7:0] sa;
Verification
rand bit [7:0] data[*];//Payload using Dynamic array,size is generated on the fly
Verilog Switch TB rand bit [7:0] parity;
Basic Constructs static bit [7:0] mem [4];

constraint addr_8bit {(da == mem[3])||(da == mem[0])||(da == mem[1])||(da


== mem[2]);}
OpenVera
Constructs // Constrain the len according the payload_size control field
Switch TB constraint len_size {
   (payload_size == SMALL_P  ) => len in { 5 : 6};
RVM Switch TB    (payload_size == MEDIUM_P ) => len in { 7 : 8};
RVM Ethernet sample    (payload_size == LARGE_P  ) => len in {9 : 10}; }
// Constrain length of data  == len
constraint data_size { data.size() ==len;}
Specman E
Interview Questions constraint len_siz { solve len before data.size() ;}

// May be assigned either a good or bad value,parity will be calculated in


portrandomize
constraint parity_type {
   (packet_kind == GOOD_P  ) => parity == 0;
   (packet_kind == BAD_P   ) => parity != 0;}

  

http://testbench.in/RV_07_PACKET.html[9/26/2012 2:52:31 PM]


WWW.TESTBENCH.IN - RVM Switch TB

//All data object methods should be virtual


//All data object methods shall be nonblocking
  task new();
  task do_cfg(Configuration cfg);
  virtual function string psdisplay(string prefix );
  virtual function rvm_data copy(rvm_data to);
  virtual function integer byte_unpack(bit [7:0] bytes[*],integer offset
=  0,integer kind = -1);
  virtual function bit[7:0] parity_cal();

  virtual function bit compare(rvm_data to,var string diff,integer kind =-1);


 virtual function integer byte_pack(var bit [7:0] bytes[*],
                                                 integer offset  =0,
                                                 integer   kind=-1);
 task post_randomize();
  

 task packet::new(){
   super.new(this.log);
 }
 
 task packet::do_cfg(Configuration cfg){
    this.mem[0]= cfg.da_port[0];
    this.mem[1]= cfg.da_port[1];
    this.mem[2]= cfg.da_port[2];
    this.mem[3]= cfg.da_port[3];
  msg = psprintf(" packet new %x %x %x %x",mem[0],mem[1],mem[2],mem[3]);
  rvm_note(this.log,msg);
   }
 
 
 function string packet::psdisplay(string prefix = ""){
    integer i;
    
   sprintf(psdisplay,"%s packet
#%0d.%0d.%0d\n", prefix,this.stream_id, this.scenario_id, this.object_id);
   sprintf(psdisplay,"%s%s   da:0x%h  sa:0x%h  len:0x%h
\n", psdisplay, prefix,this.da,this.sa,this.len);
   sprintf(psdisplay, "%s%s   data:", psdisplay, prefix);
    for (i = 0; i < this.len - 1; i++) sprintf(psdisplay,"%s data[%0d]
0x%h", psdisplay,i, data[i]);
 }
 
 
 function rvm_data packet::copy(rvm_data to = null){
    packet cpy;
 
    // Copying to a new instance?
    if (to == null) 
       cpy = new;
     else
 
    // Copying to an existing instance. Correct type?
    if (!cast_assign(cpy, to,CHECK))    
       {
       rvm_fatal(this.log, "Attempting to copy to a non packet instance");
       copy = null;
       return;
       }
    
 
    super.copy_data(cpy);
    
    cpy.da = this.da;
    cpy.sa = this.sa;
    cpy.len = this.len;
    cpy.data = new[this.len];

http://testbench.in/RV_07_PACKET.html[9/26/2012 2:52:31 PM]


WWW.TESTBENCH.IN - RVM Switch TB

    foreach(cpy.data,i)
       cpy.data[i] = this.data[i];              
 
    copy = cpy;
 }
 
 
  
 //unpacking function for converting recived data to class properties
function integer packet::byte_unpack(bit [7:0] bytes[*],integer offset
,integer kind){
      sprintf(msg," bytes size %d",bytes.size());
      da = bytes[1];
      sa = bytes[2];
      len = bytes[3];
 
    sprintf(msg,"packet
#%0d.%0d.%0d\n", this.stream_id, this.scenario_id, this.object_id);
    sprintf(msg,"da:0x%h  sa:0x%h  len:0x%h \n", this.da,this.sa,this.len);
    rvm_note(this.log,msg);
      data = new [len - 4];
      parity = bytes[bytes.size()-1];
      foreach (data,i) data[i] = bytes[i+4];
}
 
function bit[7:0] packet::parity_cal(){
integer i;
bit[7:0] result ;
result = result ^ this.da;
result = result ^ this.sa;
result = result ^ this.len;
for (i = 0;i<this.len;i++)
{
result = result ^ this.data[i];
}
parity_cal = result;
}
 
//post randomize fun to cal parity
task packet::post_randomize(){
   parity = parity ^ parity_cal();
  sprintf(msg," %x %x %x %x",mem[0],mem[1],mem[2],mem[3]);
  rvm_note(this.log,msg);
}

function bit packet::compare(rvm_data   to,var string diff,integer   kind){


    packet cmp;
 
    compare = 1; // Assume success by default.
    diff    = "No differences found";
    
    if (!cast_assign(cmp, to,CHECK)) 
    {  rvm_fatal(this.log, "Attempting to compare to a non packet instance");
       compare = 0;
       diff = "Cannot compare non packets";
       return;
   } 
 
    // data types are the same, do comparison:
    if (this.da != cmp.da) 
        {
       diff = psprintf("Different DA values: %b != %b", this.da, cmp.da);
       compare = 0;
       return;
        }
      
    if (this.sa != cmp.sa) 
        {
       diff = psprintf("Different SA values: %b != %b", this.sa, cmp.sa);
       compare = 0;
       return;
       }
    if (this.len != cmp.len) 

http://testbench.in/RV_07_PACKET.html[9/26/2012 2:52:31 PM]


WWW.TESTBENCH.IN - RVM Switch TB

       {
       diff = psprintf("Different LEN values: %b != %b", this.len, cmp.len);
       compare = 0;
       return;
       }
 
    foreach(data,i) 
       if (this.data[i] != cmp.data[i]) 
        {
          diff = psprintf("Different data[%0d] values: 0x%h !=
0x%h",i, this.data[i], cmp.data[i]);
          compare = 0;
          return;
         } 
    if (this.parity != cmp.parity) 
        {
       diff = psprintf("Different PARITY values: %b != %b", this.parity, cmp.parity);
       compare = 0;
       return;
    }
 }

function integer packet::byte_pack(var bit [7:0] bytes[*],integer offset ,integer  
kind){
byte_pack = 0;
bytes = new[this.len + 4];
bytes[0] = this.da;
bytes[1] = this.sa;
bytes[2] = this.len;
foreach(data,i)
bytes[3+i] = data[i];
bytes[this.len + 3 ] = parity;
byte_pack = this.len + 4;
}      
#endif

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/RV_07_PACKET.html[9/26/2012 2:52:31 PM]


WWW.TESTBENCH.IN - RVM Switch TB

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS CONFIGURATION Index


Introduction
SystemVerilog Rtl
Verification Configuration class is a transctor. It is extention of rvm_xactor. This class genarates Top
addresses to configure the dut 4 output ports. Interface
Constructs Program Block
Interface CODE:CFG.vr Environment
#ifndef PKT_CLASS Packet
OOPS Configuration
#define PKT_CLASS
Randomization Driver
Reciever
Functional Coverage Scoreboard
Assertion
// Data units shall be modeled as objects Report a Bug or Comment
DPI on This section - Your
class packet extends rvm_data {
UVM Tutorial input is what keeps
enum payload_size_t =  SMALL_P, MEDIUM_P, LARGE_P  ; Testbench.in improving
VMM Tutorial
enum packet_kind_t  =  GOOD_P, BAD_P ; with time!
OVM Tutorial rand packet_kind_t packet_kind ;
Easy Labs : SV rand payload_size_t payload_size;//Control field for the payload size
Easy Labs : UVM
Easy Labs : OVM static  rvm_log log = new("packet", "class");
string msg;
Easy Labs : VMM
AVM Switch TB rand bit [7:0] len;
rand bit [7:0] da;
VMM Ethernet sample rand bit [7:0] sa;

rand bit [7:0] data[*];//Payload using Dynamic array,size is generated on the fly


Verilog rand bit [7:0] parity;
Verification static bit [7:0] mem [4];
Verilog Switch TB constraint addr_8bit {(da == mem[3])||(da == mem[0])||(da == mem[1])||(da
Basic Constructs == mem[2]);}

// Constrain the len according the payload_size control field


constraint len_size {
OpenVera    (payload_size == SMALL_P  ) => len in { 5 : 6};
Constructs    (payload_size == MEDIUM_P ) => len in { 7 : 8};
Switch TB    (payload_size == LARGE_P  ) => len in {9 : 10}; }
RVM Switch TB // Constrain length of data  == len
RVM Ethernet sample constraint data_size { data.size() ==len;}
constraint len_siz { solve len before data.size() ;}
Specman E
Interview Questions // May be assigned either a good or bad value,parity will be calculated in
portrandomize
constraint parity_type {
   (packet_kind == GOOD_P  ) => parity == 0;
   (packet_kind == BAD_P   ) => parity != 0;}

  

//All data object methods should be virtual


//All data object methods shall be nonblocking

http://testbench.in/RV_08_CONFIGURATION.html[9/26/2012 2:52:42 PM]


WWW.TESTBENCH.IN - RVM Switch TB

  task new();
  task do_cfg(Configuration cfg);
  virtual function string psdisplay(string prefix );
  virtual function rvm_data copy(rvm_data to);
  virtual function integer byte_unpack(bit [7:0] bytes[*],integer offset
=  0,integer kind = -1);
  virtual function bit[7:0] parity_cal();

  virtual function bit compare(rvm_data to,var string diff,integer kind =-1);


 virtual function integer byte_pack(var bit [7:0] bytes[*],
                                                 integer offset  =0,
                                                 integer   kind=-1);
 task post_randomize();
  

 task packet::new(){
   super.new(this.log);
 }
 
 task packet::do_cfg(Configuration cfg){
    this.mem[0]= cfg.da_port[0];
    this.mem[1]= cfg.da_port[1];
    this.mem[2]= cfg.da_port[2];
    this.mem[3]= cfg.da_port[3];
  msg = psprintf(" packet new %x %x %x %x",mem[0],mem[1],mem[2],mem[3]);
  rvm_note(this.log,msg);
   }
 
 
 function string packet::psdisplay(string prefix = ""){
    integer i;
    
   sprintf(psdisplay,"%s packet
#%0d.%0d.%0d\n", prefix,this.stream_id, this.scenario_id, this.object_id);
   sprintf(psdisplay,"%s%s   da:0x%h  sa:0x%h  len:0x%h
\n", psdisplay, prefix,this.da,this.sa,this.len);
   sprintf(psdisplay, "%s%s   data:", psdisplay, prefix);
    for (i = 0; i < this.len - 1; i++) sprintf(psdisplay,"%s data[%0d]
0x%h", psdisplay,i, data[i]);
 }
 
 
 function rvm_data packet::copy(rvm_data to = null){
    packet cpy;
 
    // Copying to a new instance?
    if (to == null) 
       cpy = new;
     else
 
    // Copying to an existing instance. Correct type?
    if (!cast_assign(cpy, to,CHECK))    
       {
       rvm_fatal(this.log, "Attempting to copy to a non packet instance");
       copy = null;
       return;
       }
    
 
    super.copy_data(cpy);
    
    cpy.da = this.da;
    cpy.sa = this.sa;
    cpy.len = this.len;
    cpy.data = new[this.len];
    foreach(cpy.data,i)
       cpy.data[i] = this.data[i];              
 

http://testbench.in/RV_08_CONFIGURATION.html[9/26/2012 2:52:42 PM]


WWW.TESTBENCH.IN - RVM Switch TB

    copy = cpy;
 }
 
 
  
 //unpacking function for converting recived data to class properties
function integer packet::byte_unpack(bit [7:0] bytes[*],integer offset
,integer kind){
      sprintf(msg," bytes size %d",bytes.size());
      da = bytes[1];
      sa = bytes[2];
      len = bytes[3];
 
    sprintf(msg,"packet
#%0d.%0d.%0d\n", this.stream_id, this.scenario_id, this.object_id);
    sprintf(msg,"da:0x%h  sa:0x%h  len:0x%h \n", this.da,this.sa,this.len);
    rvm_note(this.log,msg);
      data = new [len - 4];
      parity = bytes[bytes.size()-1];
      foreach (data,i) data[i] = bytes[i+4];
}
 
function bit[7:0] packet::parity_cal(){
integer i;
bit[7:0] result ;
result = result ^ this.da;
result = result ^ this.sa;
result = result ^ this.len;
for (i = 0;i<this.len;i++)
{
result = result ^ this.data[i];
}
parity_cal = result;
}
 
//post randomize fun to cal parity
task packet::post_randomize(){
   parity = parity ^ parity_cal();
  sprintf(msg," %x %x %x %x",mem[0],mem[1],mem[2],mem[3]);
  rvm_note(this.log,msg);
}

function bit packet::compare(rvm_data   to,var string diff,integer   kind){


    packet cmp;
 
    compare = 1; // Assume success by default.
    diff    = "No differences found";
    
    if (!cast_assign(cmp, to,CHECK)) 
    {  rvm_fatal(this.log, "Attempting to compare to a non packet instance");
       compare = 0;
       diff = "Cannot compare non packets";
       return;
   } 
 
    // data types are the same, do comparison:
    if (this.da != cmp.da) 
        {
       diff = psprintf("Different DA values: %b != %b", this.da, cmp.da);
       compare = 0;
       return;
        }
      
    if (this.sa != cmp.sa) 
        {
       diff = psprintf("Different SA values: %b != %b", this.sa, cmp.sa);
       compare = 0;
       return;
       }
    if (this.len != cmp.len) 
       {
       diff = psprintf("Different LEN values: %b != %b", this.len, cmp.len);
       compare = 0;

http://testbench.in/RV_08_CONFIGURATION.html[9/26/2012 2:52:42 PM]


WWW.TESTBENCH.IN - RVM Switch TB

       return;
       }
 
    foreach(data,i) 
       if (this.data[i] != cmp.data[i]) 
        {
          diff = psprintf("Different data[%0d] values: 0x%h !=
0x%h",i, this.data[i], cmp.data[i]);
          compare = 0;
          return;
         } 
    if (this.parity != cmp.parity) 
        {
       diff = psprintf("Different PARITY values: %b != %b", this.parity, cmp.parity);
       compare = 0;
       return;
    }
 }

function integer packet::byte_pack(var bit [7:0] bytes[*],integer offset ,integer  
kind){
byte_pack = 0;
bytes = new[this.len + 4];
bytes[0] = this.da;
bytes[1] = this.sa;
bytes[2] = this.len;
foreach(data,i)
bytes[3+i] = data[i];
bytes[this.len + 3 ] = parity;
byte_pack = this.len + 4;
}      
#endif

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/RV_08_CONFIGURATION.html[9/26/2012 2:52:42 PM]


WWW.TESTBENCH.IN - RVM Switch TB

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS DRIVER Index


Introduction
SystemVerilog Rtl
Verification Driver is a tranctor. It is extension of rvm_xactor. Get the packets from gen2drv_chan Top
chennel and drive them on to dut interface. Put the packets in to drv2sb_chan Interface
Constructs channel. Program Block
Interface Environment
CODE:driver.vr Packet
OOPS Configuration
#ifndef DRVR_CLASS
Randomization #define DRVR_CLASS Driver
//Transactors shall be implemented in classes derived from the rvm_xactor Reciever
Functional Coverage Scoreboard
Assertion class drvr_xtor extends rvm_xactor{
   packet_channel   gen2drv_chan; Report a Bug or Comment
DPI on This section - Your
   packet_channel   drv2sb_chan;
UVM Tutorial    packet                     pkt,drv_pkt; input is what keeps
   string                     msg; Testbench.in improving
VMM Tutorial
with time!
OVM Tutorial
Easy Labs : SV task new(string inst = "class",
             integer stream_id = -1,
Easy Labs : UVM              packet_channel   gen2drv_chan = null,
Easy Labs : OVM              packet_channel   drv2sb_chan = null);
Easy Labs : VMM virtual task main_t();
AVM Switch TB virtual task drive(packet pkt);
VMM Ethernet sample }

task drvr_xtor::new(string inst,integer stream_id ,
Verilog              packet_channel   gen2drv_chan ,
Verification              packet_channel   drv2sb_chan ){
super.new("driver",inst,stream_id);
Verilog Switch TB
Basic Constructs if(gen2drv_chan == null)
this.gen2drv_chan = new("gen2drv_channel","chan",10);
else
this.gen2drv_chan = gen2drv_chan;
OpenVera
Constructs if(drv2sb_chan == null)
Switch TB this.drv2sb_chan = new("drv2sb_channel","chan",10);
else
RVM Switch TB this.drv2sb_chan = drv2sb_chan;
RVM Ethernet sample
rvm_note(log,"Driver created \n");
}
Specman E //All threads shall be started in the extension of the rvm_xactor::main_t() method
Interview Questions //Extensions of the rvm_xactor::main_t() method shall fork a call to super.main_t()

task drvr_xtor::main_t(){
    super.main_t();
    rvm_note(this.log," STARTED main task ");
while(1){

//wait_if_stopped_or_empty(this.gen2drv_chan);
pkt = this.gen2drv_chan.get_t();
sprintf(this.msg,"pkt da %x pkt sa %x pkt len %d \n",pkt.da,pkt.sa,pkt.len);
rvm_note(this.log,msg);

http://testbench.in/RV_09_DRIVER.html[9/26/2012 2:52:51 PM]


WWW.TESTBENCH.IN - RVM Switch TB

  if (!cast_assign(drv_pkt, pkt.copy()))
        rvm_fatal(this.log, "Attempting to copy to a non Packet instance");
drive(drv_pkt);
@(posedge intf.clk);
this.drv2sb_chan.sneak(drv_pkt);

}
}

task drvr_xtor::drive(packet pkt){
bit [7:0] pack_pkt[*];
integer pkt_len,i;
pkt_len = pkt.byte_pack(pack_pkt,0,0);
sprintf(this.msg,"Packed packet length %d \n",pkt_len);
rvm_note(this.log,this.msg);
@(posedge intf.clk);
for (i=0;i< pkt_len - 1;i++)
{
@(posedge intf.clk);
intf.data_status <= 1 ;
intf.data_in <= pack_pkt[i];
}
@(posedge intf.clk);
intf.data_status <= 0 ;
intf.data_in <= 0;
@(posedge intf.clk);
}

#endif

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/RV_09_DRIVER.html[9/26/2012 2:52:51 PM]


WWW.TESTBENCH.IN - RVM Switch TB

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS RECIEVER Index


Introduction
SystemVerilog Rtl
Verification Reciever is a tranctor. Start the collection of packet from dut in the main() task and Top
send them to score_board through rcv2sb_chan channel. Interface
Constructs Program Block
Interface CODE:reciever.vr Environment
#include "ports.vr" Packet
OOPS Configuration
#ifndef RCVR_CLASS
Randomization #define RCVR_CLASS Driver
Reciever
Functional Coverage Scoreboard
class rcvr_xtor extends rvm_xactor{
Assertion    packet_channel       rcv2sb_chan;
   packet               pkt,rcv_pkt; Report a Bug or Comment
DPI on This section - Your
   rec_ports            port_;
UVM Tutorial    string                       msg; input is what keeps
   static bit [7:0]         mem[4]; Testbench.in improving
VMM Tutorial
task new(string inst = "class",integer stream_id = -1,rec_ports port_, with time!
OVM Tutorial              packet_channel   rcv2sb_chan = null);
Easy Labs : SV virtual task main_t();
Easy Labs : UVM }
Easy Labs : OVM
Easy Labs : VMM task rcvr_xtor::new(string inst ,integer stream_id ,rec_ports port_,packet_channel  
AVM Switch TB rcv2sb_chan ){
super.new("reciver",inst,stream_id);
VMM Ethernet sample this.port_ = port_;
if(rcv2sb_chan == null)
this.rcv2sb_chan = new("rcv2sb_channel","channel",10);
Verilog else
Verification this.rcv2sb_chan = rcv2sb_chan;
rvm_note(this.log,"Receiver created \n");
Verilog Switch TB pkt = new();
Basic Constructs }

task rcvr_xtor::main_t(){
OpenVera   bit [7:0] received_bytes[*] ;
Constructs     super.main_t();
Switch TB     rvm_note(this.log," STARTED main task ");
  while(1){
RVM Switch TB           @(posedge port_.$ready);
RVM Ethernet sample           while (port_.$ready) {
               port_.$read <= 1;
               @(posedge intf.clk);
               received_bytes = new[received_bytes.size() + 1] (received_bytes);
Specman E                received_bytes[received_bytes.size()-1] = port_.$data_out;
Interview Questions                }
               port_.$read <= 0;

     void =  pkt.byte_unpack(received_bytes);
      received_bytes.delete();
      rcv_pkt = new pkt;
      rcv2sb_chan.put_t(rcv_pkt);
    }
}

#endif

http://testbench.in/RV_10_RECIEVER.html[9/26/2012 2:52:59 PM]


WWW.TESTBENCH.IN - RVM Switch TB

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/RV_10_RECIEVER.html[9/26/2012 2:52:59 PM]


WWW.TESTBENCH.IN - RVM Switch TB

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS SCOREBOARD Index


Introduction
SystemVerilog Rtl
Verification When the packet comes from reciever, the scoreboard gets the expected packet from Top
drv2sb_chan channel and compare them. Interface
Constructs Program Block
Interface CODE:scoreboard.vr Environment
`ifndef SB_CLASS Packet
OOPS Configuration
`define SB_CLASS
Randomization Driver
class scoreboard extends rvm_xactor{ Reciever
Functional Coverage Scoreboard
 packet exp_pkt;
Assertion  packet rcv_pkt;
 integer no_drv_pkt; Report a Bug or Comment
DPI on This section - Your
 integer no_rcv_pkt;
UVM Tutorial  string msg; input is what keeps
 packet_channel rcv2sb_chan; Testbench.in improving
VMM Tutorial
 packet_channel drv2sb_chan; with time!
OVM Tutorial
Easy Labs : SV task new(packet_channel rcv2sb_chan = null,packet_channel drv2sb_chan = null);
virtual task main_t();
Easy Labs : UVM
Easy Labs : OVM }
Easy Labs : VMM task scoreboard::new(packet_channel rcv2sb_chan ,packet_channel drv2sb_chan ){
AVM Switch TB super.new("Scoreboard","sb");
this.drv2sb_chan = drv2sb_chan;
VMM Ethernet sample this.rcv2sb_chan = rcv2sb_chan;
 no_drv_pkt = 0;
 no_rcv_pkt = 0;
Verilog
Verification rvm_note(log,"Scoreboard created");
}
Verilog Switch TB
Basic Constructs
task scoreboard::main_t(){
super.main_t();
    rvm_note(this.log," STARTED main task ");
OpenVera while(1){
Constructs rcv_pkt = rcv2sb_chan.get_t();
Switch TB this.no_rcv_pkt++;
exp_pkt = drv2sb_chan.get_t();
RVM Switch TB this.no_drv_pkt++;
RVM Ethernet sample
if(rcv_pkt.compare(exp_pkt,msg,0))
rvm_note(this.log,msg);
else
Specman E rvm_error(this.log,msg);
Interview Questions } 
}

`endif

http://testbench.in/RV_11_SCOREBOARD.html[9/26/2012 2:53:06 PM]


WWW.TESTBENCH.IN - RVM Switch TB

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/RV_11_SCOREBOARD.html[9/26/2012 2:53:06 PM]


WWW.TESTBENCH.IN

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS
About the author:
SystemVerilog UVM/OVM Killing Sequences on Sequencer Abruptly
Verification Vishnu Prasanth
is ovm/uvm expert. He is
Constructs Sometimes you may need to drive input until you see come condition or some timer currently working with
Interface expires. Once you meet that condition, you need to stop generating stimulus. The Vitesse, Hyderabad,
code for this scenario look like below India.
OOPS
Randomization //Test Connect to Vishnu @
Functional Coverage
begin
fork
Assertion begin
DPI wait(rtl_linkup == 1); Report a Bug or Comment
end on This section - Your
UVM Tutorial begin input is what keeps
VMM Tutorial forever Testbench.in improving
idles_transmit.start(Sequencer); with time!
OVM Tutorial end
Easy Labs : SV join_any
disable fork;
Easy Labs : UVM end
Easy Labs : OVM
Easy Labs : VMM In the above code we are driving idles until rtl_linkup condition is observed. But here
AVM Switch TB there is a problem, As we are trying kill idles_transmit sequence abruptly when
condition is met, this may cause the sequencer to be in intermittent state. This will
VMM Ethernet sample cause the problem on the next sequences which trigger on the same sequencer. As
sequencer is in intermittent state it may not get grant and will wait for for grant
forever. To avoid this problem we need to reset the sequencer after killing threads.
Verilog The code look like below.
Verification
Verilog Switch TB //Test
Basic Constructs begin
fork
begin
wait(rtl_linkup == 1);
OpenVera end
Constructs begin
Switch TB forever
idles_transmit.start(Sequencer);
RVM Switch TB end
RVM Ethernet sample join_any
disable fork;
Sequencer.stop_sequence();
end
Specman E
Interview Questions
In the above code the stop_sequences call will reset the sequencer variables and
won't cause any problem for the next sequences which are triggered on same
sequencer. Here also we have another problem with the sequence thread which is
killed with disable fork. Sometimes by the time thread is killed request might have
been sent to driver. if thread is killed and stop_sequence is called before receiving
the item_done, item_done will cause fatal error as request fifo is empty. So we need
to kill thread and call of stop_sequence only after receiving item_done from driver.
The code will look like below.

http://testbench.in/killing_sequences.html[9/26/2012 2:53:15 PM]


WWW.TESTBENCH.IN

//Sequence .
class idles_transmit extends ovm_sequence #(REQ= packet);
bit received_item_done;
task body();
wait_for_grant();
assert(req.randomize());
send_req(req);
received_item_done = 0;
wait_for_item_done();
received_item_done = 1;
endtask
endclass

//Test

begin
fork
begin
wait(rtl_linkup == 1);
end
begin
forever
idles_transmit.start(Sequencer);
end
join_any
@(posedge idles_transmit.received_item_done);
disable fork;
Sequencer.stop_sequence();
end

In the above code we are trying to kill the thread and reseting sequencer state only
after receiving the ite_done for the request sent, which is the idle way to stop
thread.

copyright © 2007 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/killing_sequences.html[9/26/2012 2:53:15 PM]


WWW.TESTBENCH.IN

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | SITEMAP | LINKS | BLOG | JOBS Search ✔

TUTORIALS
About the author:
SystemVerilog Do not rely on illegal_bins
Verification Ankit Gopani
is ASIC Engineer at
Constructs eInfochips,
Interface Do not rely on illegal_bins for checking purpose. If you rely on cover group where you Ahmedabad,India.
have written illegal_bins, what happens when you turn off the coverage??
OOPS He is a specialties in SoC
Randomization That is where Assertions coming in picture...! If you really want to ignore values then Verification and VIP
use ignore_bins. If you really want to throw errors then use an assertions checkers. development in System
Functional Coverage Verilog VMM.
Assertion While illegal_bins removes values from coverage calculations, it also throws errors.
Philosophically, you need to ask yourself the questions, Visit Ankit's Blog for
DPI more SV stuff
UVM Tutorial (1) "Should a passive component like a cover group be actively throwing errors?" and AsicWithAnkit.BlogSpot.com
VMM Tutorial (2) "If you rely on the cover group for checking, then what happens when you turn
coverage off?"
OVM Tutorial
Easy Labs : SV
covergroup cg @ (posedge clk iff decode); Report a Bug or Comment
Easy Labs : UVM on This section - Your
Easy Labs : OVM     coverpoint opcode { input is what keeps
      bins move_op[] = {3'b000, 3'b001}; Testbench.in improving
Easy Labs : VMM       bins alu_op = {[3'b010:3'b011], [3'b101:3'b110]}; with time!
AVM Switch TB       bins jump_op = {3'b111};
      illegal_bins unused_op = {3'b100};
VMM Ethernet sample   }

Verilog From the example given above, you can see 3'b100 is an illegal op code and as per
Verification protocol if that value occurs then its an error. So here instead of writing and
illegal_bins you can have a assert property with coverage to check specifically this
Verilog Switch TB scenario.
Basic Constructs
It is actually a debatable point because illegal bins will stops simulation if it hits, and
from the last message or from debugging engineer can debug the reason for failure.
The mail point is as it is not allowing the simulation forward, you can not check the
OpenVera functionality in error case. So to avoid this constraint we have assertions with cover
Constructs property which allows us to go ahead with simulation with error indication.
Switch TB
So usually I would prefer to have an assertions (with cover property) where strong
RVM Switch TB protocol check requires instead of writing illegal_bins.
RVM Ethernet sample
Enjoy...!
-ASIC with Ankit
Specman E
Interview Questions

http://testbench.in/Do_not_rely_on_illegal_bins.html[9/26/2012 2:53:23 PM]


WWW.TESTBENCH.IN

copyright © 2007 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/Do_not_rely_on_illegal_bins.html[9/26/2012 2:53:23 PM]


WWW.TESTBENCH.IN

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | SITEMAP | LINKS | BLOG | JOBS Search ✔

TUTORIALS
About the author:
SystemVerilog PASS and FAIL Messages with Colors...!
Verification Ankit Gopani
is ASIC Engineer at
Constructs eInfochips,
Interface How many among you know that you can actually display color messages using Verilog Ahmedabad,India.
and SystemVerilog?
OOPS He is a specialties in SoC
Randomization You can implement a logic in your testbench to have nicely colored display messages Verification and VIP
Functional Coverage
at the end of your simulation which will give you a PASS/FAIL messages. I have development in System
written a piece of code given below and you can refer the same. I have captured a Verilog VMM.
Assertion snapshot of output which you can see below.
Visit Ankit's Blog for
DPI more SV stuff
UVM Tutorial AsicWithAnkit.BlogSpot.com
VMM Tutorial program clr_display();
  class color ;
OVM Tutorial     task display ();
Easy Labs : SV       $display("%c[1;34m",27);
      $display("***************************************"); Report a Bug or Comment
Easy Labs : UVM       $display("*********** TEST CASE PASS ************"); on This section - Your
Easy Labs : OVM       $display("***************************************"); input is what keeps
      $write("%c[0m",27); Testbench.in improving
Easy Labs : VMM        with time!
AVM Switch TB       $display("%c[1;31m",27);
      $display("***************************************");
VMM Ethernet sample       $display("*********** TEST CASE FAIL ************");
      $display("***************************************");
      $display("%c[0m",27);
Verilog     endtask
Verification   endclass
Verilog Switch TB   initial 
Basic Constructs     begin
      color clr;
      clr = new ();
      clr.display ();
OpenVera   end
Constructs endprogram
Switch TB
RVM Switch TB OUTPUT:
RVM Ethernet sample

Specman E
Interview Questions

The message to be printed is ("%c[TYPE;COLOURm",27);.

TYPE specifies how the message should be?

1 set bold

http://testbench.in/colorfull_messages_from_systemverilog.html[9/26/2012 2:53:32 PM]


WWW.TESTBENCH.IN

2 set half-bright (simulated with color on a color display)


4 set underscore (simulated with color on a color display)
5 set blink
7 set reverse video

COLOR specifies the message color.

30 set black foreground


31 set red foreground
32 set green foreground
33 set brown foreground
34 set blue foreground
35 set magenta foreground
36 set cyan foreground
37 set white foreground

With an above example you can have a display messages with colors. So this way you
can have nicely and colored messages on your terminal.

Enjoy...!
-ASIC with Ankit

copyright © 2007 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/colorfull_messages_from_systemverilog.html[9/26/2012 2:53:32 PM]


WWW.TESTBENCH.IN

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | SITEMAP | LINKS | BLOG | JOBS Search ✔

TUTORIALS
About the author:
SystemVerilog Whats new in Systemverilog 2009 ?
Verification Ankit Shah
is working at Sibridge
Constructs In 2005 there were separate standards for Verilog and SystemVerilog which are Technologies Pvt. Ltd,
Interface merged here with SystemVerilog 2009. There are 30+ noticeable new constructs and Ahmedabad,India.
25+ system task are introduced in SystemVerilog 2009.
OOPS Your feedback / input /
Randomization I listed out following new constructs which are added in SV-2009. thought on this article,
send to Ankit @
Functional Coverage mail2ajshah@gmail.com
Assertion
DPI timeunit and timeprecision
UVM Tutorial You can specify timeunit and timeprecision inside the module with single keyword. Report a Bug or Comment
on This section - Your
VMM Tutorial
input is what keeps
OVM Tutorial module E (...); Testbench.in improving
  timeunit 100ps / 10fs; // timeunit with optional second argument with time!
Easy Labs : SV
  ...
Easy Labs : UVM endmodule
Easy Labs : OVM
(Ch. 3.14.2.2 of LRM)
Easy Labs : VMM
AVM Switch TB
checker - endchecker
VMM Ethernet sample
The checker is specifically created to encapsulate assertions. It can be added with the
modeling code and can be instantiationed. Formal arguments of checker are inputs.
Verilog
Verification (Ch. 17)
Verilog Switch TB checker my_check1 (logic test_sig);
Basic Constructs   a1: assert property (p (test_sig));
  c1: cover property (!test_sig ##1 test_sig);
endchecker : my_check1
OpenVera global clocking
Constructs
Switch TB Global clocking block is declared as the global clocking block for an entire elaborated
SystemVerilog model.
RVM Switch TB
RVM Ethernet sample global clocking @(clk1 or clk2); 
endclocking

(Ch. 14.14)
Specman E
Interview Questions Printing format

%p - displays as an assignment format.

(Ch 21.2.1.2)

%x - displays in hexadecimal format.

(Ch 21.2.1.2)

http://testbench.in/SystemVerilog_2009_enhancements.html[9/26/2012 2:53:42 PM]


WWW.TESTBENCH.IN

edge

It is equivalent to posedge+negedge

(Ch. 31.5)

let

This local score compiler directive replaces the other test macro like `define. A let
construct may be instantiated in other expressions.
let declarations can be used for customization and can replace the text macros in
many cases.

let check_grant(a, b) = assert( a ##2 b) );


check_grant(req, gnt);
(Ch. 11.13)

localparam in ANSI style header


module driver #(parameter AWIDTH = 8,
                parameter DWIDTH = 8,
                localparam PORT=1 >> data
               );
(Ch. 22.2.3)

unique0

Keyword unique will issue a violation report if no condition matches. while keyword
unique0 will not issue a violation report if no condition matches.

(Ch. 12.4.2)

Associative array size()

size() method is introduced to return number of entries in associative array like num()
method.

(Ch. 7.9.1)

Queue delete()

Now you can pass specific index number inside the delete function to delete that
particular index. If index is not specified then it will delete entire Q.

(Ch. 7.10.2)

Bit select and part select of an expression


Instead of...
assign t = (a & b) | (c & d);
assign val = t[7:4];

you can do...

assign val = {(a & b) | (c & d)}[7:4];


(Ch. 7.2.1)

Import package into design


package bit_pkg;
  bit clk;
  bit reset;
endpackage

module dut(
  input bit_pkg::reset rst;
  input bit_pkg::clk clock;
  ...
endmodule

Packet chaining, automatic package and multiple package export is also introduced in

http://testbench.in/SystemVerilog_2009_enhancements.html[9/26/2012 2:53:42 PM]


WWW.TESTBENCH.IN

SV-2009.

(Ch. 23)

pure virtual methods

SV-2009 allows to declare pure virtual methods as well as class. It must be written in
abstract class & it must be only a prototype, It must not contain any statement and
must with without endtask/endfunction.

virtual class BasePacket;
   pure virtual function integer send(bit[31:0] data); // No implementation
endclass
(Ch. 8.20)

pure constraint

It is allowd to declare pure constraint in abstract class. This must be implemented in


extended class with the same constraint name.

virtual class C;
  pure constraint test;
endclass
(Ch. 18.5.2)

Time consuming functions

Using fork/join_none, now time consuming constructs can be used inside function.

function void disp;
fork
  #0 $display("%t: This is #0", $time);
  #1 $display("%t: This is #1", $time);
  #3 $display("%t: This is #3 and A = %x", $time, a);
  a <= 8'hbb; // It allows non-blocking assignment
  #2 $display("%t: This is #2", $time);
join_none
endfunction
(Ch. 9.3.2)

covergroup with sample arguments


covergroup  with function sample(bit a, int x);
  coverpoint x;
  cross x, a;
endgroup : 

cg cg1 = new;

function void F(int j);
bit d;
  ...
  cg1.sample( d, j );
endfunction
(Ch. 19.8.1)

weak - strong

These sequence operators are introduced to simulate assertion efficiently. Assert may
produce wrong message if there is a glitch in the signal. strong require that some
terminating condition happen in the future, and this includes the requirement that
the property clock ticks enough time to enable the condition to happen. weak do not
impose any requirement on the terminating condition, and do not require the clock to
tick. If the strong or weak operator is omitted, then the evaluation of the
sequence_expr depends on the assertion statement in which it is used. If the assertion
statement is assert property or assume property, then the sequence_expr is evaluated
as weak(sequence_expr). Otherwise, the sequence_expr is evaluated as
strong(sequence_expr).

The default in SV-2005 was strong while in SV-2009 is weak unless you. specified
strong.

(Ch. 16.13)

http://testbench.in/SystemVerilog_2009_enhancements.html[9/26/2012 2:53:42 PM]


WWW.TESTBENCH.IN

Implies and iff properties

A property is an implies if it has the following form:

property_expr1 implies property_expr2

Above form evaluates to true if property_expr1 evaluates to true, if not then

property_expr2 evaluates to true.

A property is an iff if it has the following form:

property_expr1 iff property_expr2

A property of this form evaluates to true if, and only if, either both

property_expr1 evaluates to false and property_expr2 evaluates to false or both

property_expr1 evaluates to true and property_expr2 evaluates to true.

(Ch. 16.13)

followed-by (#-#, #=#)


property s1;
  ##[0:5] done #-# always !rst;
endproperty
property s2;
  ##[0:5] done #=# always !rst;
endproperty

Property s1 says that done shall be asserted at some clock tick during the first 6 clock
ticks, and starting from one of the clock ticks when done is asserted, rst shall always
be low. Property s2 says that done shall be asserted at some clock tick during the first
6 clock ticks, and starting the clock tick after one of the clock ticks when done is
asserted, rst shall always be low.

(Ch. 16.13)

The property operators

s_nexttime, s_always, s_eventually, s_until, s_until_with, and sequence operator


strong are strong.
The property operators nexttime, always, until, eventually, until_with, and sequence
operator
weak are weak.

nexttime and s_nexttime


// if the clock ticks once more, then a shall be true at the next clock tick
property s1;
  nexttime a;
endproperty
// the clock shall tick once more and a shall be true at the next clock tick.
property s2;
  s_nexttime a;
endproperty
(Ch. 16.13)

always - s_always

property s1;
  a ##1 b |=> always c;
endproperty

property s1 evaluates to true provided that if a is true at the first clock tick and b is
true at the second clock tick, then c shall be true at every clock tick that follows the
second.

(Ch. 16.13)

until - until_with - s_until - s_until_with

property s1;

http://testbench.in/SystemVerilog_2009_enhancements.html[9/26/2012 2:53:42 PM]


WWW.TESTBENCH.IN

 a until b;
endproperty

property p3;
 a until_with b;
endproperty

Property s1 evaluates to true if, and only if, a is true at every clock tick beginning
with the starting clock tick of the evaluation attempt and continuing
until, but not necessarily including, a clock tick at which b is true.

(Ch. 16.13)

The property p3 evaluates to true provided that a is true at every clock tick beginning
with the starting clock tick of the evaluation attempt and continuing
until and including a clock tick at which b is true.

(Ch. 16.13)

eventually - s_eventually
property s1;
  s_eventually a;
endproperty

The property s1 evaluates to true if, and only if, there exists a current or future clock
tick at which a is true.

(Ch. 16.13.13)

not - accept_on - reject_on - sync_accept_on - sync_reject_on


property p; (accept_on(a) s1); endproperty

If a becomes true during the evaluation of s1, then p evaluates to true.

property p; (reject_on(b) s2); endproperty

If b becomes true during the evaluation of s2 then p evaluates to false.

property p; not (reject_on(b) s2); endproperty

not inverts the effect of operator, so if b becomes true during the evaluation of s2
then p evaluates to true.

(Ch. 16.13.14)

case

case can be used inside the property.

(Ch. 16.13.16)

restrict

It is constraint to the formal verification tool to do not check the property.

untyped

It is allowed to use untyped datatype inside properties.

(Deferred assertion) assert #0 - assume #0 - cover #0

Deferred immediate assertion evaluates after signal have stabilized in a time step.

Shortcut operators
##[+] is equivalent to ##[1:$]
##[*] is equivalent to ##[0:$]
<signal>[+] is equivalent to <signal>[*1:$]
<signal>[*] is equivalent to <signal>[*0:$]

http://testbench.in/SystemVerilog_2009_enhancements.html[9/26/2012 2:53:42 PM]


WWW.TESTBENCH.IN

(Ch. 16.7)

`define

you can pass default value in define macro.

`define MACRO1(a=5) $display(a);
(Ch. 22.5)

`undefineall

It undefines all the defined test macro which is previously declared.

`define FPGASIM
`define GATESIM
module...
....
....
endmodule
`undefineall
(Ch. 22.5)

`begin_keywords and `end_keywords

It is used to specify reserved keywords, it will give an error if implementain does not
matched with version_specifier. e.g if you have specified "1800-2009" then all the
previous versions of Verilog/SystemVerilog keywords can be used but if you have
specified "1800-2005" then those keywords which are introduced specifically in SV-
2009 those can not be used.

(Ch. 22.14)

FILE name and LINE numbers

It keeps track of the filenames of SystemVerilog source files and line nunbers in the
files. which can be helpfull to source error messages and the file name. `__FILE__
expands to the name of the current input file, in the form of a string literal constant.
This is the path by which the compiler opened the file, not  the short name specified
in `include or as the command line argument. `__LINE__ expands to the current input
line number, in the form of a decimal

integer constant.

$display("Internal error: null handle at %s, line %d.",`__FILE__, `__LINE__);

file path and line number will be return which contain above message.

(Ch. 22.12, 22.13)

SYSTEM TASK

$syatem - allows operation system commands.

(Ch 20.18.1)

$global_clock returns the event statement which is written global clocking block
declaration. Here it will return "clk1 or clk2".

(Ch. 14.14)

$sformatf - this system function returns the message into string. Thus string can be
passed into valid function.
$fatel - $error - $warning - $info can be used outside assertion.
$assertpasson - enable execution of pass statement.
$assertpassoff - stop execution of pass statement.  
$assertfailon - enable execution of pass statement.
$assertfailoff - stop execution of fail statement.
$assertnonvacuouson - enable execution of pass statement when assertion is vacuous.
$assertvacuousoff - stop execution of pass statement when assertion is non vacuous.

(Ch 20.14, 16.15.8)

http://testbench.in/SystemVerilog_2009_enhancements.html[9/26/2012 2:53:42 PM]


WWW.TESTBENCH.IN

$changed

It detect changes in values between two adjscent clock tics.

(Ch 20.13)

$past_gclk - $rose_gclk - $fell_gclk - $stable_gclk - $changed_gclk

It will give past sampled value of the signal with respect to global clock.

(Ch 20.13)

$future_gclk - $rosing_gclk - $falling_gclk - $steady_gclk - $changing_gclk

It will give future sampled value of the signal with respect to global clock.

(Ch 20.13, 16.15.8)

$inferred_clock - $inferred_disable - $inferred_enable

These system function are available to query assertion

(Ch. 16.15.7)

Protected envelopes

It specify a region of text that shall be transformed prior to analysis by the source
language processor.

(Ch. 34)

Still there could be many enhancement behind the curtain. It always GOOD to KNOW
more. Your feedback/input/thought are welcomed which can help me to update
contain. Reach me at mail2ajshah@gmail.com

copyright © 2007 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SystemVerilog_2009_enhancements.html[9/26/2012 2:53:42 PM]


WWW.TESTBENCH.IN

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS
About the authors:
SystemVerilog Introduction to Ethernet Frames : Part - 1
Verification Bhavani shankar is VLSI
engineer at Kacper
Constructs This tutorial is divided into two parts. Part-1 will be on Ethernet Frames and Part-2 Technologies Pvt. Ltd.
Interface will be on Simple Ethernet Testplan. Bhavani shankar is an
For Part-2 , Click master in VLSI-CAD from
OOPS Manipal Centre for
Randomization Information Science,
1.Ethernet Protocol Layer Manipal.
Functional Coverage
Assertion The Ethernet protocol basically implements the bottom two layers of the Open Gopi Krishna He is the
DPI Systems Interconnection (OSI) 7-layer model, i.e., the data link and physical sub Author of testbench.in.
layers. Following Figure depicts the typical Ethernet protocol stack and the
UVM Tutorial relationship to the OSI model.
VMM Tutorial
Report a Bug or Comment
OVM Tutorial on This section - Your
input is what keeps
Easy Labs : SV
Testbench.in improving
Easy Labs : UVM with time!
Easy Labs : OVM
Easy Labs : VMM
AVM Switch TB
VMM Ethernet sample

Verilog
Verification
Verilog Switch TB
Basic Constructs

OpenVera
Constructs
Switch TB 2.Ethernet Frame Structure
RVM Switch TB The following illustrates the format of an Ethernet frame as defined in the original
RVM Ethernet sample IEEE 802.3 standard

Specman E
Interview Questions

Preamble

A sequence of 56 bits having alternating 1 and 0 values that are used for
synchronization. They serve to give components in the network time to detect the
presence of a signal, and read it before the frame data arrives.

http://testbench.in/introduction_to_ethernet.html[9/26/2012 2:53:52 PM]


WWW.TESTBENCH.IN

Destination MAC Address

The Destination MAC Address field addresses destination stations. This may addresses
single or multiple stations.

Destination Address (6bytes) of all 1 bits refers to all stations on the LAN and is called
a "Broadcast address".

Start Frame Delimiter

Sequence of 8 bits having the bit configuration 10101011 indicates the start of the
frame.

Source MAC Address

The Source MAC Address addresses the station at which it originated. The 802.3
standard permits these address fields to be either 2-bytes or 6-bytes in length.

Length/Type (2bytes)

If the value of this field is less than or equal to 1500, then the Length/Type field
indicates the number of bytes in the subsequent MAC Client Data field. If the value of
this field is greater than or equal to 1536, then the Length/Type field indicates the
nature of the MAC client protocol (protocol type)

MAC Client Data

This field contains the actual data transferred from the source station to the
destination station or stations. The maximum size of this field is 1500 bytes. If the
size of this field is less than 46 bytes, then use of the subsequent "Pad" field is
necessary to bring the frame size up to the minimum length.

Pad

If necessary, extra data bytes are appended in this field to bring the frame length up
to its minimum size. A minimum Ethernet frame size is 64 bytes from Destination MAC
Address(DA) field through the Frame Check Sequence(FCS).

Frame Check Sequence (FCS)

This field contains a 4-byte Cyclic Redundancy Check (CRC) value used for error
checking.

When a source station assembles a MAC frame, it calculates a CRC checksum on all
the bits in the frame from Destination MAC Address (DA) to the Pad fields (that is, all
fields except the preamble, start frame delimiter, and frame check sequence).

http://testbench.in/introduction_to_ethernet.html[9/26/2012 2:53:52 PM]


WWW.TESTBENCH.IN

The source station stores this CRC value in this field and transmits it as part of the
frame. When the frame is received at destination station, it calculates CRC of
received data and compares it with FCS. If it does not match then destination station
assumes an error occurred during transmission and discards the frame.

The original Ethernet standards defined the minimum frame size as 64-bytes and the
maximum as 1518-bytes. These numbers include all bytes from the Destination MAC
Address field through the Frame Check Sequence field. The Preamble and Start Frame
Delimiter fields are not included when quoting the size of a frame. The IEEE 802.3ac
standard released in 1998 extended the maximum allowable frame size to 1522-bytes
to allow a "VLAN tag" to be inserted into the Ethernet frame format.

Interframe Gap
Ethernet devices must allow a minimum idle period between transmission of frames
known as the interframe gap (IFG) or interpacket gap (IPG). It provides the time for
devices to recover and prepare to receive next frame. The minimum interframe gap is
96 bit times.

3.Frame Format Extensions


VLAN Tagging
The VLAN protocol permits insertion of an identifier, or "tag", into the Ethernet frame
format to identify the VLAN to which the frame belongs. It allows frames from
stations to be assigned to logical groups. This provides various benefits such as easing
network administration, allowing formation of work groups, enhancing network
security, and providing a means of limiting broadcast domains, The 802.3ac standard
defines only the implementation details of the VLAN protocol those are specific to
Ethernet. The 4-byte VLAN tag is inserted into the Ethernet frame between the Source
MAC Address field and the Length/Type field. The first 2-bytes of the VLAN tag consist
of the "802.1Q Tag Type" and are always set to a value of 0x8100. The 0x8100 value is
actually a reserved Length/Type field assignment that indicates the presence of the
VLAN tag, and signals that the traditional Length/Type field can be found at an offset
of 4-bytes further into the frame.

The last 2-bytes of the VLAN tag contain the following information

The first 3-bits are a User Priority Field that may be used to
Assign a priority level to the Ethernet frame.
The next 1-bit is a Canonical Format Indicator (CFI) used in Ethernet frames to
indicate the presence of a Routing Information Field (RIF).

The last 12-bits are the VLAN Identifier (VID) which uniquely identifies the VLAN to
which the Ethernet frame belongs.

JUMBO Frames
JUMBO frames are introduced in order to Increase the maximum size of the MAC Client
Data field, larger frames would provide more efficient use of the network Bandwidth
while reducing the number of frames that have to be processed.

JUMBO frames has the capacity to carry bytes from 64bytes (min size) to 9000bytes
(max size)
The 8870 value is actually a reserved Length/Type field assignment that indicates
frame as JUMBO.

PAUSE Frames
Flow control operation known as "PAUSE" frames are included in 10GBE as it supports
the full duplex mode.

The 8808 value is actually a reserved Length/Type field assignment that indicates
frame as PAUSE. Length/Type field is followed by 2 bytes of MAC control Opcode (00-
01) and 2bytes of MAC control Parameter (timer=00-00toFF-FF) with a unique DA (01-
80-c2-00-00-01) in MAC DA field
PAUSE frame considers 64bytes as Minimum size and 1518bytes as Maximum size for
Normal frame and 1522bytes when tagged.

http://testbench.in/introduction_to_ethernet.html[9/26/2012 2:53:52 PM]


WWW.TESTBENCH.IN

Transmitter Mac should not transmit the frames once it receives Pause frames from
receiver until the time duration specified in the Pause timer
Transmitter Mac should reset/replace the current pause timer with newly arrived
pause time when a Pause frame arrives from receiver before the current Pause time
expires.

copyright © 2007 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/introduction_to_ethernet.html[9/26/2012 2:53:52 PM]


WWW.TESTBENCH.IN

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS
About the authors:
SystemVerilog Introduction to Ethernet Frames : Part - 2
Verification Bhavani shankar is VLSI
engineer at Kacper
Constructs In part-2 , we will see a simple testplan for 10G Ethernet Frames. Technologies Pvt. Ltd.
Interface For Part-1 , Click Bhavani shankar is an
master in VLSI-CAD from
OOPS Manipal Centre for
TEST PLAN FOR MAC FRAME
Randomization Information Science,
Manipal.
Functional Coverage
MAC FRAME FORMAT
Assertion Gopi Krishna He is the
Author of testbench.in.
DPI
UVM Tutorial
VMM Tutorial
Report a Bug or Comment
OVM Tutorial on This section - Your
input is what keeps
Easy Labs : SV PREAMBLE Testbench.in improving
Easy Labs : UVM with time!
Discussion:
Easy Labs : OVM
Easy Labs : VMM The frame begins with the 64-bit preamble field which allows 10G Ethernet
interfaces on the network to synchronize themselves with the incoming data stream
AVM Switch TB before the arrival of important data fields.
VMM Ethernet sample
[Need for Synchronization: In LAN implementation, most of the physical layer
components are allowed to provide valid output only after some number of bit times
Verilog prior to the valid input signals. So this condition necessities a Preamble which is to be
sent before the start of the data .This allows the PLS circuitry to reach its steady
Verification state with the received frame’s timing. So Preamble is used for physical medium
Verilog Switch TB stabilization and synchronization followed by SFD.]
Basic Constructs
Preamble is not used by the MAC layer, so the minimum amount of preamble
required for a device to function properly depends up on which physical layer is
implemented and not up on the MAC layer.
OpenVera
Constructs The preamble bits are transmitted in order from left to right and it should be noted
Switch TB that PRE ends with a ‘0’.
RVM Switch TB Up on the reception of a Frame Physical signal Decapsulation procedure discards
RVM Ethernet sample every bit of preamble until a valid SFD.

IEEE Standard does not define the minimum PRE size, PRE size is handled depending
up on the PHY as it is the function of physical medium. So min PRE size is considered
Specman E as 1byte .Even though Standard defines as PRE as 7bytes,Mac should tolerate large
Interview Questions amounts of Preamble

[The PRE is maintained in the fast Ethernet and gigabit systems to provide
compatibility with the original Ethernet frame. However, both systems use more
complex mechanisms for encoding the signals that avoid any signal startup losses, so
they don’t need preamble to protect the frame signals]

Valid PRE

1) A frame with PRE of 7octets in PRE field with the bit pattern shown below and
should always end with a ‘0’.

http://testbench.in/introduction_to_ethernet_2.html[9/26/2012 2:54:01 PM]


WWW.TESTBENCH.IN

10101010 xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx10101010

2) A frame with variable PRE octets like 1, 2, 3,4,5,6 by using pattern shown in 1st
case

Invalid PRE

1) A frame with variable PRE octets


Generate a frame with PRE octets greater than required i.e. 8, 9,10,12

2) A frame with variable PRE pattern

3) Generate a frame with varying bit pattern’s using following cases and observe the
results.

(1st byte)...(7th byte)


00000000.....00000000
11111111.....11111111
10101111.....10101111
01010101.....11000011
10101011.....10101011

4) A frame consisting only PRE [i.e. Sop PRE Eop]

5) Repeat bad frames mentioned above with each frame followed and preceded by a
Good Frame separated by required minimum Inter Frame Gap (96 bits).

References:

IEEE STD 802.3,2005 Edition, subclasses 3.2.1, 4.2.5, 4.2.9


O’REILY-Ethernet Definitive Guide. PDF

START FRAME DELIMITER [SFD]

Discussion:

SFD field is the sequence 10101011 which immediately follows the PRE pattern and
indicates the start of the frame.

The last two bits indicates the receiving interface that the end of the preamble
and SFD has been reached and that the bits that follow are actual fields of the frame

Any successive bits following the transmission of SFD are recognized as data bits
and are passed on to the LLC sub layer

Valid SFD

1) A frame of one octet size SFD with bit pattern 10101011 and placed after PRE.

2) Any frame with invalid SFD pattern is considered as Bad frame and discarded

Invalid SFD

1) A Frame with variable SFD bit pattern


Generate a frame with variable bit pattern’s using following cases
10101010
10101111
11111111
00000000
01010111
11000011

http://testbench.in/introduction_to_ethernet_2.html[9/26/2012 2:54:01 PM]


WWW.TESTBENCH.IN

2) A Frame consisting only PRE and Good SFD [i.e. Sop PRE SFD Eop]

3) Repeat bad frames mentioned above with each frame followed and preceded by a
Good Frame separated by required minimum Inter Frame Gap (96 bits).

References:

IEEE STD 802.3,2005 Edition, subclasses 3.2.2, 4.2.6.


O’REILY-Ethernet Definitive Guide. PDF

FRAME CHECK SEQUENCE (FCS)


Discussion:

FCS field contains a 4-byte cyclical redundancy check (CRC) value used for error
checking. CRC is a polynomial that is calculated using the contents of the destination,
source, type (or length), and data fields except PRE, SFD and FCS. As the frame is
generated by the transmitting station, the CRC value is simultaneously being
calculated.

The source station stores 32 bits of the CRC value (x31 term is the most bit of the
first octet and the x0term is the right most of the last octet) that are the result of
this calculation in the FCS field and transmits it as a part of the frame. The x31
coefficient of the CRC polynomial is sent as the first bit of the field and the x0
coefficient as the last bit.

When the frame is received by the destination station, it performs an identical


check. If the calculated value does not match the value in this field, the destination
station assumes an error has occurred during transmission and discards the frame.

Valid CRC

1) The 32bit CRC value in FCS field of received frame should match the 32bit CRC
value computed on received frame.

2) Frames with incorrect CRC(mismatch) values should be discarded

Invalid CRC

1) A frame with incorrect CRC value


a) Generate a frame by keeping incorrect CRC values in FCS field and observe the
results
b) Repeat (a) for JUMBO,PAUSE and VLAN frames and observe the results Mac
should discard the frames in both the cases as CRC error

2) Repeat bad frames mentioned above with each frame followed and preceded by a
Good Frame separated by required minimum Inter Frame Gap (96 bits).

References:
IEEE STD 802.3,2005 Edition, subclasses 3.2.8, 4.2.4.1.2.
O’REILY-Ethernet Definitive Guide. PDF

LENGTH/TYPE FIELD
Discussion:

10GB Ethernet supports the following frame sizes

a) In case of untagged
Maximum untagged frame size is 1518 bytes(from DA to FCS)

http://testbench.in/introduction_to_ethernet_2.html[9/26/2012 2:54:01 PM]


WWW.TESTBENCH.IN

Minimum frame size is 64bytes(from DA to FCS)

b) In case of tag
Maximum tagged frame size is 1522bytes (Untagged size + tag prefix size)

If the value in the Length/type field is less than or equal to 1500 then the Value
indicates the number of bytes in the subsequent MAC Client Data field. (Length
Interpretation)

If the value in the length/type field is greater than or equal to 1536 then the value
Indicates the nature of the MAC client protocol (protocol type like jumbo, pause etc)
All other values are undefined. (Type Interpretation)

The minimum length of the Data/Pad field is 46 bytes, if the length of the frame in
the length/type field is less than 46 then all extra bytes are considered as
padded/appended in this field to bring the frame length up to its minimum size

The maximum length of the Data/pad field is 1500bytes, if the length of the frame
in the length /type field is greater than 1500 and less than 1536, frame is discarded.

10GE supports the VLAN Tagging which is inserted in to the Ethernet frame
between the source MAC address and Length/Type field. The first 2-bytes of the VLAN
tag consist of the "802.1Q Tag Type" and are always set to the value of 0x8100.

a) VLAN tagged frames takes 64bytes as minimum size and 1522 bytes as maximum
size (max size may vary depending up on VLAN count).
b) The 0x8100 value is actually a reserved Length/Type field assignment that
indicates the presence of the VLAN tag.

Note: As the Standard does not define the min tagged frame size, it is considered as
64bytes which is common to all types of frames. This min size constraint may vary
depending up on the Company, (CISCO defined the minimum size of the Ethernet
frame with 802.1Q tagging is 68 bytes)

JUMBO frames are introduced in order to Increase the maximum size of the MAC
Client Data field, larger frames would provide more efficient use of the network
Bandwidth while reducing the number of frames that have to be processed.

a) JUMBO frames has the capacity to carry bytes from 64bytes (min size) to
9000bytes (max size)
b) The 8870 value is actually a reserved Length/Type field assignment that
indicates frame as JUMBO.

Flow control operation known as "PAUSE" frames are included in 10GBE as it


supports the full duplex mode.

a) The 8808 value is actually a reserved Length/Type field assignment that


indicates frame as PAUSE. Length/Type field is followed by 2 bytes of MAC control
Opcode (00-01) and 2bytes of MAC control Parameter (timer=00-00toFF-FF) with a
unique DA (01-80-c2-00-00-01) in MAC DA field
b) PAUSE frame considers 64bytes as Minimum size and 1518bytes as Maximum size
for Normal frame and 1522bytes when tagged.
c) Transmitter Mac should not transmit the frames once it receives Pause frames
from receiver until the time duration specified in the Pause timer
d) Transmitter Mac should reset/replace the current pause timer with newly
arrived pause time when a Pause frame arrives from receiver before the current
Pause time expires.

Valid Frames

1) A frame(untagged) size between 64 and 1518 bytes [Valid size Normal untagged
frame]
Generate a frame with the following acceptable sizes and observe the results. Mac
should accept these frames
64,65,67,100,512,1500,1516,1517,1518

2) A tagged frame size between 64 and 1522 bytes [Valid size Normal tagged frame]
Generate a frame with the following acceptable sizes and observe the results, Mac
should accept these frames
64,65,67,100,512,1500,1516,1517,1518, 1520,1522

3) A frame less than min length (<46) with padded values [Length (<46) untagged
padded Normal frame]

http://testbench.in/introduction_to_ethernet_2.html[9/26/2012 2:54:01 PM]


WWW.TESTBENCH.IN

Generate a frame with the following lengths in length field along with proper
Padding and observe the results, Mac should accept the frames
1,2,3,4,5,6,7,40,42,44,45

4) A frame greater than min length (with out padding) but less than max
length(1500bytes) [Length (>46) untagged Normal frame]
Generate a frame with the following lengths in length field and observe the
results, Mac should accept the frames
47,50,100,512,1497,1498,1499,1500

5) A frame greater than or equal to1536 bytes i.e. Type interpretation Generate a
frame with the following values in length/Type field and observe the results, Mac
should interpret the frame as one of the following types

5.1) A frame with VLAN tag ( 8100/9100--VLAN tagged )


Generate a tagged frame by placing 8100/9100 in the first two bytes of tagged
length/type field that indicates the presence of VLAN tag and replaces the normal
"Length/Type" field repeat with 3. (a) & 4. (a) Valid frame cases. Mac should accept
the frame as normal VLAN tagged frame [Length (<46) tagged padded Normal frame,
Length (>46) tagged Normal frame]

5.2) JUMBO frame Type ( 8870 - JUMBO Type)

5.2.1 ) JUMBO frame of size >64 bytes with VLAN tag

Generate a Jumbo Tagged frame of size (>64) by placing8870 in regular


Length/Type field and repeat with 2nd valid frame cases; Mac should accept the
frame as JUMBO frame with VLAN tag. [JUMBO (size>64) tagged frame]

5.2.2) JUMBO frame of size (<=9k+22) with VLAN tag

Generate a Jumbo frame of size (< =9k+22); Mac should accept the frame as JUMBO
frame with VLAN tag. [JUMBO (size<=9k+22) tagged frame]

5.2.3) JUMBO frame with out VLAN tag

a) Generate a frame of size (>64) by placing 8870 in the regular Length/type field
and repeat with 1st valid frame case including 1519, 1520, 1522. Mac should accept
the frame as JUMBO untagged frame. [JUMBO (size>64) untagged frame]

b) Generate a frame of size (<=9k+18) by placing 8870 in the regular Length/type


field and repeat with 1st valid frame case; Mac should accept the frame as JUMBO
untagged frame. [JUMBO (size<=9k+18) untagged frame]

5.3) PAUSE Frame Type (8808 - PAUSE Type)

5.3.1) PAUSE frame of size (>64) and (<1522) with VLAN tag

Generate a Tagged Pause frame by placing 8808 in the regular Length/type field
and next 2bytes of opcode field with (00-01) and repeat with 2nd valid frame cases
(64,65,67,100,512,1500,1516,1517,1518, 1520,1522) ; Mac should accept the frame as
Pause frame with VLAN tag. [PAUSE (size>64) and (<1522) Tagged Frame]

5.3.2) PAUSE frame with out VLAN tag

Generate a untagged pause frame and repeat with 1st valid frame cases
(64,65,67,100,512,1500,1516,1517,1518); Mac should accept the frame as Pause
frame with out VLAN tag. [PAUSE (size>64) and (<1518) untagged Frame]

5.3.3) PAUSE frame with MAC control Parameters (zero & Non-zero Timer)

a) Generate a untagged Pause frame by placing (00-01) in opcode field and vary
timer values from 00-00 to FF-FF(hex) [Untagged PAUSE with Zero & non-zero Timer]
b) Repeat (a) for tagged Pause frame [Tagged PAUSE with Zero & non-zero Timer]
c) Repeat (a),(b) with different pause times before the completion of current
pause_timer [Multiple Pause frames with different timers]

Invalid Frames

1) A Frame which is less than min frame size (<64) with bad CRC(Runt frames) [Runt
size (<64) common to Normal, JUMBO&VLAN tagged/untagged Runt frames]

a) Generate a frame (both tagged and untagged) with the following sizes which are
less than min frame size (<64) and observe the results, MAC should discard these

http://testbench.in/introduction_to_ethernet_2.html[9/26/2012 2:54:01 PM]


WWW.TESTBENCH.IN

frames

(1) 1, 2,3,4,5,6,7,8,45,46,47
(2) 50, 61, 62, 63

b) Repeat (a) for PAUSE frame and observe the results, Mac should not accept the
frame as VALID [PAUSE Runt frame]

2) Repeat (1) for SHORT frames [SHORT Frames]

3) A untagged Frame greater than max frame size (>1518) [Over size (>1518) untagged
Normal frame]

3.1) Generate a frame with the following sizes which are greater than Max frame
size
a) 1519, 1520, 1521, 1522
b) 1526, 1530, 1534,1535,1536,1537

3.2) Repeat (a) for untagged PAUSE frame [Over size (>1518) untagged PAUSE
frame]

4) A tagged (VLAN) Frame greater than max frame size (>1522)

(a) Generate a frame using 3.A (b) Invalid frame cases [Over size (>1522) tagged
Normal frame]
(b) Repeat (a) for tagged PAUSE frame [Over size (>1522) tagged PAUSE frame]

5) A frame less than min length (<46) without padding

a) Generate a frame with the following lengths in length field without padding and
observe the results, Mac should discard the frames as
1,2,3,4,5,6,7,40,42,44,45 [Runt Length (<46) not padded Normal frame]
b) Repeat (a) with tagged frame [Runt Length (<46) not padded tagged Normal
frame]

6) A frame greater than max length (>1500) and( <1536)


a) Generate a frame with the following lengths in length field and observe the
results, Mac should discard the frames [Invalid Length (>1500&<1536) untagged Normal
frame]
1501,1505,1518,1522,1526,1530,1535
b) Repeat (a) with tagged frame [Invalid Length (>1500&<1536) tagged Normal
frame]

7) A frame with invalid value in Length/Type field( i.e. Type interpretation)


a) Generate a frame with the following values in length/Type field and observe the
results, Mac should identify these frame types
1536,1537, 1540, 8000.8101,8110,8807,8809,8880 [Invalid Type (>1536) untagged
Normal/Pause frame]
b) Repeat (a) with Tagged frame [Invalid Type (>1536) tagged Normal/Pause frame]

8) A JUMBO frame of size > (9k+18)


a) Generate a Jumbo frame of size (>9k+18); Mac should discard the frame as
Invalid size JUMBO untagged frame [Over size JUMBO (size>9k+18) untagged frame]
b) Generate a Jumbo frame of size (>9k+22); Mac should discard the frame as
Invalid size JUMBO tagged frame [Over size JUMBO (size>9k+22) tagged frame]

9) PAUSE frame with invalid value in opcode field


a) Generate an untagged Pause frame with invalid opcode (other than 00-01) values
with following opcode values 00-10, 01-00, 00-02 to 00-07, 00-00, 00-FF,01-01 etc.
[Invalid opcode PAUSE untagged frame]
b) Repeat (a) for Tagged PAUSE frame[Invalid opcode PAUSE tagged frame]

10) Multiple PAUSE frames


Generate a pause frame by varying Pause timer values such that Transmit MAC should
not affect the Min IFG gap required between frames after the completion of PAUSE
duration

[Example: suppose current pause timer is set to 8sec and if other frame arrives with
pause time 0sec, then Mac should transmit the frames with out violating the min IFG]
Repeat bad frames mentioned above with each frame followed and preceded by a
Good Frame separated by required minimum Inter Frame Gap (96 bits).

http://testbench.in/introduction_to_ethernet_2.html[9/26/2012 2:54:01 PM]


WWW.TESTBENCH.IN

References:
IEEE Std 802.3, 2002 Edition - subclasses 3.1.1, Figure 3-1 - MAC frame format,3.2.6,
3.5, Figure 3-3 Tagged MAC frame format, 4.4.2-allowable Implementations
IEEE STD 802.3-2005 - Subclasses 31.3 and 31B.3.3, 31B.3.7
IEEE STD 802.3-2005 - Subclasses 3.5, 31.4, 31.5.1, and 31.5.2
IEEE STD 802.3-2005 - Subclasses 4.2.9, and 4.2.4.2.2
O’REILY-Ethernet Definitive Guide. PDF

DESTINATION FIELD (DA)


Discussion:

The Destination MAC Address field identifies the station or stations that are to
receive the frame. DA field follows the preamble and Each Ethernet interface is
assigned a unique 48-bit address, called the interface's physical or hardware address.

The DA field contains the 48-bit Ethernet address that corresponds to the address
of the interface in the station that is the destination of the frame.

The DA field may specify either an "Individual address" destined for a single station
or "Multicast address" destined for a group of stations or the standard broadcast
address

If the LSB(1st bit) is 0---indicates Individual address 1---indicates Multicast address


(including Broadcast)
If the 2nd bit is 0---indicates globally administered 1---indicates locally administered
(including Broadcast)

The IEEE 802.3 version of the frame adds significance to the second bit of the
destination address, which is used to distinguish between locally and globally
administered addresses.

1) A globally administered address is a physical address assigned to the interface by


the manufacturer, which is indicated by setting the second bit to zero.

2) If the address of the Ethernet interface is administered locally for some reason,
then the second bit is supposed to be set to a value of one. In the case of a broadcast
address, the second bit is also a one.

Remaining 46bits are a uniquely assigned value that identifies a single station or
group of stations or all stations on the network

[Locally administered addresses are very rarely used on Ethernet systems, since the
vast majority of Ethernet interfaces are assigned their own unique 48-bit address.
Locally administered addresses, However, have been commonly used on some Token
Ring systems.]

Valid Frame

1) A Frame with 6bytes of DA [valid DA field Normal frame]


a) Generate a frame by placing 6 bytes of following valid address values
Unicast MAC address
Multicasting MAC address
Broadcasting MAC address

b) Repeat (a) for tagged normal frame

2) A Frame with PAUSE Multicast unique DA

a) Repeat 5.3.C (a), (b),(c) Valid paused Type frame cases by placing unique
multicast address reserved for PAUSE transactions (01-80-C2-00-00-01) [Un tagged
Pause with Unique (DA) reserved Multicast Address]

b) Repeat (a) for tagged PAUSE frame [Tagged Pause with Unique (DA) reserved
Multicast Address]

Invalid Frame

http://testbench.in/introduction_to_ethernet_2.html[9/26/2012 2:54:01 PM]


WWW.TESTBENCH.IN

1) A Frame with 6bytes of invalid DA [Invalid DA field Normal frame]


a) Generate a frame by placing following invalid address values(only when they are
not valid MAC address)
All zeros (000000...)
All ones (1111111...)
SFD pattern(10101011)
Random value

b) Repeat (a) for tagged normal frame

2) A Frame with 6bytes of PAUSE Multicast DA [Invalid DA field Normal frame]

a) Generate a frame by placing Pause unique address (01-80-C2-00-00-01);


Mac should discard this frame (should not be a PAUSE frame type)

2) PAUSE frame with invalid DA (only when addresses are not valid )
a) Generate a Pause frame with DA other than pause unique Multicast address (01-
80-C2-00-00-01) by placing following address values in DA field
[Invalid DA PAUSE tagged frame] All zeros(0000000000000)
All ones(11111111111111)
SFD or PRE pattern(10101011)
Random values

b) Repeat (a) for untagged PAUSE frame [Invalid DA PAUSE untagged frame]
Repeat bad frames mentioned above with each frame followed and preceded by a
Good Frame separated by required minimum Inter Frame Gap (96 bits).

References:

IEEE STD 802.3-2005 - Subclasses 3.2.3.1,3.2.4


O-REILY-Ethernet Definitive Guide. PDF

SOURCE ADDRESS (SA)


Discussion:

The Source MAC Address (6 bytes) identifies the station that originated the frame
and it is always an individual address. The 1st bit (LSB) is reserved and always set
to"0".

This is the physical address of the interface that sends the frame. The source
address is not interpreted in any way by the Ethernet MAC protocol. Instead, it is
provided for the use of high-level protocols. An Ethernet station uses its physical
address as the source address in any frame it transmits.

[IEEE standard does not specifically state that an interface may have the ability to
override the 48-bit physical address assigned by the manufacturer. However, all
Ethernet interfaces in use these days appear to allow the physical address to be
changed, which makes it possible for the network administrator or the high level
network software to modify the Ethernet interface address]

Valid Frame

Generate a frame by placing valid 6bytes of source address ensuring first bit with "0"

Invalid Frame

1) A Frame with 6bytes of invalid SA(only when following are invalid addresses)
[Invalid SA field Normal frame]
a) Generate a frame by placing following invalid address values
All zeros (000000...)
All ones (1111111...)
SFD or PRE pattern(10101011)
Random value

b) Repeat (a) for tagged normal frame

2) Repeat bad frames mentioned above with each frame followed and preceded by a
Good Frame separated by required minimum Inter Frame Gap (96 bits).

http://testbench.in/introduction_to_ethernet_2.html[9/26/2012 2:54:01 PM]


WWW.TESTBENCH.IN

3) A frame with invalid SA by making 0th bit as 1 ,Receiving MAC should discard
packet

References:

IEEE STD 802.3-2005 - Subclasses 3.2.3,3.2.5


O-REILY-Ethernet Definitive Guide. PDF

DATA / PAD Field


Discussion:

Data Field contains the data transferred from the source station to the destination
station or stations
The maximum size of this field is 1500 bytes
The minimum size of this field is 46bytes
The maximum size of the data field is determined by the maximum frame size and
address size parameters of the particular implementation

PAD

If the size < 46 bytes, then use of the subsequent "Pad" field is necessary to bring
the frame size up to the minimum length.
If necessary, extra data bytes are appended in this field to bring the frame length up
to its minimum size.
The size of the pad, if any is determined by the size of the data field supplied by the
MAC client and the minimum frame size and address size parameters.

Full data transparency is provided in the sense that any arbitrary sequence of octet
values may appear in the data field up to a maximum number specified by the
implementation of the standard that is used.

Length value indicated in Length/Type field is compared with the Data length in
Data field
Length>Data length - Length error (loss of Data bits)
Length
Length=Data length - no padding required

For a padded Frame of Length (<46) in Length/Type field then data length should
be always greater than the value in length field.

Padding is always performed only using all zero values.

Valid Frame

1) A Frame with data length (>=46) and (<=1500)


Generate a frame with data range between min and max Data lengths by placing
the following data in Data field
All zeros (000000...)
All ones (1111111...)
SFD or PRE pattern(10101011)
Random values

Invalid Frame

1) Generate a Tagged frame of length (<46) in Length/Type field but data field length
shows value (<46) even after padding is performed by transmitter Mac. [Padded
Tagged frame < min size]

2) A Frame with excess Padding [Frame with Excess Padding]


a) Generate a frame of length (<46) in Length/Type field but data field length
shows value (>46-excess) even after padding is performed by transmitter Mac
b) Generate a frame of length (<46) in Length/Type but data field length shows
value(>46-excess) and it has violated the maximam size
(Mac should discard the packet if excess padding violates the maximam size)

http://testbench.in/introduction_to_ethernet_2.html[9/26/2012 2:54:01 PM]


WWW.TESTBENCH.IN

3) A Frame of length (>46) in Length/Type field but data field shows the length less
than the length shown in Length field. [Frame with Length error(loss of Data bits)]
{Suppose length field has 70 but data length is 60bytes then what about remaining
10bytes?}

4) A Frame with invalid padding


Generate a frame of length (<46 bytes) in Length field and pad with the following
values
All ones (1111111...)
SFD or PRE pattern(10101011)
Random values

5) Repeat bad frames mentioned above with each frame followed and preceded by a
Good Frame separated by required minimum Inter Frame Gap (96 bits).

References:

IEEE STD 802.3-2005 - Subclasses 3.1.1,3.2.7 Mac Frame Format


O-REILY-Ethernet Definitive Guide. PDF

copyright © 2007 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/introduction_to_ethernet_2.html[9/26/2012 2:54:01 PM]


WWW.TESTBENCH.IN

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS
About the author:
SystemVerilog Introduction to PCI Express
Verification Arjun Shetty
is perusing Master of
Constructs We will start with a conceptual understanding of PCI Express. This will let us Technology in VLSI &
Interface appreciate the importance of PCI Express. This will be followed by a brief study of the Embedded Systems in
PCI Express protocol. Then we will look at the enhancements and improvements of the International Institute
OOPS Of Information
protocol in the newer 3.0 specs.
Randomization Technology, Hyderabad
Functional Coverage 1 Basic PC system architecture
Arjuns Blog
Assertion We will start by looking at the basic layout of a PC system. Logically, an average PC
DPI system is laid out in something like shown in the figure.
UVM Tutorial The core logic chipset acts as a switch or router, and routes I/O traffic among the Report a Bug or Comment
different devices that make up the system. on This section - Your
VMM Tutorial
input is what keeps
OVM Tutorial In reality, the core logic chipset is split into two parts: the northbridge and the Testbench.in improving
Easy Labs : SV southbridge (or I/O bridge). This split is there for a couple of reasons, the most with time!
important of which is the fact that there are three types of devices that naturally
Easy Labs : UVM work very closely together, and so they need to have faster access to each other: the
Easy Labs : OVM CPU, the main memory, and the video card. In a modern system, the video card's GPU
is functionally a second (or third) CPU, so it needs to share privileged access to main
Easy Labs : VMM
memory with the CPU(s). As a result, these three devices are all clustered together
AVM Switch TB off of the northbridge.
VMM Ethernet sample

Verilog
Verification
Verilog Switch TB
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/introduction_to_pci_express.html[9/26/2012 2:54:12 PM]


WWW.TESTBENCH.IN

The northbridge is tied to a secondary bridge, the southbridge, which routes traffic
from the different I/O devices on the system: the hard drives, USB ports, Ethernet
ports, etc. The traffic from these devices is routed through the southbridge to the
northbridge and then on to the CPU and/or memory.

http://testbench.in/introduction_to_pci_express.html[9/26/2012 2:54:12 PM]


WWW.TESTBENCH.IN

As is evident from the diagram above, the PCI bus is attached to the southbridge. This
bus is usually the oldest, slowest bus in a modern system, and is the one most in need
of an upgrade.

The main thing that we should take away from the previous diagram is that the
modern PC is a motley collection of specialized buses of different protocols and
bandwidth capabilities. This mix of specialized buses designed to attach different
types of hardware directly to the southbridge is something of a continuously evolving
hack that has been gradually and collectively engineered by the PC industry as it tries
to get around the limitations of the aging PCI bus. Because the PCI bus can't really cut
it for things like Serial ATA, Firewire, etc., the trend has been to attach interfaces
for both internal and external I/O directly to the southbridge. So today's southbridge
is sort of the Swiss Army Knife of I/O switches, and thanks to Moore's Curves it has
been able to keep adding functionality in the form of new interfaces that keep
bandwidth-hungry devices from starving on the PCI bus.

In an ideal world, there would be one primary type of bus and one bus protocol that
connects all of these different I/O devices ? including the video card/GPU ? to the
CPU and main memory. Of course, this "one bus to rule them all" ideal is never, ever
going to happen in the real world. It won't happen with PCI Express, and it won't
happen with Infiniband (although it technically could happen with Infiniband if we
threw away all of today's PC hardware and started over from scratch with a round of
natively Infiniband-compliant devices).

Still, even though the utopian ideal of one bus and one bus protocol for every device
will never be achieved, there has to be way bring some order to the chaos. Luckily for
us, that way has finally arrived in the form of PCI Express (a.k.a. PCIe).

2 A primer on PCI
Before we go into detail on PCIe, it helps to understand how PCI works and what its
limitations are.

http://testbench.in/introduction_to_pci_express.html[9/26/2012 2:54:12 PM]


WWW.TESTBENCH.IN

The PCI bus debuted over a decade ago at 33MHz, with a 32-bit bus and a peak
theoretical bandwidth of 132MB/s. This was pretty good for the time, but as the rest
of the system got more bandwidth hungry both the bus speed and bus width were
cranked up in a effort keep pace. Later flavors of PCI included a 64-bit, 33MHz bus
combination with a peak bandwidth of 264MB/s; a more recent 64-bit, 66MHz
combination with a bandwidth of 512MB/s.

PCI uses a shared bus topology to allow for communication among the different
devices on the bus; the different PCI devices (i.e., a network card, a sound card, a
RAID card, etc.) are all attached to the same bus, which they use to communicate
with the CPU. Take a look at the following diagram to get a feel for what a shared
bus looks like.

Because all of the devices attached to the bus must share it among themselves, there
has to be some kind of bus arbitration scheme in place for deciding who gets access
to the bus and when, especially in situations where multiple devices need to use the
bus at the same time. Once a device has control of the bus, it becomes the bus
master, which means that it can use the PCI bus to talk to the CPU or memory via the
chipset's southbridge.

The shared bus topology's main advantages are that it's simple, cheap, and easy to
implement ? or at least, that's the case as long as you're not trying to do anything too
fancy with it. Once you start demanding more performance and functionality from a
shared bus, then you run into its limitations. Let's take a look at some of those
limitations, in order to motivate our discussion of PCI Express's improvements.

This scheme works fine when there are only a few devices attached to the bus,
listening to it for addresses and data. But the nature of a bus is that any device that's
attached to it and is "listening" to it injects a certain amount of noise onto the bus.
Thus the more devices that listen to the bus ? and thereby place an electrical load on
the bus ? the more noise there is on the bus and the harder it becomes to get a clean
signal through.

2.1 Summary of PCI's shortcomings

To summarize, PCI as it exists today has some serious shortcomings that prevent it
from providing the bandwidth and features needed by current and future generations
of I/O and storage devices. Specifically, its highly parallel shared-bus architecture
holds it back by limiting its bus speed and scalability, and its simple, load-store, flat
memory-based communications model is less robust and extensible than a routed,
packet-based model.

3 PCI-X: wider and faster, but still outdated


The PCI-X spec was an attempt to update PCI as painlessly as possible and allow it to
hobble along for a few more years. This being the case, the spec doesn't really fix any
of the inherent problems outlined above. In fact, it actually makes some of the
problems worse.

The PCI-X spec essentially doubled the bus width from 32 bits to 64 bits, thereby
increasing PCI's parallel data transmission abilities and enlarging its address space.

http://testbench.in/introduction_to_pci_express.html[9/26/2012 2:54:12 PM]


WWW.TESTBENCH.IN

The spec also ups PCI's basic clock rate to 66MHz with a 133MHz variety on the high
end, providing yet another boost to PCI's bandwidth and bringing it up to 1GB/s (at
133MHz).

The latest version of the PCI-X spec (PCI-X 266) also double-pumps the bus, so that
data is transmitted on the rising and falling edges of the clock. While this improves
PCI-X's peak theoretical bandwidth, its real-world sustained bandwidth gains are more
modest.

While both of these moves significantly increased PCI's bandwidth and its usefulness,
they also made it more expensive to implement. The faster a bus runs, the sensitive it
becomes to noise; manufacturing standards for high-speed buses are exceptionally
strict for this very reason; shoddy materials and/or wide margins of error translate
directly into noise at higher clock speeds. This means that the higher-speed PCI-X bus
is more expensive to make.

The higher clock speed isn't the only thing that increases PCI-X's noise problems and
manufacturing costs. The other factor is the increased bus width. Because the bus is
wider and consists of more wires, there's more noise in the form of crosstalk.
Furthermore, all of those new wires are connected at their endpoints to multiple PCI
devices, which means an even larger load on the bus and thus more noise injected
into the bus by attached devices. And then there's the fact that the PCI devices
themselves need 32 extra pins, which increases the manufacturing cost of each
individual device and of the connectors on the motherboard.

All of these factors, when taken together with the increased clock rate, combine to
make the PCI-X a more expensive proposition than PCI, which keeps it out of
mainstream PCs. And it should also be noted that most of the problems with
increasing bus parallelism and double-pumping the bus also plague recent forms of
DDR, and especially the DDR-II spec.

And after all of that pain, you still have to deal with PCI's shared-bus topology and all
of its attendant ills. Fortunately, there's a better way.

4 PCI Express: the next generation


PCI Express (PCIe) is the newest name for the technology formerly known as 3GIO.
Though the PCIe specification was finalized in 2002, PCIe-based devices have just now
started to debut on the market.

PCIe's most drastic and obvious improvement over PCI is its point-to-point bus
topology. Take a look at the following diagram, and compare it to the layout of the
PCI bus.

http://testbench.in/introduction_to_pci_express.html[9/26/2012 2:54:12 PM]


WWW.TESTBENCH.IN

In a point-to-point bus topology, a shared switch replaces the shared bus as the
single shared resource by means of which all of the devices communicate. Unlike in a
shared bus topology, where the devices must collectively arbitrate among themselves
for use of the bus, each device in the system has direct and exclusive access to the
switch. In other words, each device sits on its own dedicated bus, which in PCIe lingo
is called a link.

Like a router in a network or a telephone switchbox, the switch routes bus traffic and
establishes point-to-point connections between any two communicating devices on a
system.

4.1 Enabling Quality of Service

The overall effect of the switched fabric topology is that it allows the "smarts" needed
to manage and route traffic to be centralized in one single chip ? the switch. With a
shared bus, the devices on the bus must use an arbitration scheme to decide among
themselves how to distribute a shared resource (i.e., the bus). With a switched
fabric, the switch makes all the resource-sharing decisions.

By centralizing the traffic-routing and resource-management functions in a single


unit, PCIe also enables another important and long overdue next-generation function:
quality of service (QoS). PCIe's switch can prioritize packets, so that real-time
streaming packets (i.e., a video stream or an audio stream) can take priority over
packets that aren't as time critical. This should mean fewer dropped frames in your
first-person shooter and lower audio latency in your digital recording software.

4.2 Traffic runs in lanes

When PCIe's designers started thinking about a true next-generation upgrade for PCI,
one of the issues that they needed to tackle was pin count. In the section on PCI
above, I covered some of the problems with the kind of large-scale data parallelism
that PCI exhibits (i.e. noise, cost, poor frequency scaling, etc.). PCIe solves this
problem by taking a serial approach.

As I noted previously, a connection between two a PCIe device and a PCIe switch is

http://testbench.in/introduction_to_pci_express.html[9/26/2012 2:54:12 PM]


WWW.TESTBENCH.IN

called a link. Each link is composed of one or more lanes, and each lane is capable of
transmitting one byte at a time in both directions at once. This full-duplex
communication is possible because each lane is itself composed of one pair of signals:
send and receive.

In order to transmit PCIe packets, which are composed of multiple bytes, a one-lane
link must break down each packet into a series of bytes, and then transmit the bytes
in rapid succession. The device on the receiving end must collect all of the bytes and
then reassemble them into a complete packet. This disassembly and reassembly
happens must happen rapidly enough to where it's transparent to the next layer up in
the stack. This means that it requires some processing power on each end of the link.
The upside, though, is that because each lane is only one byte wide, very few pins are
needed to transmit the data. You might say that this serial transmission scheme is a
way of turning processing power into bandwidth; this is in contrast to the old PCI
parallel approach, which turns bus width (and hence pin counts) into bandwidth. It so
happens that thanks to Moore's Curves, processing power is cheaper than bus width,
hence PCIe's tradeoff makes a lot of sense.

We saw earlier that a link can be composed of "one or more lanes", so us clarify that
now. One of PCIe's nicest features is the ability to aggregate multiple individual lanes
together to form a single link. In other words, two lanes could be coupled together to
form a single link capable of transmitting two bytes at a time, thus doubling the link
bandwidth. Likewise, you could combine four lanes, or eight lanes, and so on.

A link that's composed of a single lane is called an x1 link; a link composed of two
lanes is called an x2 link; a link composed of four lanes is called an x4 link, etc. PCIe
supports x1, x2, x4, x8, x12, x16, and x32 link widths.

PCIe's bandwidth gains over PCI are considerable. A single lane is capable of
transmitting 2.5Gbps in each direction, simultaneously. Add two lanes together to
form an x2 link and you've got 5 Gbps, and so on with each link width. These high
transfer speeds are good, good news, and will enable a new class of applications, like
SLI video card rendering.

5 PCIe Protocol Details


Till now we were concerned with the system level impact of PCIe. We did not look at

http://testbench.in/introduction_to_pci_express.html[9/26/2012 2:54:12 PM]


WWW.TESTBENCH.IN

the protocol itself. The following material will make an attempt to explain the details
of PCIe protocol, its layers and the functions of each of the layers in a brief way.

PCI Express is a high performance, general purpose I/O interconnect defined for a
wide variety of future computing and communication platforms.

5.1 PCIe Link

A Link represents a dual-simplex communications channel between two components.


The fundamental PCI Express Link consists of two, low-voltage, differentially driven
signal pairs: a Transmit pair and a Receive pair

5.2 PCIe Fabric Topology

5.2.1 Root Complex

A Root Complex (RC) denotes the root of an I/O hierarchy that connects the

http://testbench.in/introduction_to_pci_express.html[9/26/2012 2:54:12 PM]


WWW.TESTBENCH.IN

CPU/memory subsystem to the I/O.

5.2.2 Endpoints

Endpoint refers to a type of Function that can be the Requester or Completer of a PCI
Express transaction either on its own behalf or on behalf of a distinct non-PCI Express
device (other than a PCI device or Host CPU), e.g., a PCI Express attached graphics
controller or a PCI Express-USB host controller. Endpoints are classified as either
legacy, PCI Express, or Root Complex Integrated Endpoints.

5.2.3 PCI Express to PCI/PCI-X Bridge

A PCI Express to PCI/PCI-X Bridge provides a connection between a PCI Express fabric
and a PCI/PCI-X hierarchy.

5.3 PCI Express Layering Overview

PCI Express can be divided into three discrete logical layers: the Transaction Layer,
the Data Link Layer, and the Physical Layer. Each of these layers is divided into two
sections: one that processes outbound (to be transmitted) information and one that
processes inbound (received) information.

PCI Express uses packets to communicate information between components. Packets


are formed in the Transaction and Data Link Layers to carry the information from the
transmitting component to the receiving component. As the transmitted packets flow
through the other layers, they are extended with additional information necessary to
handle packets at those layers. At the receiving side the reverse process occurs and
packets get transformed from their Physical Layer representation to the Data Link
Layer representation and finally (for Transaction Layer Packets) to the form that can
be processed by the Transaction Layer of the receiving device. Figure below shows the
conceptual flow of transaction level packet information through the layers.

http://testbench.in/introduction_to_pci_express.html[9/26/2012 2:54:12 PM]


WWW.TESTBENCH.IN

Note that a simpler form of packet communication is supported between two Data
Link Layers (connected to the same Link) for the purpose of Link management.

5.4 Layers of the Protocol

We take a brief look at the functions of each of the 3 layers.

5.4.1 Transaction Layer

This is the top layer that interacts with the software above.

Functions of Transaction Layer:

1. Mechanisms for differentiating the ordering and processing requirements of


Transaction Layer Packets (TLPs)

2. Credit-based flow control

3. TLP construction and processing

4. Association of transaction-level mechanisms with device resources including Flow


Control and Virtual Channel management

5.4.2 Data Link Layer

The Data Link Layer acts as an intermediate stage between the Transaction Layer and
the Physical Layer. Its primary responsibility is to provide a reliable mechanism for
exchanging Transaction Layer Packets (TLPs) between the two components on a Link.

Functions of Transaction Layer:


1. Data Exchange:
2. Error Detection and Retry:
3. Initialization and power management:

5.4.3 Physical Layer


The Physical Layer isolates the Transaction and Data Link Layers from the signaling
technology used for Link data interchange. The Physical Layer is divided into the
logical and electrical subblocks.

Logical Sub-block
Takes care of Symbol Encoding, framing, data scrambling, Link initialization and
training, Lane to lane de-skew

Electrical Sub-block
The electrical sub-block section defines the physical layer of PCI Express 5.0 GT/s
that consists of a reference clock source, Transmitter, channel, and Receiver. This
section defines the electrical-layer parameters required to guarantee interoperability
among the above-listed PCI Express components. This section comprehends both 2.5
GT/s and 5.0 GT/s electricals. In many cases the parameter definitions between 2.5
and 5.0 GT/s are identical, even though their respective values may differ. However,
the need at 5.0 GT/s to minimize guardbanding, while simultaneously comprehending
all phenomena affecting signal integrity, requires that all the PCI Express system
components - Transmitter, Receiver, channel, and Refclk, be explicitly defined in the
specification. For this reason, each of these four components has a separate
specification section for 5.0 GT/s.

http://testbench.in/introduction_to_pci_express.html[9/26/2012 2:54:12 PM]


WWW.TESTBENCH.IN

6 Changes in PCIe 3.0 (GEN3)

The goal of the PCI-SIG work group defining this next-generation interface was to
double the bandwidth of PCIe Gen 2, which is 5 gigatransfers per second (GT/s)
signaling but 4GT/s effective bandwidth after 8b/10b encoding overhead. The group
had two choices: either to increase the signaling rate to 10GT/s with 20 percent
encoding overhead or select a lower signaling rate (8GT/s) for better signal integrity
and reduced encoding overhead with a different set of challenges. The PCI-SIG
decided to go with 8GT/s and reduce the encoding overhead to offer approximately
7.99GT/s of effective bandwidth, approximately double that of PCIe Gen 2. The
increase in signaling rate from PCIe Gen 2's 5GT/s to PCIe Gen 3's 8GT/s provides a
sixty percent increase in data rate and the remainder of the effective bandwidth
increase comes from replacing the 8b/10b encoding (20 percent inefficiency) with
128b/130b coding (1-2 percent inefficiency). The challenge of moving from PCIe Gen 2
to Gen 3 is to accommodate the signaling rate where clock timing goes from 200ps to
125ps, jitter tolerance goes from 44ps to 14ps and the total sharable band (for SSC)
goes down from 80ps to 35ps. These are enormous challenges to overcome but the
PCI-SIG has already completed board, package, and system modeling to make sure
designers are able to develop systems that support these rates. The table below
highlights some key aspects of PCIe Gen 2 and Gen 3. The beauty of the Gen 3 solution
is that it will support twice the data rate with equal or lower power consumption than
PCIe Gen 2. Additionally, applications using PCIe Gen 2 would be able to migrate
seamlessly as the reference clock remains at 100MHz and the channel reach for
mobiles (8 inches), clients (14 inches), and volume servers (20 inches) stay the same.
More complex equalizers, such as decision feedback equalization, may be
implemented optionally for extended reach needed in a backplane environment. The
Gen 3 specification will enhance signaling by adding transmitter de-emphasis,
receiver equalization, and optimization of Tx/Rx Phase Lock Loops and Clock Data
Recovery. The Gen 3 specification also requires devices that support Gen 3 rate to
dynamically negotiate up or down to/from Gen 1 and Gen 2 data rates based on
signal/line conditions.

6.1 Benefits from the newer specs:-

6.1.1 Higher Speed

Goal: improve performance. Each successive generation doubles the bit rate of the
previous generation, and that holds true for Gen3, too, but there’s a significant
difference this time. Since the previous speed was 5.0 GT/s, the new speed would
normally have been 10.0 GT/s, but the spec writers considered a signal that used a
10GHz clock problematic because of the board design and signal integrity issues that
many vendors would face. Constrained to stay under that frequency, they were forced
to consider other options. The solution they chose was to move away from the 8b/10b

http://testbench.in/introduction_to_pci_express.html[9/26/2012 2:54:12 PM]


WWW.TESTBENCH.IN

encoding scheme that PCIe and most other serial transports have used because it adds
a 20% overhead from the receiver’s perspective. Instead, they chose a modified
scrambling method that effectively creates a 128/130 encoding method. This gain in
efficiency meant that an increase in frequency to only 8.0GHz would be enough to
achieve a doubling of the bandwidth and meet this goal

6.1.2 Resizable BAR Capability

Goal: allow the system to select how much system resource is allocated to a device.
This new optional set of registers allows functions to communicate their resources
size options to system software, which can then select the optimal size and
communicate that back to the function. Ideally, the software would use the largest
setting reported, since that would give the best performance, but it might choose a
smaller size to accommodate constrained resources. Currently, sizes from 1MB to
512GB are possible. If these registers are implemented, there is one capability
register to report the possible sizes, and one control register to select the desired size
for each BAR. Note that devices might report a smaller size by default to help them
be compatible in many systems, but using the smaller size would also reduce its
performance.

6.1.3 Dynamic Power Allocation

Goal: provide more software-controlled power states to improve power management


(PM). Some endpoint devices don’t have a device-specific driver to manage their
power efficiently, and DPA provides a means to fill that gap. DPA only applies when
the device is in the D0 state, and it defines up to 32 substates. Substate0 (default)
defines the max power, and successive sub-states have a power allocation equal to or
lower than the previous one. Software is permitted to change the sub-states in any
order. The Substate Control Enabled bit can be used to disable this capability. Any
time the device is changing between substates, it must always report the highest
power requirement of the two until the transition has been completed, and the time
needed to make the change is implementation specific.

To allow software to set up PM policies, functions define two transition latency values
and every substate associates its max transition time (longest time it takes to enter
that substate from any other substate) with one of those.

6.1.4 Alternative Routing-ID Interpretation

Goal: support a much larger number of functions inside devices. For requesters and
completers, this means treating the device number value as though it was really just
an extension of the function field to give an 8-bit value for the function number.
Since the device number is no longer included, it’s always assumed to be 0. The spec
also defines a new set of optional registers that can be used to assign a function
group number to each function. Within an ARI device, several functions can be
associated with a single group number, and that can serve as the basis for arbitration
or access control.

References:
www.arstechnica.com
www.pcisig.com
www.pcstats.com
www.digitalhomedesignline.com

copyright © 2007 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/introduction_to_pci_express.html[9/26/2012 2:54:12 PM]


WWW.TESTBENCH.IN

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS
About the author:
SystemVerilog VCSMX Separate compilation example
Verification Emmanuelle Chu
is EDA support engineer
Constructs When I started to use VCSMX along with system Verilog, one main problem came up: I at Texas Instruments
Interface had to generate one executable for each program. (Nice Area, France). She
Coming up with VCSMX version 2008.12, the separate compile feature was introduced is with TI from 2004.
OOPS Emmanuelle Chu is an
to solve the problem; anyway the working model is quite strict. I used as a starting
Randomization point "switch" example from www.testbench.in to illustrate the separate compile master in Electronics
flow. The idea is to generate a partition of your program file that would be loaded and computers from
Functional Coverage ENSSAT.
when you launch your executable. A single image of your design is needed; if you
Assertion change your program file, you would only need to analyze it and generate a new
DPI partition. Please have a look to the Makefile provided along with the testcase. The
version 2008.12-2 of VCSMX was used to set up the testcase.
UVM Tutorial Report a Bug or Comment
1. Compile your DUT on This section - Your
VMM Tutorial
comp_dut input is what keeps
OVM Tutorial Testbench.in improving
2. Compile the testbench components for a given package. with time!
Easy Labs : SV
comp_pack
Easy Labs : UVM
Easy Labs : OVM - Analyze the code with vlogan..
- Generate shared object libraries for each package with VCS.
Easy Labs : VMM - Repeat these steps for each package.
AVM Switch TB
In VMM methodology, a class should be defined within a package, Driver.sv, packet.sv
VMM Ethernet sample and environment.sv are now system verilog packages.
Partition should also be generated for packages [separate compile feature steps]

Verilog 3. Compile the testcases.


Verification comp_prg
Verilog Switch TB - Analyze the code with vlogan and specify a unique partition name for each testcase.
Basic Constructs
- Generate shared object libraries for different program partitions with VCS.

4. Generate a program shell file from the program block.


OpenVera gen_shell
Constructs
Switch TB This shell file is used for compiling the main simv in order to provide a hook for
dynamic linking of the testbench at runtime. The testcases must have the same
RVM Switch TB program block name so that only one shell file is required to load the testcases.
RVM Ethernet sample
5. Analyze the top level testbench file:
comp_top
Specman E You must compile in different libraries the test bench files and the design part. rtl.sv '
Interview Questions current Driver.sv, packet.sv, environment.sv and interface.sv ' testcase Top.sv
interface.sv ' current Interface.sv is analyzed twice but in current and testcases
libraries. This is due to the separate compile feature and also because environment.sv
and top.sv instantiates interfaces.

6. Generate simv, which includes the DUT, program shell file, and top module to link
the DUT with the program shell file.
elab

7. Run simulations using the generated simv, specifying the partitions that need to be
loaded

http://testbench.in/vcsmx_separate_compilation.html[9/26/2012 2:54:22 PM]


WWW.TESTBENCH.IN

run

Repeat steps 3 or 4 followed by step 7 to further develop the testbench or testcases,


and later in the testing cycle, to run your tests and regressions.

Download the example

copyright © 2007 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/vcsmx_separate_compilation.html[9/26/2012 2:54:22 PM]


WWW.TESTBENCH.IN

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS

SystemVerilog PSYCHOLOGY OF VERIFICATION ENGINEER About the author:


Verification
Gopi Krishna He is the
Constructs Broadly speaking, we can view Verification Engineer as having two kinds of skills: one Author of testbench.in.
Interface set used to perform basic duties at work, and another set of skills used to approach
work. The former can be categorized as technical skills and the latter as soft skills.
OOPS
Randomization While the technical skills are absolutely important for a Verification Engineer, there Report a Bug or Comment
are certain soft skills that should complement the technical abilities. A on This section - Your
Functional Coverage input is what keeps
comprehensive Verification engineer should have a blend of the technical and soft
Assertion skills. Testbench.in improving
with time!
DPI
 To elaborate more on soft skills, these are the ones that define one's approach
UVM Tutorial towards work, life, problems, etc. Soft skills are people skills. The best part about
VMM Tutorial mastering them is that the application of these skills is not limited to one's profession,
but their scope reaches all aspects of life. Technical skills may teach one how to meet
OVM Tutorial the expectations of the job, but soft skills teach one to succeed, and to exceed
Easy Labs : SV expectations. There are many situations that we come across on the day-to-day work
life as a Verification engineer in which one person perform better than the others just
Easy Labs : UVM on the basis of Soft skills- be it winning an argument with RTL designer on the basis of
Easy Labs : OVM his/her communication or finding handling multiple tasks effectively because if
superior organizational abilities etc.
Easy Labs : VMM   
AVM Switch TB Soft skills are extremely important for the people in Verification and this is something
that is often found to be neglected by the upcoming Verification engineers. It is
VMM Ethernet sample surprising that we spend our time educating almost exclusively in technical skills.

Human beings reaction in this complex world of happenings varies widely with respect
Verilog to situations, surroundings, emotions, need, requirements, time frame, money,
Verification visualization, belief, education, knowledge, expertise, intuition and so on. Such
complex is the nature of human being and certainly there's no exception at work place
Verilog Switch TB too. Therefore it's cynical to say that the job being done by a Verification Engineer is
Basic Constructs simple & complete.

The quality of the job done by the verification engineer is directly proportional to his
or her psychological maturity and profoundness acquired, adopted and developed with
OpenVera age and experience.
Constructs
Switch TB Let's examine the psychology of the verification engineer by describing the definition
of Verification under three circumstances.
RVM Switch TB
RVM Ethernet sample
"Functional Verification is the process to prove that the RTL works as per the
specification"
Specman E "Functional verification is the process to find all the bugs present in the RTL design"  
Interview Questions
"Functional Verification is the process to detect the defects and minimize the risks
associated with the residual defects"

Above three definitions are upside-down. Understanding the true definition of


Functional verification can make a profound difference in the success of your efforts.

1)

http://testbench.in/PH_01_PSYCHOLOGY_OF_VERIFICATION_ENGINEER.html[9/26/2012 2:54:29 PM]


WWW.TESTBENCH.IN

"Functional Verification is the process to prove that the RTL works as per the
specification"

Generally this definition is given by the RTL designers or the new verification
engineers with prior RTL design experience. The above definition sounds good if the
RTL designer itself is trying to verify his implementation .  RTL designer intentions
would mostly revolve around the point to prove that the RTL meets the specification.
RTL designer will exercise only those inputs for which the correct results are obtained
and are specified in the specification and the DUT can still contain bugs which will not
be visible.

2)

"Functional verification is the process to find all the bugs present in the RTL design"  

This definition sounds good epically if the main aim of the verification engineer is to
prove that the RTL work for what it's supposed to do and not what is not supposed to
do. This type of psychology would bring out the most of the bugs in the RTL.  This goal
is impossible to achieve.

3)

"Functional Verification is the process to detect the defects and minimize the risks
associated with the residual defects"

This definition appears to sound realistic. Practically, if at any point, the RTL
development starts, the verification should start and keep in track the number of bugs
being detected while correcting.

 
At some stage of a planned verification, there would be a stage where no bugs are
identified after many days or weeks or sometimes months of verification which
statistically allows you to conclude that the RTL is "good enough" to be released to
next step. i.e. there may still exist some bugs undetected, but the risk associated with
the residual defects is not very high or are tolerable.

From the above three definitions, we can understand that the psychology of a
verification engineer plays a vital role throughout the ASIC development cycle.

Role And Characteristics Of A Verification Engineer

Verification Engineer requires technical skills similar to RTL designers, but Verification
engineers need to acquire other skills, as well.

Most engineers that I've talked to over the years believe that the mind-set and
personality of a good Verification engineer are different from those of a good RTL
designers. For example Verification engineer are more experimental then RTL
designers.

 Keen Observation
 Detective Skills
 Deduction skills
 Destructive Creativity and Negative Thinking
 Understanding the DUT as an integration of its parts
 Cynical but Affable Attitude
 Organized, Flexible and Patience at Job
 Objective and Neutral Attitude
 Discipline and Perseverance
 Communication Skills
 Learning from Past

http://testbench.in/PH_01_PSYCHOLOGY_OF_VERIFICATION_ENGINEER.html[9/26/2012 2:54:29 PM]


WWW.TESTBENCH.IN

 Eagerness to embrace new technologies, methods and flows

Keen Observation

The Verification engineer must possess the qualities of an 'eye for detail'. A keen
observation is the prime quality any Verification engineer must possess. Not all bugs
are visible clearly to the naked eye. With keen observation, the Verification engineer
can easily identify or detect many critical bugs. Verification engineer should learn
how to look for details, how to analyze the things from different possible dimensions.
The more observant a verification engineer is, the more likely he is detecting more
bugs.

Without observation, it is impossible to tell the outcome of a test or an experiment.


Although this makes sense, it is tempting to design tests and experiments that are
difficult if not impossible to observe. We may want to prove or test something, but
real-world constraints prevent constructing an accurate experiment. That's why you
can't verify everything and not everything is verifiable.

Detective Skills

Ideally the Design under development would be documented before, after and
throughout the development process. Unfortunately, there is every chance of not
updating the documentation (specification, defect reports etc) due to time and
resource constraints.

The Verification engineer should therefore apply his knowledge of rationalization in


knowing about the DUT from formal system like system specifications, design &
functional specifications, review notes etc. From this information, the Verification
engineer should look for researching more analytical information through other
sources called non-formal sources of information like RTL designers, previous version
test plans, bugs and related product documents, reviews of related and (seemingly)
unrelated documents.

A Verification engineer should therefore possess the quality of a 'detective' to explore


the product under test, more rationally

Deduction Skills

A Verification engineer with deduction skills is also likely to be good at issue solving.
Deduction skill is an ability to analyze the meanings of the signs and deriving of a
conclusion by reasoning. It's a logical thinking, which helps a Verification engineer to
differentiate a bug from a false one. Deduction skills may come from practice of
cognitive information processing, power of interpretation and can help a Verification
engineer in differencing and decision making.
Deduction skills play major role while debugging. Not all the verification engineers
can debug an issue at same speed. Looking at some waveform signals, log messages,
he has to isolate or locate it. In Verification life cycle, everything can be planned and
can meet the schedule in time except debugging. Time spent in debugging is
unpredictable and cannot be planned ahead.  

Destructive Creativity Or Negative Thinking

Most human beings are constructive in nature rather than destructive.


The Verification engineer need to develop destructive skills ,means skills to perturb
and crash RTL functionality. In other words, the Verification engineer should 'not
hesitate to break the RTL functionality. In the world of functional verification,
boundaries are meant to be crossed not obeyed.

A creative oriented but destructive approach is necessary while verifying a RTL by the
Verification engineer to make the RTL Design evolve more robustly and reliably.

Negative Thinking is a art. While mentioning the risks involved in the project, a
Verification engineer has to consider all the things that can go wrong. Training the
mind to think negatively in required situations helps Verification engineer develop an
efficient contingency plan.  
 
A word of caution here; distractive skills are useful only for specific situations. A
Verification engineer has to be smart enough to identify such situations and wear an
appropriate thinking hat to deal with the situation.  

Understanding The Dut As An Integration Of Its Parts

http://testbench.in/PH_01_PSYCHOLOGY_OF_VERIFICATION_ENGINEER.html[9/26/2012 2:54:29 PM]


WWW.TESTBENCH.IN

The RTL design is a culmination of lines of code interacting with data through user
interfaces. It is an integration of separate group of code interacting with other groups
assembled together to function as a whole chip. The developers might be working on
a respective piece of code module focusing more on those modules under work, at a
time.

It is no wonder if the developer sometimes may not even know the complete workflow
of the RTL and not necessary too. Whereas, in the case of a Verification engineer,
being the rider of the DUT, should understand and know about the complete
specifications of the DUT.

The Verification engineer may not be the best expert on any one module of the RTL
but definitely he/she should gain expertise on the overall operation of the RTL
Design. In fact, the Verification engineer should possess a 'Systems' view of the RTL
design because they are the only people to see and verify the complete functionality
of interdependent modules and compatibility.

Cynical But Affable Attitude

Irrespective of the nature of the RTL design, the Verification engineer need to be
tenacious in questioning even the smallest ambiguity until it is proved.

There may arise some situations during the course of verification , a large number of
bugs might be encountered unusually which might compel to further delay in RTL
freezing. This may lead to heat up the relation between the Verification engineer and
RTL design teams. The Verification engineer should balance this relationship not at
the cost of the bugs but by convincing and upholding their intentions to "assault the
RTL design but not the RTL developers".

Organized, Flexible And Patience At Job

Verification engineer must remember the fact that not all the tests planned are
performed completely and some tests dependent on other tests has to be blocked for
later testing. We manage ourselves, our tasks, so that we make the most of our time.
Verification engineer have to juggle a lot of tasks.

This needs an organized approach by the Verification engineer in attempting to phase


out the bugs. Sometimes, significant tests has to be rerun which would change the
fundamental functionality of the RTL design. The Verification engineer should
therefore have patience to retest the planned bugs and any new bugs that may arise.

It is even more important to the Verification engineer to be patient and keep


prepared in the event of a dynamic development and test model. Development keeps
changing continuously as requirements and technology keeps changing rapidly and so
should Verification. The Verification engineer must take these changes into account
and plan to perform tests while maintaining the control of Verification environment to
ensure valid test results.

Objective And Neutral Attitude

Nobody would like to hear and believe bad news, right? Well, Verification engineer
are sometimes viewed as messengers of bad news in a team. No wonder, how good
the Verification engineer is (meaning very negative) and brilliant in doing his job
(identifying bugs-no one likes to do it but most human beings are taken for granted to
be naturally very good at it, at least from childhood), he/she might always be a
messenger of communicating the bad part, which, the creators (developers) doesn't
like it.

The Verification engineer must be able to deal with the situation where he/she is
blamed for doing his/her job (detecting bugs) too good. The Verification engineer's
jobs must be appreciated and the bugs should be welcomed by the RTL design team
because every potential bug found by the Verification engineer would mean a
reduction of one bug that would potentially might have been encountered in later
stage.

Irrespective of the negative aspects of doing such a highly skillful job, the role of a
Verification engineer is to report honestly every known bug encountered in the
product with always an objective and a neutral attitude.

Discipline And Perseverance

http://testbench.in/PH_01_PSYCHOLOGY_OF_VERIFICATION_ENGINEER.html[9/26/2012 2:54:29 PM]


WWW.TESTBENCH.IN

One obvious aspect of verification is that it can be extremely repetitive and may
require a lot of manual effort. Consider the following situations:

 A Verification engineer is struck with a bug that is not reproducible at all the
instances. In order to reproduce the bug he goes through the whole series of steps
again and again.

 As part of a daily routine, a Verification engineer has been asked to collect data
about test cases executed, bugs reported, etc.

There can be numerous examples that prove the reiterative nature of the job.
A very predictable reaction to this repetition is to simply get tired of the job. But soft
skills include the psychological tools to persevere, and to find ways to make effort
more productive and interesting. This attitude difference helps a Verification
engineer maintain focus and higher levels of quality work. It brings the ability to carry
out task at hand in spite of difficulty.

Communication Skills

Communication skills form the necessary ingredients for success in any profession.
Communication is something that we always do in our personal lives as well as
professional life. Communication is a very basic human skill and one cannot go very far
without it. Communication in this context does not involve any body language; so it's
the pure word power, which rules the situation. Though most of us agree that these
skills are important, very few of us give these skills a high enough priority. For a VE,
both verbal and written communication is crucial.

If your written communication is bad, you'll miss the salient points - the audience
won't know the important stuff - or you'll put the audience to sleep. This means your
bug reports will bounce back as "invalid" / "unable to reproduce" / "won't fix."

Many instances can be thought of in the day-to-day work of Verification engineer,


where a Verification engineer can make a difference to the situations with effective
communications skills.

Learn From Past

Keep learning from past experience and try not getting caught in any mistakes that
have been made earlier. A common saying is "Never repeat the same mistake again". A
verification engineer should know not only his mistakes, but also the RTL Designers
mistakes. If RTL designers does the same mistake, Verification engineer past
experience on catching the same mistake increases the possibility of the finding the
mistake easily.

Mistakes can be categorizes into 4 categories:

Stupid:
Absurdly dumb things that just happen.  

Simple:
Mistakes that are avoidable but your sequence of decisions made inevitable.

Involved:
Mistakes that are understood but require effort to prevent.

Complex:
Mistakes that have complicated causes and no obvious way to avoid next time.

Eagerness To Embrace New Technologies, Methods And Flows

A Verification engineer should have enthusiasm to learn new technologies, methods


and flows and eagerness to progress further. Today's functional verification is still in
research stage. Even most of the terminology is not stable across the industry. As the
research is going on, companies are adopting new technologies and the Verification
engineers should be able to learn them.

copyright © 2007 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/PH_01_PSYCHOLOGY_OF_VERIFICATION_ENGINEER.html[9/26/2012 2:54:29 PM]


WWW.TESTBENCH.IN

http://testbench.in/PH_01_PSYCHOLOGY_OF_VERIFICATION_ENGINEER.html[9/26/2012 2:54:29 PM]


WWW.TESTBENCH.IN

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS
About the author:
SystemVerilog Graphical Test Bench Generation
Verification Donna Mitchell
is Vice President of
Constructs Test bench code is often difficult to understand, even when written using modular Marketing and Co-
Interface programming techniques, because of the large amount of parallel activity occurring in Founder of SynaptiCAD
the test bench that is not apparent when just reading through the code. However, Sales Inc. Mitchell's
OOPS industry experience
when that same parallel activity is displayed as waveforms in a timing diagram the
Randomization interaction between the signals is obvious from just glancing at the timing diagram. includes 20 years of
Timing diagrams allow a much clearer and concise description of the interaction of hardware and software
Functional Coverage development.
parallel processes and signal activity than can be achieved by writing code. A
Assertion graphical representation also facilitates the collaboration of many engineers on a
DPI single test bench by removing the need to interpret source code. Any engineer
familiar with the design specifications is able to look at a given timing diagram and
UVM Tutorial have an immediate understanding of what the transactor does, dramatically Report a Bug or Comment
simplifying test bench maintenance. on This section - Your
VMM Tutorial
input is what keeps
OVM Tutorial There are several tools on the market that can take basic waveforms and generate Testbench.in improving
Easy Labs : SV simple VHDL and Verilog models. This article will discuss the tools offered by with time!
SynaptiCAD, because they offer three different levels of test bench generation ranging
Easy Labs : UVM from simple stimulus test benches, test benches that monitor system reaction during
Easy Labs : OVM simulation, to full bus-functional models that behaviorally model the outside system.
We will show examples of timing diagrams and some of the code that they can
Easy Labs : VMM generate.
AVM Switch TB
VMM Ethernet sample Level 1: Basic Stimulus Generation

The most basic of the graphical testbench generation tools can take drawn waveforms
Verilog and generate VHDL or Verilog stimulus. This level of test bench generation is great for
Verification generating quick small test benches, because the temporal relationships between
edges are easier to see in a graphical timing diagram then in raw VHDL or Verilog
Verilog Switch TB code. This simple graphical test bench generation can be found in many timing
Basic Constructs diagram editors and several graphical simulator-debugging environments. SynaptiCAD
offers it in their WaveFormer Pro timing diagram editor and in their BugHunter Pro
simulation debugging environment.
OpenVera Below is an image of a simple timing diagram that was drawn in WaveFormer Pro. This
Constructs shows how different types of signals, buses, and clocks will generate stimulus code.
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

Once a timing diagram is finished, the test bench code can be generated via a simple

http://testbench.in/graphicaltestbench.html[9/26/2012 2:54:38 PM]


WWW.TESTBENCH.IN

file save operation. WaveFormer generates either a Verilog module or a VHDL


entity/architecture model for the stimulus test bench. This test bench model can then
be instantiated in a user's project and compiled and simulated with the rest of the
design. Below is an example of a timing diagram and some of the VHDL code that was
generated from the timing diagram.

-- Generated by WaveFormer Pro Version


library ieee, std;
use ieee.std_logic_1164.all;
 
entity stimulus is
  port (
    SIG0 : out std_logic := 'Z';
    SIG1 : out std_logic_vector(3 downto 0) := "ZZZZ";
    SIG2 : out integer;
    SIG3 : out MyColor;
    CLK0 : out std_logic := 'Z');
      -- more entity code
end stimulus;
 
architecture STIMULATOR of stimulus is
 
  -- some signal and parameter declarations
 
begin
 
  -- clock and status setup code
 
  -- Clock Process
  CLK0_process : process
    variable CLK0_low : real;
    variable CLK0_high : real;
  begin
    tb_mainloop : loop
      wait until (tb_status = TB_ONCE)
                 or (tb_status = TB_LOOPING);
      CLK0_high := CLK0_Period * CLK0_Duty / 100.0;
      CLK0_low := CLK0_Period - CLK0_high;
        -- more clock code
    end loop;
  end process;
 
  -- Sequence: Unclocked
  Unclocked : process
  begin
    SIG0_driver <= '0';
    SIG1_driver <= x"3";
    SIG2_driver <= 1;
    SIG3_driver <= Yellow;
    wait for 45.0 ns;
    SIG1_driver <= x"F";
    wait for 5.0 ns;
      -- more signal statements
    wait;
  end process;
end STIMULATOR;

In the generated code, notice that the clock is a parameterized process. Not all tools
generate clock signals this way, but it makes it easy for the user to modify the
operation of the test bench by changing the values of the clock variables.

WaveFormer also supports complex data types and user-defined types. Notice that
SIG1 has a VHDL type of integer. In WaveFormer, the VHDL and Verilog types of signals
can be changed using the Signals Properties dialog. VHDL user-defined types can also
be entered through the same interface as demonstrated by the SIG3 signal.

For larger test benches, the waveform data can be imported from an outside source
like a logic analyzer, simulator, or spreadsheet. For example, if you are designing a

http://testbench.in/graphicaltestbench.html[9/26/2012 2:54:38 PM]


WWW.TESTBENCH.IN

new ASIC to upgrade an existing communications system, then you can use a logic
analyzer to capture stimulus vectors from the communications system and use
WaveFormer to translate the data into a VHDL test bench to test the new ASIC design.
It is important to investigate whether the test bench tool you are using can read the
type of files that your waveform data is in.

Level 2: Reactive Test Bench Generation

The next level up in graphical test bench generation is to add elements to the timing
diagram that will generate code to check the behavior of the model under test (MUT)
during simulation. In the SynaptiCAD tool line, you can add the Reactive Test Bench
Option to any of the tools that support basic stimulus generation.

In the timing diagram, the user draws both the stimulus waveforms (black) and the
expected output of the model under test (blue waveforms). Samples are added to the
blue expected waveforms to generate specific tests at those points in the diagram.
During simulation if the actual value is different from the expected value at the
sample point, then a report will be generated that describes the discrepancy between
the expected and actual value from the model under test.

Below is a picture of the generated code for the sample that is used to check the
output of the read cycle.

Often reactive test bench tools include a method for repeating sections of the
waveforms. With SynaptiCAD’s tools the user places marker lines on the diagram to
define the beginning and ending of loops. Loops can also depend on the sampled
values of expected output from the model under test. This way the test bench can be
made to "react" to the behavior of the model under test during simulation.

http://testbench.in/graphicaltestbench.html[9/26/2012 2:54:38 PM]


WWW.TESTBENCH.IN

Reactive test bench generation often allows the option of creating "clock-based" test
benches as well as the "time-based" test benches currently supported by the stimulus
based generation models. Clock-based test benches delay in clock cycles instead of
times, allowing the user to change his clock frequency without needing to change his
timing diagram. Clock-based test benches are also required when testing using high-
speed "cycle-based" simulators.

Level 3: Bus-Functional Model (BFM) Generation

As your test benches become more and more complicated, it will become more
difficult to model them using a single timing diagram as described in the previous two
levels. SynaptiCAD offers TestBencher Pro to overcome this problem. At the time of
this writing TestBencher is the only graphical test bench generator that can take
multiple timing diagrams and generate a complete bus functional model from them.

TestBencher generates a transactor for each timing diagram in the project. A


transactor represents a reusable interface specification of the bus-functional model
that you are creating (e.g., read cycle, write cycle, interrupt cycle). These
transactors are modules for Verilog, entity/architecture pairs for VHDL and classes
for TestBuilder. Regardless of the language, the transactors use the same general
architecture.

Once the transactions are defined, the user writes a sequencer process to apply the
timing diagrams to the model under test. Inside the sequencer process the user can
write behavioral VHDL or Verilog code to pass in variables and process information to

http://testbench.in/graphicaltestbench.html[9/26/2012 2:54:38 PM]


WWW.TESTBENCH.IN

the transactions. TestBencher also has a graphical interface for assisting the user in
writing the apply calls. Below is an example of a sequencer process that repetitively
applies a write transaction followed by a read transaction. Each time the loop is
performed the delay value is changed so that model is tested over different delay
times.

   // Sequencer Process
   real delay0; // delay0 will serve as the index and the delay value
   initial
   begin
      for (delay0 = 32.0; delay0 > 5.0; delay0 = delay0 - 5.0)
      begin
         // Apply_Tbwrite( addr , data , $realtobits(delay0_min) );
         Apply_Tbwrite( 'hF0 , 'hAE , $realtobits(delay0) );
         // Apply_tbread( addr , data , $realtobits(delay0_min) );
         Apply_tbread( 'hF0 , 'hAE , $realtobits(delay0));
      end
  
   Abort_tbglobal_clock;
   $fclose(logfile);
   end

TestBencher Pro also supports hierarchical BFM design by allowing projects to be


instantiated inside other projects. This lets you develop and verify complex test
benches in an incremental manor. For example, if you are designing a test bench for
an ATM switch, you can develop a project that can transmit an ATM cell to an
interface port on the ATM switch. After you have tested your transmitter project, you
can make it a sub-project and instantiate a copy of it for each different port of the
ATM switch.

Summary of Graphical Test Bench Generation

You can free yourself from the time-consuming process of writing Verilog and VHDL
test benches by hand and instead generate them graphically from timing diagrams
using a timing diagram editor. By using timing diagrams, the engineer can work at a
higher level abstraction, free from the tedious details of the underlying code. This
graphical representation facilitates the collaboration of many engineers on a single
test bench by removing the need to interpret HDL source code. Any engineer familiar
with the design specifications is able to look at a given timing diagram and have an
immediate understanding of what the transaction is doing. This level of abstraction
also provides a great aid in terms of maintainability. The first step in choosing a test
bench generator is to determine the complexity of your expected test bench and then
to pick a tool that can generate that code. This article described the functionality of
test bench tools offered by SynaptiCAD. If you would like to experiment with these
tools you can find more information on the http://www.syncad.com/syn_tb_diff.htm
page of the SynaptiCAD web site.

copyright © 2007 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/graphicaltestbench.html[9/26/2012 2:54:38 PM]


WWW.TESTBENCH.IN

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS
About the author:
SystemVerilog Verilog Basic Examples
Verification Nithin Singani
is perusing Master of
Constructs AND GATE Technology in VLSI &
Interface   Embedded Systems in
Truth Table Manipal University,
OOPS India.
 
Randomization
Functional Coverage
Assertion Report a Bug or Comment
on This section - Your
DPI input is what keeps
UVM Tutorial Testbench.in improving
with time!
VMM Tutorial
OVM Tutorial Verilog design
Easy Labs : SV
//in data flow model
Easy Labs : UVM module and_gate(
Easy Labs : OVM     input a,b,    
    output y);
Easy Labs : VMM
AVM Switch TB //Above style of declaring ports is ANSI style.Verilog2001 Feature
VMM Ethernet sample
   assign y = a & b;

endmodule
Verilog
Verification TestBench
Verilog Switch TB module tb_and_gate;
Basic Constructs     
    reg A,B;
    wire Y;
    
OpenVera
    and_gate a1 (.a(A) ,.b(B),.y(Y));
Constructs     
Switch TB     //Above style is connecting by names
    
RVM Switch TB     initial begin
RVM Ethernet sample         A =1'b0;
        B= 1'b0;
        #45 $finish;
    end
Specman E     
Interview Questions     always #6 A =~A;
    always #3 B =~B;
    
    always @(Y)
    $display( "time =%0t \tINPUT VALUES: \t A=%b B =%b \t output value
Y  =%b",$time,A,B,Y);
endmodule

output

time =0         INPUT VALUES:    A=0 B =0        output value Y=0

http://testbench.in/verilog_basic_examples.html[9/26/2012 2:54:49 PM]


WWW.TESTBENCH.IN

time =6         INPUT VALUES:    A=1 B=0        output value Y =0


time =9         INPUT VALUES:    A=1 B =1        output value Y =1
time =12        INPUT VALUES:    A=0 B =0        output value Y =0
time =18        INPUT VALUES:    a=1 b =0        output value y =0

 
XOR GATE

Truth Table
 

Verilog design

//in Structural model

module xor_gate (
input a,b,
output y);

   xor x1(y,a, b); //xor is a built in primitive. While using these primitives you should


follow the connection rules. First signal should be output and then inputs.

endmodule

TestBench

module tb_and_gate;

    reg A,B;
    wire Y;
    
    xor_gate a1 (.a(A) ,.b(B),.y(Y));        
    
    initial begin
    
        A =1'b0;
        B= 1'b0;
        #45 $finish;
    
    end    
    
    always #6 A =~A;
    always #3 B =~B;
    
    always @(Y)
    $display( "time =%0t \tINPUT VALUES: \t A=%b B =%b \t output value Y
=%b",$time,A,B,Y);

endmodule

output

time =0         INPUT VALUES:    A=0 B =0        output value Y =0


time =3         INPUT VALUES:    A=0 B =1        output value Y =1
time =6         INPUT VALUES:    A=1 B =0        output value Y =1
time =9         INPUT VALUES:    A=1 B =1        output value Y =0

OR GATE

http://testbench.in/verilog_basic_examples.html[9/26/2012 2:54:49 PM]


WWW.TESTBENCH.IN

 
Truth Table
 

Verilog design

//in Behaviour model


module or_gate(
input a,b,
output reg  y);

    always @(a,b)
    
    y = a |b;

endmodule

TestBench

module tb_and_gate;
reg A,B;
wire Y;

or_gate a1 (.a(A) ,.b(B),.y(Y));

initial begin
    
    A =1'b0;
    B= 1'b0;
    #45 $finish;
    
end

always #6 A =~A;
always #3 B =~B;

always @(Y)
$display( "time =%0t \tINPUT VALUES: \t A=%b B =%b \t output value Y
=%b",$time,A,B,Y);

endmodule

output

time =0         INPUT VALUES:    A=0 B =0        output value Y =0


time =3         INPUT VALUES:    A=0 B =1        output value Y =1
time =12        INPUT VALUES:    A=0 B =0        output value Y =0
time =15        INPUT VALUES:    A=0 B =1        output value Y =1
time =24        INPUT VALUES:    A=0 B =0        output value Y =0

Half Adder
 
Truth Table
 

Verilog design

http://testbench.in/verilog_basic_examples.html[9/26/2012 2:54:49 PM]


WWW.TESTBENCH.IN

module half_adder(
input a,b,
output sum,carry);

   assign sum = a^b;
   assign carry = a & b;

endmodule

TestBench

module tb_half_adder;

    reg A,B;
    wire SUM,CARRY;
    
    half_adder HA (.a(A) ,.b(B),.sum(SUM),.carry(CARRY))
    
    initial begin
        A =1'b0;
        B= 1'b0;
        #45 $finish;
    end
    
    always #6 A =~A;
    always #3 B =~B;
    
    always @(SUM,CARRY)
    $display( "time =%0t \tINPUT VALUES: \t A=%b B =%b \t output value SUM =%b CARRY
=%b ",$time,A,B,SUM,CARRY);

endmodule

output

time =0         INPUT VALUES:    A=0 B =0        output value SUM =0 CARRY =0


time =3         INPUT VALUES:    A=0 B =1        output value SUM =1 CARRY =0
time =6         INPUT VALUES:    A=1 B =0        output value SUM =1 CARRY =0
time =9         INPUT VALUES:    A=1 B =1        output value SUM =0 CARRY =1

Full Adder
 
 

Verilog design

module full_adder(
input a,b,cin,
output reg  sum,cout);

   always @(*) begin
       sum = a^b^cin;
       cout = (a&b)+(b&cin)+(cin&a);
   end

http://testbench.in/verilog_basic_examples.html[9/26/2012 2:54:49 PM]


WWW.TESTBENCH.IN

endmodule

TestBench

module tb_full_adder;

     reg A,B,CIN;
     wire SUM,COUT;
    
     full_adder FA (.a(A) ,.b(B),.sum(SUM),.cin(CIN),.cout(COUT));
    
     initial begin
         A =1'b0;
         B= 1'b0;
         CIN = 1'b0;
         #45 $finish;
     end
    
     always #6 A =~A;
     always #3 B =~B;
     always #12 CIN = ~CIN;
    
     always @(SUM,COUT)
     $display( "time =%0t \tINPUT VALUES: \t A =%b B =%b CIN =%b \t output value
SUM          
      =%b COUT =%b ",$time,A,B,CIN,SUM,COUT);

endmodule

output

time =0         INPUT VALUES:    A =0 B =0 CIN =0        output value SUM =0 COUT =0


time =3         INPUT VALUES:    A =0 B =1 CIN =0        output value SUM =1 COUT =0
time =9         INPUT VALUES:    A =1 B =1 CIN =0        output value SUM =0 COUT =1
time =12        INPUT VALUES:    A =0 B =0 CIN =1        output value SUM =1 COUT =0
time =15        INPUT VALUES:    A =0 B =1 CIN =1        output value SUM =0 COUT =1

Ripple Carry  Adder(Parameterized and using generate )


 
Verilog design
`include "full_adder.v"

//Full_added.v contains above defined(Full ADDER) program

module ripple_carry(a,b,cin,cout,sum);
    
    parameter N=4;
    
    input   [N-1 :0] a,b;
    input   cin;
    output [N-1:0]sum;
    output cout;
    
    wire [N:0]carry;
    
    assign carry[0]=cin;
    
    //generate statement without using label is verilog-2005 feature. Generate
statement is verilog-2001 feature.
    genvar i;
    generate for(i=0;i<N;i=i+1) begin
    full_adder FA (.a(a[i]),.b(b[i]),.cin(carry[i]),.sum(sum[i]),.cout(carry[i+1]));
    end
    
    endgenerate
    
    assign cout = carry[N];
    
endmodule

TestBench  Using $random

http://testbench.in/verilog_basic_examples.html[9/26/2012 2:54:49 PM]


WWW.TESTBENCH.IN

module tb_ripple_carry;

    parameter N=4;
    
    reg [N-1:0]A,B;
    reg CIN;
    wire [N-1:0]SUM;
    wire COUT;
    
    ripple_carry RCA(.a(A),.b(B),.cin(CIN),.sum(SUM),.cout(COUT));
    
    initial begin
       A= 4'b0000;
       B= 4'b0000;
       CIN =1'b0;
      
       repeat(10)
       input_generate(A,B,CIN);
       #45 $finish;
    end
    
    task input_generate;
    output [N-1:0]A_t,B_t;
    output CIN_t;
    begin
        #4;
        A_t = $random % 4;
        //Above statement will generate Random values from -3 to +3.
        B_t = $random % 4;
        CIN_t =$random;
    end
    endtask
    
    task display;
    input [N-1:0] A_td,B_td,SUM_td;
    input CIN_td,COUT_td;
    
    $strobe("Time =%0t \t INPUT VALUES A=%b B=%b CIN =%b \t OUTPUT VALUES SUM
=%b COUT =%b",$time,A_td,B_td,CIN_td,SUM_td,COUT_td);
    
    endtask
    
    always@(SUM,A,COUT)
    
    $display(A,B,SUM,CIN,COUT);

endmodule

output

Time =0   INPUT VALUES A=0000 B=0000 CIN =0   OUTPUT VALUES SUM =0000 COUT =0
Time =4   INPUT VALUES A=0000 B=1101 CIN =1   OUTPUT VALUES SUM =1110 COUT =0
Time =8   INPUT VALUES A=1111 B=0001 CIN =1   OUTPUT VALUES SUM =0001 COUT =1
Time =12   INPUT VALUES A=1101 B=1110 CIN =1 OUTPUT VALUES SUM =1100 COUT =1
Time =16   INPUT VALUES A=0001 B=0010 CIN =1 OUTPUT VALUES SUM =0100 COUT =0
Time =20   INPUT VALUES A=0001 B=0000 CIN =1 OUTPUT VALUES SUM =0010 COUT =0
Time =24   INPUT VALUES A=1110 B=1101 CIN =0 OUTPUT VALUES SUM =1011 COUT =1
Time =28   INPUT VALUES A=0001 B=1111 CIN =0 OUTPUT VALUES SUM =0000 COUT =1
Time =32   INPUT VALUES A=0011 B=0010 CIN =0 OUTPUT VALUES SUM =0101 COUT =0
Time =36   INPUT VALUES A=0000 B=1101 CIN =0 OUTPUT VALUES SUM =1101 COUT =0

Multiplexer(2:1)
 
Truth Table
 

http://testbench.in/verilog_basic_examples.html[9/26/2012 2:54:49 PM]


WWW.TESTBENCH.IN

Verilog design

module mux21(
input a,b,sel,
output y);

    assign y = sel ?b:a;

endmodule

TestBench

module tb_mux21;

    reg A,B,SEL;
    wire Y;
    
    mux21 MUX (.a(A) ,.b(B),.sel(SEL),.y(Y));      
    
    initial begin
        A =1'b0;
        B= 1'b0;
        SEL =1'b0;
        #45 $finish;
    end
    
    always #6 A =~A;
    always #3 B =~B;
    always #5 SEL = ~SEL;
    
    always @(Y)
    $display( "time =%0t \tINPUT VALUES: \t A=%b B =%b SEL =%b \t output value Y =%b
",$time,A,B,SEL,Y);

endmodule

output

time =0    INPUT VALUES:         A=0 B =0 SEL =0         output value Y =0


time =5    INPUT VALUES:         A=0 B =1 SEL =1         output value Y =1
time =6    INPUT VALUES:         A=1 B =0 SEL =1         output value Y =0
time =9    INPUT VALUES:         A=1 B =1 SEL =1         output value Y =1

Multiplexer(4:1)
 

Verilog design

module mux41(
    input i0,i1,i2,i3,sel0,sel1,
    output reg y);
    
    always @(*)   //It includes all Inputs. You can use this instead of specifying all
inputs in //sensivity list.Verilog-2001 Feature
    begin
       case ({sel0,sel1})
       2'b00 : y = i0;
       2'b01 : y = i1;
       2'b10 : y = i2;
       2'b11 : y = i3;
       endcase
    end
    
endmodule

http://testbench.in/verilog_basic_examples.html[9/26/2012 2:54:49 PM]


WWW.TESTBENCH.IN

TestBench

module tb_mux41;

   reg I0,I1,I2,I3,SEL0,SEL1;
   wire Y;
  
   mux41 MUX (.i0(I0),.i1(I1),.i2(I2),.i3(I3),.sel0(SEL0),.sel1(SEL1),.y(Y));
  
   initial begin
       I0 =1'b0;
       I1= 1'b0;
       I2 =1'b0;
       I3 =1'b0;
       SEL0 =1'b0;
       SEL1 =1'b0;
       #45 $finish;
   end
  
   always #2 I0 = ~I0;
   always #4 I1 =~I1;
   always #6 I2 =~I1;
   always #8 I3 =~I1;
   always #3 SEL0 = ~SEL0;
   always #3 SEL1 = ~SEL1;
  
   always @(Y)
   $display( "time =%0t INPUT VALUES: \t I0=%b I1 =%b I2 =%b I3 =%b SEL0 =%b SEL1 =%b
\t output value Y =%b ",$time,I0,I1,I2,I3,SEL0,SEL1,Y);
  
endmodule

output

time =0 INPUT VALUES:    I0=0 I1 =0 I2 =0 I3 =0 SEL0 =0 SEL1 =0          output value Y =0


time =2 INPUT VALUES:    I0=1 I1 =0 I2 =0 I3 =0 SEL0 =0 SEL1 =0          output value Y =1
time =3 INPUT VALUES:    I0=1 I1 =0 I2 =0 I3 =0 SEL0 =1 SEL1 =1          output value Y =0
time =6 INPUT VALUES:    I0=1 I1 =1 I2 =0 I3 =0 SEL0 =0 SEL1 =0          output value Y =1
time =8 INPUT VALUES:    I0=0 I1 =0 I2 =0 I3 =0 SEL0 =0 SEL1 =0          output value Y =0
time =14 INPUT VALUES:   I0=1 I1 =1 I2 =1 I3 =0 SEL0 =0 SEL1 =0          output value Y
=1
time =15 INPUT VALUES:   I0=1 I1 =1 I2 =1 I3 =0 SEL0 =1 SEL1 =1          output value Y
=0

Encoder(8:3)
 

*Disadvantage of Encoder is that at a time only one Input is active.


*Output is zero for when all inputs are zero and when enable is zero

Verilog design

http://testbench.in/verilog_basic_examples.html[9/26/2012 2:54:49 PM]


WWW.TESTBENCH.IN

module encoder83(
input  en,
input  [7:0]in,
output reg [2:0]out);

   always@(*)
   begin
       if(!en) //Active low enable
           out = 0;
       else begin
           case ({in})
           8'b0000_0001 : out =3'b000;
           8'b0000_0010 : out =3'b001;
           8'b0000_0100 : out =3'b010;
           8'b0000_1000 : out =3'b011;
           8'b0001_0000 : out =3'b100;
           8'b0010_0000 : out =3'b101;
           8'b0100_0000 : out =3'b110;
           8'b1000_0000 : out =3'b110;
           default      : out =3'bxxx;
           endcase
       end
   end 

endmodule

TestBench using $random and Tasks

module tb_encoder83;

    reg en;
    reg  [7:0]in;
    wire [2:0] out;
    
    encoder83 ENC (.en(en),.in(in),.out(out));    
    
    initial begin
        en =0;
        in =0;
        repeat(10)
        random_generation(in,en);
        #45 $finish;
    end
    
    task random_generation;
    output [7:0]in_t;
    output en_t;
    begin
        #4;
        in_t = $random % 8;
        en_t =$random;
    end
    endtask
    
    
    task display;
    input en_t;
    input [7:0]in_t;
    input [2:0]out_t;
        $display("time =%0t \t INPUT VALUES \t en =%b in =%b \t OUTPUT VALUES out
=%b",$time,en_t,in_t,out_t);
    endtask
    
    always@(out)
       display(en,in,out);

endmodule

output

time =0          INPUT VALUES    en =0 in =00000000      OUTPUT VALUES out =000


time =4          INPUT VALUES    en =1 in =00000100      OUTPUT VALUES out =010

http://testbench.in/verilog_basic_examples.html[9/26/2012 2:54:49 PM]


WWW.TESTBENCH.IN

time =8          INPUT VALUES    en =1 in =11111001      OUTPUT VALUES out =xxx


time =16         INPUT VALUES    en =0 in =11111101      OUTPUT VALUES out =000
time =24         INPUT VALUES    en =1 in =00000110      OUTPUT VALUES out =xxx
time =28         INPUT VALUES    en =0 in =00000101      OUTPUT VALUES out =000
time =40         INPUT VALUES    en =1 in =00000101      OUTPUT VALUES out =xxx

Priority Encoder(8:3)

Priority Encoder overcomes all drawbacks of encoder.


* At a time more than one input can be active, Based on priority output will come.
* "v" is a valid Indicator, it become HIGH only when at least one input is active. You
can    differentiate the output when enable is zero and when only LSB (in0) is active

Verilog design

module priority_enco(
input en,
input [3:0]in,
output reg v,
output reg [1:0]out );

    integer i;
    
    always@(*) begin
       if(!en) begin
            out = 2'b00;
            v =1'b0;  
       end
       else
       begin :block1
           for (i=3; i>=0; i= i-1) begin
                //Priority Logic. each Time It will check Whether the MSB bit is active, If so
it will break //the loop. Otherwise It will decrement and continue the same
                if (in[i]==1'b1) begin
                case (i)
                     3: begin out = 2'b11; v= 1'b1; end
                     2: begin out = 2'b10; v= 1'b1; end
                     1: begin out = 2'b01; v= 1'b1; end
                     0: begin out = 2'b00; v= 1'b1; end
                    default :begin out = 2'bxx; v= 1'bx; end
                endcase
                
                disable block1;
                //Disable statement is synthesizible
                
                end  
           end
          
       end 
    end

endmodule

TestBench using $random and Tasks

module tb_prior_enco ;
    

http://testbench.in/verilog_basic_examples.html[9/26/2012 2:54:49 PM]


WWW.TESTBENCH.IN

    reg en;
    reg  [2:0]in;
    wire [1:0] out;
    wire v;
    
    priority_enco  PRIOR_ENC (.en(en),.in(in),.out(out),.v(v));
    
    initial begin
        en =0;
        in =0;
        repeat(19)
        random_generation(in,en);
        #65 $finish;
    end
    
    
    task random_generation;
    output [3:0]in_t;
    output en_t;
    begin
        #4;
        in_t = $random % 4;
        en_t =$random;
    end
    endtask
    
    task display;
    input en_t;
    input [3:0]in_t;
    input [1:0]out_t;
    input v_t;
    
        $display("time =%0t \t INPUT VALUES \t en =%b in =%b \t OUTPUT VALUES out =%b
v =%b",$time,en_t,in_t,out_t,v_t);
    
    endtask
    
    always@(out)
       display(en,in,out,v);
    
endmodule

output

time =0          INPUT VALUES    en =0 in =0000          OUTPUT VALUES out =00 v =0


time =8          INPUT VALUES    en =1 in =1101          OUTPUT VALUES out =11 v =1
time =12         INPUT VALUES    en =1 in =0001          OUTPUT VALUES out =00 v =1
time =24         INPUT VALUES    en =1 in =0010          OUTPUT VALUES out =01 v =1
time =28         INPUT VALUES    en =0 in =0001          OUTPUT VALUES out =00 v =0
time =44         INPUT VALUES    en =1 in =1110          OUTPUT VALUES out =11 v =1
time =48         INPUT VALUES    en =0 in =0010          OUTPUT VALUES out =00 v =0
time =60         INPUT VALUES    en =1 in =1101          OUTPUT VALUES out =11 v =1
time =64         INPUT VALUES    en =0 in =1111          OUTPUT VALUES out =00 v =0
time =72         INPUT VALUES    en =1 in =0010          OUTPUT VALUES out =01 v =1
time =76         INPUT VALUES    en =1 in =1110          OUTPUT VALUES out =11 v =1

Decoder(8:3)

http://testbench.in/verilog_basic_examples.html[9/26/2012 2:54:49 PM]


WWW.TESTBENCH.IN

Verilog design

module decoder38(
    input  en,
    input  [2:0]in,
    output  reg [7:0]out);
    
    always@(*)
    begin
       if(!en)
           out  = 0;
       else begin
           case ({in})      
           3'b000  :  out = 8'b0000_0001;
           3'b001  :  out = 8'b0000_0010;
           3'b010  :  out = 8'b0000_0100;
           3'b011  :  out = 8'b0000_1000;
           3'b100  :  out = 8'b0001_0000;
           3'b101  :  out = 8'b0010_0000;
           3'b110  :  out = 8'b0100_0000;
           3'b111  :  out = 8'b1000_0000;
           default :  out = 8'bxxxx_xxxx;
           endcase
       end
    end
    
endmodule

TestBench using $random and Tasks

module tb_decoder38;
    reg en_tb;
    reg  [2:0]in_tb;
    wire [7:0] out_d;
    reg  [7:0] out_tb;
    
    decoder38  DEC (.en(en_tb),.in(in_tb),.out(out_d));
    
    initial begin
       en_tb  =0;
       in_tb  =0;
       repeat(10)
       random_generation(in_tb,en_tb) ;
       #45 $finish;
    end
    
    //Below Block is used to generate expected outputs in Test bench only. These
outputs //are used to compare with DUT output. You have Checker task (ScoreBoard
in SV), for //that you need Reference output
    
    always@(in_tb,en_tb)
    begin
        if(!en_tb)
           out_tb   = 0;
        else begin
           case ({in_tb})
           3'b000  :  out_tb  = 8'b0000_0001;

http://testbench.in/verilog_basic_examples.html[9/26/2012 2:54:49 PM]


WWW.TESTBENCH.IN

           3'b001  :  out_tb  = 8'b0000_0010;
           3'b010  :  out_tb  = 8'b0000_0100;
           3'b011  :  out_tb  = 8'b0000_1000;
           3'b100  :  out_tb  = 8'b0001_0000;
           3'b101  :  out_tb  = 8'b0010_0000;
           3'b110  :  out_tb  = 8'b0100_0000;
           3'b111  :  out_tb  = 8'b1000_0000;
           default :  out_tb  = 8'bxxxx_xxxx;
           endcase
        end
    end
    
    
    task random_generation;
    output [2:0]in_t;
    output en_t;
    begin
        #4;
        in_t = $random % 3;
        en_t =$random;
    end
    endtask
    
    task checker;
    //In this block reference value and generated output are compared
    input [7:0]outd_t;
    input [7:0]outtb_t;
    begin
        if(outd_t === outtb_t)
            $display("time =%0t \t  DUT VALUE =%b TB VALUE =%b \tDUT and TB VALUES
ARE MATCHED ",$time,outd_t,outtb_t);
        else
            $display("time =%0t \tDUT and TB VALUES ARE NOT  MATCHED ",$time);
    end
    endtask
    
    always@(out_d,out_tb)
    checker(out_d,out_tb);

endmodule

TestBench using $random and Tasks

time =0   DUT VALUE =00000000 TB VALUE =00000000 DUT and TB VALUES ARE
MATCHED
time =4   DUT VALUE =00000100 TB VALUE =00000100 DUT and TB VALUES ARE
MATCHED
time =8   DUT VALUE =00000001 TB VALUE =00000001 DUT and TB VALUES ARE
MATCHED
time =16   DUT VALUE =00000000 TB VALUE =00000000 DUT and TB VALUES ARE
MATCHED
time =20   DUT VALUE =00000001 TB VALUE =00000001 DUT and TB VALUES ARE
MATCHED
time =28   DUT VALUE =00000000 TB VALUE =00000000 DUT and TB VALUES ARE
MATCHED
time =40   DUT VALUE =00000001 TB VALUE =00000001 DUT and TB VALUES ARE
MATCHED

D-Latch
 

Verilog design

module d_latch(
input en,d,
output reg q);

http://testbench.in/verilog_basic_examples.html[9/26/2012 2:54:49 PM]


WWW.TESTBENCH.IN

   always@(en,d)
   begin
      if(en)
      q <= d;
   end

endmodule

TestBench

module tb_latch;
    reg en,d;
    wire q;
    
    d_latch DLATCH (.en(en) ,.d(d) ,.q(q));
    
    initial begin
        en =1'b0;
        d =1'b1;
        #45 $finish;
    end
    
    always #6 en =~ en;
    always #3 d =~d;
    
    always@( q , en )
        $display("time =%0t \t INPUT VALUES \t en =%b d =%b \t OUTPUT VALUES
q=%b",$time,en,d,q);

endmodule

output

time =0     INPUT VALUES         en =0 d =1      OUTPUT VALUES q=x


time =6     INPUT VALUES         en =1 d =1      OUTPUT VALUES q=1
time =9     INPUT VALUES         en =1 d =0      OUTPUT VALUES q=0
time =12    INPUT VALUES         en =0 d =1      OUTPUT VALUES q=0
time =18    INPUT VALUES         en =1 d =1      OUTPUT VALUES q=0
time =18    INPUT VALUES         en =1 d =1      OUTPUT VALUES q=1
time =21    INPUT VALUES         en =1 d =0      OUTPUT VALUES q=0

D-FlipFlop(Asynchronous Reset)

Verilog design

module d_ff (
input clk,d,rst_n,
output reg q);

   //Here is reset is Asynchronous, You have include in sensitivity list


  
   always@(posedge clk ,negedge rst_n)
   begin
      if(!rst_n)
         q <= 1'b0;
      else
         q <= d;
   end

endmodule

TestBench

module tb_dff;

http://testbench.in/verilog_basic_examples.html[9/26/2012 2:54:49 PM]


WWW.TESTBENCH.IN

    reg RST_n, CLK,D;
    wire Q;
    
    d_ff DFF (.clk(CLK) ,.rst_n(RST_n) ,.q(Q),.d(D));
    
    initial begin
        RST_n = 1'b0;
        CLK =1'b0;
        D =1'b0;
        #5 RST_n = 1'b1;
        #13 RST_n = 1'b0;
        #7 RST_n = 1'b1;
        #45 $finish;
    end
    
    always #3 CLK = ~CLK;
    always #6 D = ~D;
    
    always @(posedge CLK ,negedge RST_n)
    $strobe("time =%0t \t INPUD VALUES \t D =%b RST_n =%b \t OUDPUD VALUES Q
=%d",$time,D,RST_n,Q);
    //$strobe will execute as a last statement in current simulation.

endmodule
 
output

time =0     INPUT VALUES         D =0 RST_n =0   OUTPUT VALUES Q =0


time =3     INPUT VALUES         D =0 RST_n =0   OUTPUT VALUES Q =0
time =9     INPUT VALUES         D =1 RST_n =1   OUTPUT VALUES Q =1
time =15    INPUT VALUES         D =0 RST_n =1   OUTPUT VALUES Q =0
time =18    INPUT VALUES         D =1 RST_n =0   OUTPUT VALUES Q =0
time =21    INPUT VALUES         D =1 RST_n =0   OUTPUT VALUES Q =0
time =27    INPUT VALUES         D =0 RST_n =1   OUTPUT VALUES Q =0
time =33    INPUT VALUES         D =1 RST_n =1   OUTPUT VALUES Q =1
time =39    INPUT VALUES         D =0 RST_n =1   OUTPUT VALUES Q =0

D-FlipFlop(Synchronous Reset)
 

Verilog design

module d_ff (
input clk,d,rst_n,
output reg q);
 
    //In Synchronous Reset, Reset condition is verified wrt to clk.Here It is verified at
every //posedge of clk.
    always@(posedge clk )
    begin
        if (!rst_n)
            q <= 1'b0;
        else
            q <= d;
    end
 
endmodule

TestBench

module tb_dff;
    reg RST_n, CLK,D;
    wire Q;
    
    d_ff DFF (.clk(CLK) ,.rst_n(RST_n) ,.q(Q),.d(D));
    

http://testbench.in/verilog_basic_examples.html[9/26/2012 2:54:49 PM]


WWW.TESTBENCH.IN

    initial begin
        RST_n = 1'b0;
        CLK =1'b0;
        D =1'b1;
        #5 RST_n = 1'b1;
        #7 RST_n = 1'b0;
        #7 RST_n = 1'b1;
        #45 $finish;
    end
    
    always #4 CLK = ~CLK;
    always #6 D = ~D;
    
    always @(posedge CLK )
    $strobe("time =%0t \t INPUT VALUES \t D =%b RST_n =%b \t OUDPUT VALUES Q
=%d",$time,D,RST_n,Q);

endmodule

output

time =4          INPUT VALUES    D =1 RST_n =0   OUTPUT VALUES Q =0


time =12         INPUT VALUES    D =1 RST_n =0   OUTPUT VALUES Q =0
time =20         INPUT VALUES    D =0 RST_n =1   OUTPUT VALUES Q =0
time =28         INPUT VALUES    D =1 RST_n =1   OUTPUT VALUES Q =1
time =36         INPUT VALUES    D =1 RST_n =1   OUTPUT VALUES Q =1
time =44         INPUT VALUES    D =0 RST_n =1   OUTPUT VALUES Q =0
time =52         INPUT VALUES    D =1 RST_n =1   OUTPUT VALUES Q =1
time =60         INPUT VALUES    D =1 RST_n =1   OUTPUT VALUES Q =1

T-FlipFlop
 

Verilog design

module t_ff (
input clk,t,rst_n,
output reg q);

    always@(posedge clk ,negedge rst_n)
    begin
        if (!rst_n)
            q <= 1'b0;
        else if(t)
            q <= ~q;
        else
            q <= q;
    end

endmodule

TestBench

module tb_tff;
    reg RST_n, CLK,T;
    wire Q;
    
    t_ff TFF (.clk(CLK) ,.rst_n(RST_n) ,.q( Q ),.t(T));
    
    initial begin
        RST_n = 1'b0;
        CLK =1'b0;
        T =1'b0;
        #5 RST_n = 1'b1;
        #13 RST_n = 1'b0;

http://testbench.in/verilog_basic_examples.html[9/26/2012 2:54:49 PM]


WWW.TESTBENCH.IN

        #7 RST_n = 1'b1;
        #45 $finish;
    end
    
    always #3 CLK = ~CLK;
    always #6 T = ~T;
    
    always @(posedge CLK ,negedge RST_n)
    $strobe("time =%0t \t INPUT VALUES \t T =%b RST_n =%b \t OUTPUT VALUES Q
=%d",$time,T,RST_n,Q);
 
endmodule

output

time =0     INPUT VALUES         T =0 RST_n =0   OUTPUT VALUES Q =0


time =3     INPUT VALUES         T =0 RST_n =0   OUTPUT VALUES Q =0
time =9     INPUT VALUES         T =1 RST_n =1   OUTPUT VALUES Q =1
time =15    INPUT VALUES         T =0 RST_n =1   OUTPUT VALUES Q =1
time =18    INPUT VALUES         T =1 RST_n =0   OUTPUT VALUES Q =0
time =21    INPUT VALUES         T =1 RST_n =0   OUTPUT VALUES Q =0
time =27    INPUT VALUES         T =0 RST_n =1   OUTPUT VALUES Q =0
time =33    INPUT VALUES         T =1 RST_n =1   OUTPUT VALUES Q =1

3-Bit Counter
 
//Used Structural Model in RTL and Behavior Model in Test bench

Verilog design

module t_ff(
output reg q,
input t, rst_n, clk);

always @ (posedge clk or negedge rst_n)
    if (!rst_n) q <= 1'b0;
    else if (t) q <= ~q;

endmodule

            //Standard counters are designed using either T or JK F/F.

module counter (
    output [2:0] q,
    input rst_n, clk);
    
    wire t2;
    
    t_ff ff0 ( q[0], 1'b1, rst_n, clk);
    t_ff ff1 ( q[1], q[0], rst_n, clk);
    t_ff ff2 ( q[2], t2,   rst_n, clk);
    and a1 (t2, q[0], q[1]);
    
endmodule

TestBench

module tb_counter_3bit;
    reg clk,rst_n;
    wire [2:0] q;
    reg [2:0] count;
    
    counter CNTR (.clk(clk),.rst_n(rst_n),.q(q));
    
    initial begin
        clk <= 1'b0;
        forever #5 clk <= ~ clk;
    end

    initial
    begin
         rst_n <= 0;

http://testbench.in/verilog_basic_examples.html[9/26/2012 2:54:49 PM]


WWW.TESTBENCH.IN

         @(posedge clk);
         @(negedge clk);
         rst_n <= 1;
         repeat (10)   @(posedge clk);
         $finish;
    end
    
    //Below always block represents the 3-bit counter in behavior style.
    //Here it is used to generate reference output
    always @(posedge clk or negedge rst_n) begin
         if (!rst_n) 
             count <= 0;
         else
             count <= (count + 1);
    end
    
    always @( q ) scoreboard(count);
    
    //Below task is used to compare reference and generated output. Similar to score
board //in SV Test bench
    
    task scoreboard;
    input [2:0]count;
    input [2:0] q;
    begin
       if (count == q)
           $display ("time =%4t q = %3b count = %b match!-:)",
                                  $time, q, count);
       else
           $display ("time =%4t q = %3b count = %b <-- no match",
                                 $time, q, count);
    end
    endtask

endmodule

output

time =   0 q = 000 count = 000 match!-:)


time =  15 q = 001 count = 001 match!-:)
time =  25 q = 010 count = 010 match!-:)
time =  35 q = 011 count = 011 match!-:)
time =  45 q = 100 count = 100 match!-:)
time =  55 q = 101 count = 101 match!-:)
time =  65 q = 110 count = 110 match!-:)
time =  75 q = 111 count = 111 match!-:)
time =  85 q = 000 count = 000 match!-:)
time =  95 q = 001 count = 001 match!-:)

17.  Gray code counter (3-bit) Using FSM.

It will have following sequence of states. It can be implemented without FSM also.

000
001
011
010
110
111
101
100

FSM Design IN VERILOG

 There are many ways of designing FSM.Most efficient are


 (i)Using Three always Block (ex: Gray code counter)
 (ii)Using Two always block (Ex: divide by 3 counter)

Verilog Code

module greycode_counter_3bit(
    input clk,rst_n,

http://testbench.in/verilog_basic_examples.html[9/26/2012 2:54:49 PM]


WWW.TESTBENCH.IN

    output reg [2:0]count);
    reg [2:0] pr_state,nx_state;
    
    parameter cnt0 =3'b000,
              cnt1 =3'b001,
              cnt2 =3'b011,
              cnt3 =3'b010,
              cnt4 =3'b110,
              cnt5 =3'b111,
              cnt6 =3'b101,
              cnt7 =3'b100;
    
    always@(posedge clk, negedge rst_n) begin // FIRST ALWAYS BLOCK
    //This always block is used for State assignment. Sequential always block.
    if(!rst_n)
        pr_state <= cnt0;
    else
        pr_state <=nx_state;
    end
    
    always@(pr_state) begin  //SECOND ALWAYS BLOCK
        //this always block used for next state logic, Combinational
        case (pr_state)
        cnt0 : nx_state = cnt1;
        cnt1 : nx_state = cnt2;
        cnt2 : nx_state = cnt3;
        cnt3 : nx_state = cnt4;
        cnt4 : nx_state = cnt5;
        cnt5 : nx_state = cnt6;
        cnt6 : nx_state = cnt7;
        cnt7 : nx_state = cnt0;
        default : nx_state = cnt0;
        endcase
    end
    
    always@(posedge clk ,negedge rst_n) begin //THIRD ALWAYS BLOCK
        //this always block used for output assignment,Sequential
        if(!rst_n)
            count <= 3'b000;
        else begin
            case (pr_state)
            cnt0 : count <= 3'b000;
            cnt1 : count <= 3'b001;
            cnt2 : count <= 3'b011;
            cnt3 : count <= 3'b010;
            cnt4 : count <= 3'b110;
            cnt5 : count <= 3'b111;
            cnt6 : count <= 3'b101;
            cnt7 : count <= 3'b100;
            default :count <=3'bxxx;
            endcase
        end
    end
endmodule

TestBench

module tb_greycode_counter;
    reg clk,rst_n;
    wire [2:0] count;
    
    greycode_counter_3bit COUNTER(.clk(clk),.rst_n(rst_n),.count(count));
    
    initial begin
        clk =1'b0;
        rst_n = 1'b0;
        @(posedge clk);
        @(posedge clk);
        rst_n = 1'b1;
        repeat(9) @(posedge clk);
        $finish;
    end
    
    always #5 clk = ~clk;

http://testbench.in/verilog_basic_examples.html[9/26/2012 2:54:49 PM]


WWW.TESTBENCH.IN

    always@(count)
    $display("time =%0t \t rst_n =%b count =%b",$time,rst_n,count);
    
endmodule

output

time =0          rst_n =0 count =000


time =25         rst_n =1 count =001
time =35         rst_n =1 count =011
time =45         rst_n =1 count =010
time =55         rst_n =1 count =110
time =65         rst_n =1 count =111
time =75         rst_n =1 count =101
time =85         rst_n =1 count =100
time =95         rst_n =1 count =000

Divide by 2 clk

module div_2clk(
input clk,rst_n,
output reg clk_out);

    always@(posedge clk,negedge rst_n) begin
    if(rst_n)
        clk_out <= 1'b0;
    else
        clk_out <= ~clk_out;
    end

endmodule

TestBench

module tb_div_2clk;
    reg clk,rst_n;
    wire clk_out;
    
    div2_clk clkby2 (.clk(clk),.rst_n(rst_n),.clk_out(clk_out));
    
    initial begin
        clk =1'b0;
        rst_n =1'b0;
        @(posedge clk);
        @(posedge clk);
        rst_n = 1'b1;
        
        repeat(15) @(posedge clk);
        //It will run till 15 clock cycles
        $finish;
    end
    
    always #5 clk = ~clk;
    always @(clk_out)
    $display("time = %0t \t Input  clk =%b \t output clk=%b ",$time,clk,clk_out);

endmodule

output
 

http://testbench.in/verilog_basic_examples.html[9/26/2012 2:54:49 PM]


WWW.TESTBENCH.IN

 
Divide by 3 clk

This is an example for two always block FSM


in this Example you have Two FSMs, one is operating at posedge clk and other
//operating at negedge clk. In Double Data Rate (DDR2) also data transfer occur at
both //the edges. It is synthesizable

Verilog Code

module div_3clk(
input clk,rst_n,
output clk_by_3);

    parameter ST10 =2'b00,
              ST11 =2'b01,
              ST12 = 2'b10;
    parameter ST20 =2'b00,
              ST21 =2'b01,
              ST22 = 2'b10;
    
    reg clk_temp1,clk_temp2;
    reg [1:0]  pr_state1,nx_state1;
    reg [1:0]  pr_state2,nx_state2;
    
    always@(posedge clk ,negedge rst_n) begin
        if(!rst_n)
            pr_state1 <= ST10;
        else
            pr_state1 <= nx_state1;
    end
    
    always @(pr_state1) begin
        //In second always block only we have output logic and next state logic
         case (pr_state1)
         ST10   : begin clk_temp1 = 1'b1; nx_state1 =ST11; end
         ST11   : begin clk_temp1 = 1'b0; nx_state1 =ST12; end
         ST12   : begin clk_temp1 = 1'b0; nx_state1 =ST10; end
        default : begin clk_temp1 = 1'bx; nx_state1 =ST10; end
        endcase

http://testbench.in/verilog_basic_examples.html[9/26/2012 2:54:49 PM]


WWW.TESTBENCH.IN

    end
    
    always@(negedge clk ,posedge rst_n) begin
        if(!rst_n)
            pr_state2 <= ST20;
        else
            pr_state2 <= nx_state2;
    end
    
    always @(pr_state2) begin
        case (pr_state2)
         ST20   : begin clk_temp2 = 1'b0; nx_state1 =ST21; end
         ST21   : begin clk_temp2 = 1'b0; nx_state1 =ST22; end
         ST22   : begin clk_temp2 = 1'b1; nx_state1 =ST20; end
        default : begin clk_temp2 = 1'bx; nx_state1 =ST20; end
        endcase
    end
    
    assign clk_divby3 = clk_temp1|| clk_temp1;

endmodule

TestBench

module tb_div_2clk;
    reg clk,rst_n;
    wire clk_out;
    
    div_3clk  clkby3 (.clk(clk),.rst_n(rst_n),.clk_by_3(clk_out));
    
    initial begin
        clk =1'b0;
        rst_n =1'b0;
        @(posedge clk);
        @(posedge clk);
        rst_n = 1'b1;
        repeat(15) @(posedge clk);
        $finish;
    end
    
    always #5 clk = ~clk;
    always @(clk_out)
    $display("time = %0t \t Input  clk =%b \t output clk=%b ",$time,clk,clk_out);

endmodule

output

http://testbench.in/verilog_basic_examples.html[9/26/2012 2:54:49 PM]


WWW.TESTBENCH.IN

              

copyright © 2007 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/verilog_basic_examples.html[9/26/2012 2:54:49 PM]


WWW.TESTBENCH.IN - Specman E

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS INTRODUCTION Index


Introduction
SystemVerilog E Basics
Verification The Specman automates verification processes, provides functional coverage analysis, Data Types
and raises the level of abstraction for functional coverage analysis from the RTL to the Operators
Constructs architectural/specification level. This means that you can: Struct
Interface Easily capture your design specifications to set up an accurate and appropriate Units
verification environment List
OOPS Methods
Quickly and effectively create as many tests as you need
Randomization Create self-checking modules that include protocols checking Concurrency Actions
Accurately identify when your verification cycle is complete Constraints
Functional Coverage Extend
Assertion The Specman Elite system provides three main enabling technologies that enhance When And Like
your productivity: Events
DPI Temporal Expressions
UVM Tutorial --Constraint-driven test generation : You control automatic test generation by Temporal Operators 1
capturing constraints from the interface specifications and the functional test plan. Temporal Operators 2
VMM Tutorial Synchronizing With The
Capturing the constraints is easy and straightforward.
OVM Tutorial Simulator
--Data and temporal checking : You can create self-checking modules that ensure Wait And Sync
Easy Labs : SV
data correctness and temporal conformance. For data checking, you can use a Physical Virual Feilds
Easy Labs : UVM reference model or a rule-based approach. Packing N Unpacking
Pre Run N On The Fly
Easy Labs : OVM
--Functional coverage analysis : You avoid creating redundant tests that waste Coverage
Easy Labs : VMM simulation cycles, because you can measure the progress of your verification effort Commands
AVM Switch TB against a functional test plan. Extendable Methods
Non Extendable Methods
VMM Ethernet sample And Gate Evc

Report a Bug or Comment


Verilog on This section - Your
input is what keeps
Verification
Testbench.in improving
Verilog Switch TB with time!
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/SP_01_INTRODUCTION.html[9/26/2012 2:54:59 PM]


WWW.TESTBENCH.IN - Specman E

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SP_01_INTRODUCTION.html[9/26/2012 2:54:59 PM]


WWW.TESTBENCH.IN - Specman E

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS E BASICS Index


Introduction
SystemVerilog Code Segments E Basics
Verification Data Types
A code segment is enclosed with a begin-code marker <' and an end-code marker '>. Operators
Constructs Both the begin-code and the end-code markers must be placed at the beginning of a Struct
Interface line (left most), with no other text on that same line (no code and no comments). For Units
example, the following three lines of code form a code segment: List
OOPS Methods
Randomization EXAMPLE Concurrency Actions
    <' Constraints
Functional Coverage Extend
          import eth_env;
Assertion     '> When And Like
Events
DPI Temporal Expressions
UVM Tutorial Several code segments can appear in one ï¬le. Each code segment consists of one or Temporal Operators 1
more statements. Temporal Operators 2
VMM Tutorial Synchronizing With The
OVM Tutorial Simulator
Comments Wait And Sync
Easy Labs : SV
Physical Virual Feilds
Easy Labs : UVM e ï¬les begin as a comment which ends when the ï¬rst begin-code marker <' is Packing N Unpacking
encountered. Pre Run N On The Fly
Easy Labs : OVM
Coverage
Easy Labs : VMM Comments within code segments can be marked with double dashes (--) or double Commands
AVM Switch TB slashes (//) Extendable Methods
Non Extendable Methods
VMM Ethernet sample The end-code '> and the begin-code <' markers can be used in the middle of code And Gate Evc
sections, to write several consecutive lines of comment:
Report a Bug or Comment
Verilog <' on This section - Your
    import eth_env; input is what keeps
Verification
'> Testbench.in improving
Verilog Switch TB with time!
Basic Constructs This is
several
consecutive
lines of comment
OpenVera
Constructs <'
Switch TB min = 46;
RVM Switch TB  -- This is an inline comment
RVM Ethernet sample
max = 1500;

 // This is also an inline comment


Specman E
Interview Questions '>

Literals And Constants

Literals are numeric, character and string values speciï¬ed literally in e. Operators
can be applied to literals to create compound expressions. The following categories of
literals and constants are supported in e:

------------------------------------------------------------

http://testbench.in/SP_02_E_BASICS.html[9/26/2012 2:55:08 PM]


WWW.TESTBENCH.IN - Specman E

Unsized Numbers                  12, 55_32, -764


Decimal integer                  10, 23_23 .-444  
Binary integer                   0b100111,  0b1100_0101
Hexadecimal integer              0x99_aa_bb_cc
Octal integer                    0o66_123
K (kilo: multiply by 1024)       32K, 32k, 128k
M (mega: multiply by 1024*1024)  1m, 4m, 4M
-------------------------------------------------------------

 
Sized Numbers

--------------------------------------------------------------
Binary      A leading 'b or 'B               8'b11001010
Octal       A leading 'o or 'O               6'o45
Decimal     A leading 'd or 'D               16'd63453
Hexadecimal A leading 'h or 'H or 'x or 'X   32'h12ffab04
--------------------------------------------------------------

Predeï¬Ned Constants

---------------------------------------------------------
Constant   Description
---------------------------------------------------------
TRUE       For Boolean variables and expressions.
FALSE      For Boolean variables and expressions.
NULL       For structs, speciï¬es a NULL pointer. For
           character strings, speciï¬es an empty string.
UNDEF      UNDEF indicates NONE where an index is expected.
MAX_INT    Represents the largest 32-bit int (231 -1)
MIN_INT    Represents the smallest 32-bit int (-231).
MAX_UINT   Represents the largest 32-bit uint (232-1).
--------------------------------------------------------

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/SP_02_E_BASICS.html[9/26/2012 2:55:08 PM]


WWW.TESTBENCH.IN - Specman E

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SP_02_E_BASICS.html[9/26/2012 2:55:08 PM]


WWW.TESTBENCH.IN - Specman E

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS DATA TYPES Index


Introduction
SystemVerilog E Basics
Verification Most e expressions have an explicit data type. These data types are described in the Data Types
following sections: Operators
Constructs Struct
Interface ----------------------------------------------------------------
Units
Name    Description                         Example List
OOPS ---------------------------------------------------------------- Methods
Randomization
bool    Boolean value: TRUE or FALSE       valid : bool; Concurrency Actions
int     Integer, default 32 bits                   length: int; Constraints
Functional Coverage uint    Unsigned integer,default 32 bits   addr  : uint(bits:8);
Extend
bit     1-bit unsigned integer                 valid : bit;
Assertion byte    8-bit unsigned integer             data  : byte; When And Like
time    64-bit unsigned integer            delay : time; Events
DPI string  String of ASCII characters         prompt: string; Temporal Expressions
list    Resizable                          payload:list of byte;
UVM Tutorial ---------------------------------------------------------------- Temporal Operators 1
Temporal Operators 2
VMM Tutorial Synchronizing With The
OVM Tutorial Simulator
Enumerated Types Wait And Sync
Easy Labs : SV
Physical Virual Feilds
Easy Labs : UVM You can define the valid values for a variable or field as a list of symbolic constants. Packing N Unpacking
These are referred to as enumerated types. Pre Run N On The Fly
Easy Labs : OVM
Coverage
Easy Labs : VMM Commands
Syntax: type enum-type: [name1[=exp],…][(bits|bytes: width-exp)];
AVM Switch TB Extendable Methods
Non Extendable Methods
VMM Ethernet sample And Gate Evc
EXAMPLE

type priority_t: [high, medium, low]; Report a Bug or Comment


Verilog type packet_kind_t: [good, bad]; on This section - Your
input is what keeps
Verification
Testbench.in improving
Verilog Switch TB By default, the new enumerated type is 32 bits, but it can be sized according to the with time!
Basic Constructs number of bits required.

EXAMPLE:
OpenVera
type direction_t: [READ, WRITE] (bits: 1);
Constructs
Switch TB Default first enum value is 0. Subsequent enum values are increment by 1.  This
internal value is used for comparisons(with strong type matching maintained).
RVM Switch TB Values can be explicitly assigned with the syntax:
RVM Ethernet sample
EXAMPLE:
type opcode_t: [ADD = 4, SUB = 6];
Specman E
Interview Questions

http://testbench.in/SP_03_DATA_TYPES.html[9/26/2012 2:55:17 PM]


WWW.TESTBENCH.IN - Specman E

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SP_03_DATA_TYPES.html[9/26/2012 2:55:17 PM]


WWW.TESTBENCH.IN - Specman E

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS OPERATORS Index


Introduction
SystemVerilog Unary Bitwise Operators E Basics
Verification Data Types
Operators
Constructs Unary bitwise negation( ~ ) operator Sets each 1 bit of an expression to 0 and each 0 Struct
Interface bits to 1. Each bit of the result expression is the opposite Units
of the same bit in the original expression. List
OOPS Methods
Randomization Concurrency Actions
EXAMPLE: Constraints
Functional Coverage Extend
<'
Assertion extend sys { When And Like
run() is also{ Events
DPI Temporal Expressions
    var x : int = 0x0000ff;
UVM Tutorial     print ~x using hex; Temporal Operators 1
}; Temporal Operators 2
VMM Tutorial Synchronizing With The
};
OVM Tutorial '> Simulator
RESULT Wait And Sync
Easy Labs : SV
Physical Virual Feilds
Easy Labs : UVM   ~x = 0xffffff00 Packing N Unpacking
Pre Run N On The Fly
Easy Labs : OVM
Coverage
Easy Labs : VMM Binary Bitwise Operations Commands
AVM Switch TB Extendable Methods
Non Extendable Methods
VMM Ethernet sample And Gate Evc
&  --  Performs an AND operation.
|  --  Performs an OR operation. Report a Bug or Comment
Verilog ^  --  Performs an XOR operation. on This section - Your
input is what keeps
Verification
Testbench.in improving
Verilog Switch TB with time!
Basic Constructs EXAMPLE:
<'
extend sys {
run() is also{
OpenVera   var x: uint = 0xff03;
Constructs     var y: uint = 0x70f6;
Switch TB    var z : uint;
    z  = x & y ;
RVM Switch TB     outf ( "%b & %b is %b \n",x,y,z);
RVM Ethernet sample     z  = x | y ;
    outf ( "%b | %b is %b \n",x,y,z);
    z  = x ^ y ;
    outf ( "%b ^ %b is %b \n",x,y,z);
Specman E   
Interview Questions
};
};
'>
RESULT:

1111111100000011 & 111000011110110 is 111000000000010


1111111100000011 | 111000011110110 is 1111111111110111
1111111100000011 ^ 111000011110110 is 1000111111110101

http://testbench.in/SP_04_OPERATORS.html[9/26/2012 2:55:24 PM]


WWW.TESTBENCH.IN - Specman E

Shift Operators

<<  --  Performs a shift-left operation.


>>  --  Performs a shift-right operation.

EXAMPLE
<'
extend sys {
run() is also{
  var x: int = 0x123456;
    outf("%x\n", x >> 2);
    var y: uint = 0x654321;
    outf("%x\n", y >> 3);

};
};
'>
RESULT

48d15
ca864

Boolean Operators

! (not)  -- Returns TRUE when an expression evaluates to FALSE, and vice


versa.
&& (and) -- Returns TRUE if two expressions are both TRUE.
|| (or)  -- Returns TRUE if one of two expressions is TRUE.
=>       -- Returns TRUE when the ï¬rst expression of two expressions
            is FALSE, or when both expressions are TRUE.
now      -- Returns TRUE if an event has occurred in the current cycle.

EXAMPLE
<'
extend sys {
run() is also{
  var x: int = 2;
  if(x > 1)
  { out(" (X > 1) ");};
  if((x > 1) && (x < 3))
  { out(" (x > 1) && (x < 3) "); };
if((x > 1) || (x < 3))
  { out(" (x > 1) || (x < 3) "); };
if((x > 1) => (x < 3))
  { out(" (x > 1) => (x < 3) "); };
if((x > 1) and (x < 3))

http://testbench.in/SP_04_OPERATORS.html[9/26/2012 2:55:24 PM]


WWW.TESTBENCH.IN - Specman E

  { out(" (x > 1) and (x < 3) "); };


if((x > 1) or (x < 3))
  { out(" (x > 1) or (x < 3) "); };

};
};
'>
RESULT

 (X > 1)
 (x > 1) && (x < 3)
 (x > 1) || (x < 3)
 (x > 1) => (x < 3)
 (x > 1) and (x < 3)
 (x > 1) or (x < 3)

Arithmetic Operators

+  -- Performs addition.


-  -- Performs subtraction.
*  -- Performs multiplication.
/  -- Performs division and returns the quotient, rounded down.
%  -- Performs division and returns the remainder.

EXAMPLE:
<'
extend sys {
run() is also{
out(1 + 4);
out(3 - 4);
out(41 * 3);
out(27 / 4);
out(53 % 7);
};
};
'>
RESULTS

5
-1
123
6
4

Comparison Operators

<   -- Returns TRUE if the ï¬rst expression is smaller than


       the second expression.
<=  -- Returns TRUE if the ï¬rst expression is not larger
       than the second expression.
>   -- Returns TRUE if the ï¬rst expression is larger than
       the second expression.
>=  -- Returns TRUE if the ï¬rst expression is not smaller
       than the second expression.
==  -- Returns TRUE if the ï¬rst expression evaluates to
       the same value as the second expression.
!=  -- Returns TRUE if the ï¬rst expression does not
       evaluate to the same value as the second expression.
=== -- Determines identity, as in Verilog. Returns TRUE if
       the left and right operands have identical values,
       considering also the x and z values.
!== -- Determines non-identity, as in Verilog. TRUE if the
       left and right operands differ in at least 1 bit,
       considering also the x and z values.
==  -- Returns TRUE if after translating all x values to 0
       and  all z values to 1, the left and right operands
       are equal.
!=  -- Returns TRUE if after translating all x values to 0
       and all z values to 1, the left and right operands
       are non-equal.
exp -- Either a literal with four-state values, a numeric
       expression, or another HDL pathname.

http://testbench.in/SP_04_OPERATORS.html[9/26/2012 2:55:24 PM]


WWW.TESTBENCH.IN - Specman E

~   -- Returns TRUE if the pattern string can be matched


       to the whole string.
!~  -- Returns TRUE if the pattern string cannot be
       matched to the whole string.
IN  -- Check for value in a list or specify a range for
       a constraint.

EXAMPLE
<'
extend sys {
run() is also{
out( 5 <   6);    
out( 5 <=  6);  
out( 5 >   6);  
out( 5 >=  6);  
out( 5 ==  6);  
out( 5 !=  6);  
out( 5 ==  6);  
out( 5 !=  6); 
out( "gg" ~ "gg" );
out( "gg" !~ "gg");
out( 5 in {4;5;6} ); 

};
};
'>

RESULT

TRUE
TRUE
FALSE
FALSE
FALSE
TRUE
FALSE
TRUE
TRUE
FALSE
TRUE

Extraction And Concatenation Operators

The following sections describe the e extraction and concatenation operators:

[ ]          -- Extracts or sets a single item from a list.


[ : ]        -- Extracts or sets consecutive bits or slices of
                a scalar, a list of bits, or a list of bytes.
[ .. ]       -- List slicing operator
[ range,...] -- Range list operator
{… ; …}      -- List concatenation
%{… , …}     -- Bit concatenation

Special-Purpose Operators

Specman Elite supports the following special purpose operators:

is [not] -- Identify the subtype of a struct instance


new      -- Allocate a new struct
.        -- Refer to ï¬elds in structs
'        -- Used in names of e entities
? :      -- Conditional operator

EXAMPLE:is[not]
<'
type pack_kind :[long, short];
struct packet {

http://testbench.in/SP_04_OPERATORS.html[9/26/2012 2:55:24 PM]


WWW.TESTBENCH.IN - Specman E

kind: pack_kind;
when long packet {
a: int;
};
check_my_type() is {
if me is a long packet (l) {
print l;
};
if me is not a long packet {
print kind;
};
};
};
extend sys {
p:packet;
run() is also {
p.check_my_type();
}
};
'>
RESULT

  l = packet-@0: packet


--------------------------------------------------@test
0       kind:                           long
1       long'a:                         2129590818

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SP_04_OPERATORS.html[9/26/2012 2:55:24 PM]


WWW.TESTBENCH.IN - Specman E

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS STRUCT Index


Introduction
SystemVerilog E Basics
Verification Structs are the basis building blocks for any e language based testbenches. This are Data Types
similar to class in C++ and thus are used for constructing compound data structures. Operators
Constructs Like in C++ and C, we can use this compound data structures in all the places like, it Struct
Interface Can be used as regular data types in any context where a type is required. The Units
default value for a struct is NULL . Struct can be passed to/from methods just as in C List
OOPS Methods
methods. Struct Can be used in another struct as normal data type . You can also
Randomization define a variable using a struct type. Concurrency Actions
Constraints
Functional Coverage Extend
Assertion EXAMPLE: When And Like
<' Events
DPI Temporal Expressions
struct data {
UVM Tutorial  addr : uint (bits : 32); Temporal Operators 1
 data : uint (bytes: 8); Temporal Operators 2
VMM Tutorial Synchronizing With The
 rdwr : bit;
OVM Tutorial }; Simulator
extend sys { Wait And Sync
Easy Labs : SV
d : data; Physical Virual Feilds
Easy Labs : UVM run() is also{ Packing N Unpacking
gen d; Pre Run N On The Fly
Easy Labs : OVM
print d; Coverage
Easy Labs : VMM gen d; Commands
AVM Switch TB print d; Extendable Methods
}; Non Extendable Methods
VMM Ethernet sample }; And Gate Evc
'>
Report a Bug or Comment
Verilog RESULT on This section - Your
input is what keeps
Verification
  d = data-@0: data Testbench.in improving
Verilog Switch TB                                                         @11 with time!
Basic Constructs 0       addr:                           1956082095
1       data:                           5743609808327112738
2       rdwr:                           0
  d = data-@1: data
OpenVera                                                         @11
Constructs 0       addr:                           3861093091
Switch TB 1       data:                           8956857106270623639
2       rdwr:                           0
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/SP_05_STRUCT.html[9/26/2012 2:55:33 PM]


WWW.TESTBENCH.IN - Specman E

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SP_05_STRUCT.html[9/26/2012 2:55:33 PM]


WWW.TESTBENCH.IN - Specman E

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS UNITS Index


Introduction
SystemVerilog E Basics
Verification Units are similar to structs. It also contain all struct members, i.e. fields, methods, Data Types
etc. Units are static. It is created during start of the simulation and stays until the Operators
Constructs end of simulation. Units are generated in Pre-run generation phase. We will task Struct
Interface about the generation phases in more detailed later. Units are associated with an HDL Units
hierarchy instance. Predefine method hdl_path() is used for setting the unit's List
OOPS Methods
associated HDL path. For accessing parent enclosing unit , predefined method
Randomization get_enclosing_unit() is used. Concurrency Actions
Constraints
Functional Coverage Extend
Assertion Syntax: unit unit-type [like base-unit-type] { [unit-member; ...]}; When And Like
Events
DPI Temporal Expressions
EXAMPLE:
UVM Tutorial unit XYZ_router { Temporal Operators 1
channels: list of XYZ_channel is instance; Temporal Operators 2
VMM Tutorial Synchronizing With The
keep channels.size() == 3;
OVM Tutorial keep for each in channels {.hdl_path() == Simulator
append("chan", index); }; Wait And Sync
Easy Labs : SV
}; Physical Virual Feilds
Easy Labs : UVM Packing N Unpacking
Units Vs Structs Pre Run N On The Fly
Easy Labs : OVM
Coverage
Easy Labs : VMM The decision of whether to model a DUT component with a unit or a struct often Commands
AVM Switch TB depends on your verification strategy. You intend to test the DUT component both Extendable Methods
standalone and integrated into a larger system. Modeling the DUT component with a Non Extendable Methods
VMM Ethernet sample unit instead of a struct allows you to use relative path names when referencing HDL And Gate Evc
objects. Your e program has methods that access many signals at runtime. The
correctness of all signal references within units are determined and checked during Report a Bug or Comment
Verilog pre-run generation. If your e program does not contain user units, the absolute HDL on This section - Your
references within structs are also checked during pre-run generation. However, if input is what keeps
Verification
your e program does contain user units, the relative HDL references within structs are Testbench.in improving
Verilog Switch TB checked at run time. In this case, using units rather than structs can enhance runtime with time!
Basic Constructs performance

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/SP_06_UNITS.html[9/26/2012 2:55:42 PM]


WWW.TESTBENCH.IN - Specman E

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SP_06_UNITS.html[9/26/2012 2:55:42 PM]


WWW.TESTBENCH.IN - Specman E

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS LIST Index


Introduction
SystemVerilog There are two of lists in e language E Basics
Verification -- Regular list Data Types
-- Keyed list Regular Operators
Constructs Struct
Interface Units
Regular List List
OOPS Methods
Randomization -List types hold ordered collections of data elements. Concurrency Actions
-All items in a list must be of the same type. Constraints
Functional Coverage Extend
-List elements can be of any type.
Assertion -Items in a list can be indexed with the subscript operator [ ], by placing a non- When And Like
negative integer expression in the    brackets.   Events
DPI Temporal Expressions
-List indexes start at zero. You can select an item from a list by specifying its index.
UVM Tutorial -Lists are dynamically resizable. Temporal Operators 1
-Lists contain many predefined methods. Temporal Operators 2
VMM Tutorial Synchronizing With The
-Lists are defined by using the list of keyword in a variable or a field definition.
OVM Tutorial Simulator
Wait And Sync
Easy Labs : SV
EXAMPLE: Physical Virual Feilds
Easy Labs : UVM lis : list of int; Packing N Unpacking
Pre Run N On The Fly
Easy Labs : OVM
Coverage
Easy Labs : VMM List Operations Commands
AVM Switch TB Extendable Methods
size() : This is used to set the size of the list. Non Extendable Methods
VMM Ethernet sample add(item or list) : Add an item to the end of a list And Gate Evc
add0(item or list) : Add an item to the head of a list
clear(): Delete all items from a list Report a Bug or Comment
Verilog delete(index) : Delete an item from a list on This section - Your
insert(index,item) : Insert an item in a list at a specified index input is what keeps
Verification
pop(item) : Remove and return the last list item Testbench.in improving
Verilog Switch TB pop0(item) : Remove and return the first list item with time!
Basic Constructs push(item) : Add an item to the end of a list
push0(item) : Add an item to the head of a list
resize() : Change the size of a list
OpenVera
Constructs
Switch TB EXAMPLE:
<'
RVM Switch TB extend sys {
RVM Ethernet sample run() is also {
var a_list: list of int = {1;2;3;4};
var b_list: list of int = {5;5};
print a_list;
Specman E print a_list.pop();
Interview Questions a_list.add(9);
print a_list;
a_list.insert(2,33); 
print a_list;
a_list.add(b_list); 
print a_list;
a_list.delete(4);
print a_list;
a_list.add0(22);
print a_list;
print a_list.pop0();

http://testbench.in/SP_07_LIST.html[9/26/2012 2:55:52 PM]


WWW.TESTBENCH.IN - Specman E

a_list.push(44);
print a_list;
a_list.push0(55); 
print a_list;
a_list.resize(4);
print a_list;
a_list.clear();
print a_list;
}
};
'>
RESULT:

  a_list =
0.      1
1.      2
2.      3
3.      4
  a_list.pop() = 4
  a_list =
0.      1
1.      2
2.      3
3.      9
  a_list =
0.      1
1.      2
2.      33
3.      3
4.      9
  a_list =
0.      1
1.      2
2.      33
3.      3
4.      9
5.      5
6.      5
  a_list =
0.      1
1.      2
2.      33
3.      3
4.      5
5.      5
  a_list =
0.      22
1.      1
2.      2
3.      33
4.      3
5.      5
6.      5

http://testbench.in/SP_07_LIST.html[9/26/2012 2:55:52 PM]


WWW.TESTBENCH.IN - Specman E

  a_list.pop0() = 22
  a_list =
0.      1
1.      2
2.      33
3.      3
4.      5
5.      5
6.      44
  a_list =
0.      55
1.      1
2.      2
3.      33
4.      3
5.      5
6.      5
7.      44
  a_list =
0.      0
1.      0
2.      0
3.      0
  a_list = (empty)

Keyed List:

A keyed list data type is similar to hash tables or association lists found in other
programming languages. If the element type of the list is a scalar type or a string
type, then the hash key must be the predefined implicit variable it.

A keyed list is a distinct type, different from a regular list. This means that you
cannot assign a keyed list to a regular list, nor assign a regular list to a keyed list: if
list_a is a keyed list and list_b is a regular list, list_a = list_b is a syntax error.

EXAMPLE:
<'
extend sys {
!a: list(key: it) of int(bits: 3);
run() is also {
var b: int(bits: 4);
for i from 0 to 10 {
gen b;
a.add(b);
};
if a.key_exists(2) then {
print a;
print a.key_index(4);
};
};
};
'>

RESULT:

a =  (11 items, dec):


-3 -3 -2   1 -2  2 -1   0 -4  0 -3      .0
a.key_index(4) = 2

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/SP_07_LIST.html[9/26/2012 2:55:52 PM]


WWW.TESTBENCH.IN - Specman E

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SP_07_LIST.html[9/26/2012 2:55:52 PM]


WWW.TESTBENCH.IN - Specman E

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS METHODS Index


Introduction
SystemVerilog e methods are similar to C functions, Verilog tasks, and VHDL processes. E Basics
Verification Methods can contain actions (procedural code). User can declare and use local Data Types
variables and parameters. Methods can have zero to fourteen input Operators
Constructs arguments/parameters. You can work around this restriction by passing a compound Struct
Interface parameter such as a struct or a list. It can aslo optionally return a value . Units
List
OOPS Methods
Randomization EXAMPLE: Concurrency Actions
<' Constraints
Functional Coverage Extend
struct A {my_type() is {out("I am type A")}};
Assertion extend sys { When And Like
a: A; Events
DPI Temporal Expressions
run() is also {
UVM Tutorial a.my_type(); Temporal Operators 1
}; Temporal Operators 2
VMM Tutorial Synchronizing With The
};
OVM Tutorial '> Simulator
Wait And Sync
Easy Labs : SV
RESULT: Physical Virual Feilds
Easy Labs : UVM Packing N Unpacking
I am type A Pre Run N On The Fly
Easy Labs : OVM
Coverage
Easy Labs : VMM Commands
AVM Switch TB Extendable Methods
Time-Consuming Methods(Tcms) Non Extendable Methods
VMM Ethernet sample And Gate Evc
A TCM is a time-consuming method that is distinguished from a regular method by the
presence of @event and can use time-consuming actions such as sync and wait. Report a Bug or Comment
Verilog on This section - Your
EXAMPLE: input is what keeps
Verification
<' Testbench.in improving
Verilog Switch TB struct data_drive { with time!
Basic Constructs event clk is rise('top.clk') @sim;
data: list of int;
driver() @clk is {
for each in data {
OpenVera wait true('top.data_ready'== 1);
Constructs // Will not fall through, even if the condition
Switch TB // holds when the wait is reached.
'top.in_reg' = it;
RVM Switch TB };
RVM Ethernet sample stop_run();
};
shadow() @clk is {
while TRUE {
Specman E sync true('top.data_ready' == 0);
Interview Questions // If the condition holds, the sync falls through.
out("Shadow read ", 'top.in_reg');
wait cycle;
// This wait is necessary to prevent
// an infinite loop.
};
};
run() is also {
start driver();
start shadow();
};

http://testbench.in/SP_08_METHODS.html[9/26/2012 2:56:02 PM]


WWW.TESTBENCH.IN - Specman E

};
'>

Invoking Tcms:

start tcm() Syntax start [[struct-exp].]method-name([parameter-list])

A start action can be used within another method, either a TCM or a regular method.
A started TCM begins execution either when its sampling event occurs or immediately,
if the sampling event has already occurred for the current Specman tick.A started
TCM runs in parallel with the TCM that started it on a separate thread. Notes. A TCM
that has a return value cannot be started with a start action.. You cannot start a TCM
before the run phase begins or after the check phase begins.

EXAMPLE:
<'
struct meth {
event clk is rise('top.clk');
run() is also {
out("Starting main…");
start main();
};
};
'>

Execution Flow

Specman Elite provides a predetermined execution flow composed of “test phasesâ


€.
  
Each test phase is called in a specific order.
Each test phase is represented by a predefined method.
Most predefined methods are meant to be extended.
Extend a predefined method to call your method(s) at the appropriate time.

---------------------
Execution Phases
---------------------
--Initialization
--Pre-run generation
--Simulation run
--Post-run check
--Finalization
---------------------

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/SP_08_METHODS.html[9/26/2012 2:56:02 PM]


WWW.TESTBENCH.IN - Specman E

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SP_08_METHODS.html[9/26/2012 2:56:02 PM]


WWW.TESTBENCH.IN - Specman E

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS CONCURRENCY ACTIONS Index


Introduction
SystemVerilog All Of E Basics
Verification Data Types
Execute multiple action blocks concurrently, as separate branches of a fork. The Operators
Constructs action following the all of action will be reached only when all branches of the all of Struct
Interface have been fully executed. All branches of the fork are automatically joined at the Units
termination of the all of action block. List
OOPS Methods
Randomization Concurrency Actions
First Of Constraints
Functional Coverage Extend
Assertion Execute multiple action blocks concurrently, as separate branches of a fork. The When And Like
action following the first of action will be reached when any of the branches in the Events
DPI Temporal Expressions
first of has been fully executed. All branches of the fork are automatically joined at
UVM Tutorial the termination of the first of action block. Temporal Operators 1
Temporal Operators 2
VMM Tutorial Synchronizing With The
OVM Tutorial Simulator
Wait And Sync
Easy Labs : SV
Physical Virual Feilds
Easy Labs : UVM Packing N Unpacking
Pre Run N On The Fly
Easy Labs : OVM
Coverage
Easy Labs : VMM Commands
AVM Switch TB Extendable Methods
Non Extendable Methods
VMM Ethernet sample And Gate Evc

Report a Bug or Comment


Verilog on This section - Your
input is what keeps
Verification
Testbench.in improving
Verilog Switch TB with time!
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/SP_09_Concurrency_Actions.html[9/26/2012 2:56:09 PM]


WWW.TESTBENCH.IN - Specman E

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SP_09_Concurrency_Actions.html[9/26/2012 2:56:09 PM]


WWW.TESTBENCH.IN - Specman E

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS CONSTRAINTS Index


Introduction
SystemVerilog ConstraintsConstraints are directives that influence the behavior of the Specman test E Basics
Verification generator. They are declared within a struct and influence the generation of values Data Types
for data items within the struct and its subtree. Operators
Constructs Struct
Interface 1. Hard Constraints Units
2. Soft Constraints List
OOPS Methods
Randomization For constraints that might need to be overridden, we use soft constraints. Soft Concurrency Actions
constraints are obeyed if not contradicted by hard constraints. The last loaded soft Constraints
Functional Coverage Extend
constraint prevails if there is a contradiction with other soft constraints. Soft
Assertion constraints are used to define the default range of values of fields. Soft constraints When And Like
are used to set initial settings for tests. Events
DPI Temporal Expressions
UVM Tutorial Temporal Operators 1
EXAMPLE: Temporal Operators 2
VMM Tutorial Synchronizing With The
keep kind != tx or len == 16;
OVM Tutorial Simulator
Wait And Sync
Easy Labs : SV
Physical Virual Feilds
Easy Labs : UVM Packing N Unpacking
Pre Run N On The Fly
Easy Labs : OVM
Coverage
Easy Labs : VMM Commands
AVM Switch TB Extendable Methods
Non Extendable Methods
VMM Ethernet sample And Gate Evc

Report a Bug or Comment


Verilog on This section - Your
input is what keeps
Verification
Testbench.in improving
Verilog Switch TB with time!
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/SP_10_CONSTRAINTS.html[9/26/2012 2:56:18 PM]


WWW.TESTBENCH.IN - Specman E

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SP_10_CONSTRAINTS.html[9/26/2012 2:56:18 PM]


WWW.TESTBENCH.IN - Specman E

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS EXTEND Index


Introduction
SystemVerilog Is Also E Basics
Verification Data Types
"is also" is used for extending existing method/TCM. When we use "is also" it adds new Operators
Constructs lines of code/functionality after the existing code as shown in below example. Struct
Interface Units
List
OOPS Methods
EXAMPLE:
Randomization <' Concurrency Actions
Constraints
Functional Coverage Extend
struct exam { 
Assertion from_exam() is {  When And Like
  out ( "This is BASE" );  Events
DPI Temporal Expressions
};
UVM Tutorial Temporal Operators 1
}; Temporal Operators 2
VMM Tutorial Synchronizing With The
OVM Tutorial struct e_exam like exam{   Simulator
from_exam() is also { Wait And Sync
Easy Labs : SV
 out( "This is EXTENDED" );   Physical Virual Feilds
Easy Labs : UVM Packing N Unpacking
}; Pre Run N On The Fly
Easy Labs : OVM
Coverage
Easy Labs : VMM }; Commands
AVM Switch TB Extendable Methods
extend sys {  Non Extendable Methods
VMM Ethernet sample  exam : exam;   And Gate Evc
 e_exam : e_exam;  
run() is also {   Report a Bug or Comment
Verilog  exam.from_exam();  on This section - Your
 e_exam.from_exam();  input is what keeps
Verification
 }; Testbench.in improving
Verilog Switch TB with time!
Basic Constructs };
'>

OpenVera RESULT:
Constructs
Switch TB This is BASE
This is BASE
RVM Switch TB This is EXTENDED
RVM Ethernet sample

Is First
Specman E
Interview Questions "is first" is used for extending existing method/TCM. When we use "is first" it adds new
lines of code/functionality before existing code shown in below example.

EXAMPLE:
<'

struct exam { 
from_exam() is { 
  out ( "This is BASE" ); 
};

http://testbench.in/SP_11_EXTEND.html[9/26/2012 2:56:27 PM]


WWW.TESTBENCH.IN - Specman E

};

struct e_exam like exam{  


from_exam() is first {
 out( "This is EXTENDED" );  

};

};

extend sys { 
 exam : exam;  
 e_exam : e_exam;  
run() is also {  
 exam.from_exam(); 
 e_exam.from_exam(); 
 };

};
'>

RESULT

This is BASE
This is EXTENDED
This is BASE

Is Only

"is only"  is used for over riding existing method/TCM. When we use "is only" it over
rides the existing code/functionality before existing code and replaces with new code
as shown in below example.

EXAMPLE:
<'

struct exam { 
from_exam() is { 
  out ( "This is BASE" ); 
};

};

struct e_exam like exam{  


from_exam() is only {
 out( "This is EXTENDED" );  

};

http://testbench.in/SP_11_EXTEND.html[9/26/2012 2:56:27 PM]


WWW.TESTBENCH.IN - Specman E

};

extend sys { 
 exam : exam;  
 e_exam : e_exam;  
run() is also {  
 exam.from_exam(); 
 e_exam.from_exam(); 
 };

};
'>

RESULT:

This is BASE
This is EXTENDED

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SP_11_EXTEND.html[9/26/2012 2:56:27 PM]


WWW.TESTBENCH.IN - Specman E

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS WHEN AND LIKE Index


Introduction
SystemVerilog There are two ways to implement object-oriented inheritance in e: like inheritance E Basics
Verification and when inheritance   Data Types
Operators
Constructs Struct
Interface Like Units
List
OOPS
Like inheritance is the classical, single inheritance familiar to users of all object- Methods
Randomization oriented languages and is specified with the like clause in new struct definitions. Concurrency Actions
Constraints
Functional Coverage Extend
Assertion When And Like
EXAMPLE: Events
DPI Temporal Expressions
<'
UVM Tutorial Temporal Operators 1
struct exam {  Temporal Operators 2
VMM Tutorial Synchronizing With The
from_exam() is { 
OVM Tutorial   out ( "This is BASE" );  Simulator
}; Wait And Sync
Easy Labs : SV
Physical Virual Feilds
Easy Labs : UVM }; Packing N Unpacking
Pre Run N On The Fly
Easy Labs : OVM
struct e_exam like exam{   Coverage
Easy Labs : VMM from_exam() is only { Commands
AVM Switch TB  out( "This is EXTENDED" );   Extendable Methods
Non Extendable Methods
VMM Ethernet sample }; And Gate Evc

}; Report a Bug or Comment


Verilog on This section - Your
extend sys {  input is what keeps
Verification
 exam : exam;   Testbench.in improving
Verilog Switch TB  e_exam : e_exam;   with time!
Basic Constructs run() is also {  
 exam.from_exam(); 
 e_exam.from_exam(); 
 };
OpenVera
Constructs };
Switch TB '>
RVM Switch TB
RVM Ethernet sample RESULT:
This is BASE
This is EXTENDED
Specman E
Interview Questions

When

When inheritance is a concept unique to e and is specified by defining subtypes with


when struct members. When inheritance provides the following advantages
compared    to like inheritance:    
-Ability to have explicit reference to the when fields
-Ability to have multiple, orthogonal subtypes  
-Ability to extend the struct later

http://testbench.in/SP_12_When_and_Like.html[9/26/2012 2:56:37 PM]


WWW.TESTBENCH.IN - Specman E

EXAMPLE:when
<'
type pack_kind :[long, short];
struct packet {
kind: pack_kind;
when long packet {
a: int;
};
check_my_type() is {
if me is a long packet (l) {
print l;
};
if me is not a long packet {
print kind;
};
};
};
extend sys {
p:packet;
run() is also {
p.check_my_type();
}
};
'>
RESULT

  l = packet-@0: packet


--------------------------------------------------@test
0       kind:                           long
1       long'a:                         2129590818

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SP_12_When_and_Like.html[9/26/2012 2:56:37 PM]


WWW.TESTBENCH.IN - Specman E

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS EVENTS Index


Introduction
SystemVerilog The e language provides temporal constructs for specifying and verifying behavior E Basics
Verification over time. All e temporal language features depend on the occurrence of events, Data Types
which are used to synchronize activity with a simulator and within Specman. Operators
Constructs Struct
Interface Defining and Emitting Named Events Units
List
OOPS Methods
event  Syntax   event event-type[is [only] temporal-expression]  
Randomization Concurrency Actions
EXAMPLE: Constraints
Functional Coverage Extend
expect {[1]; true(chk)@rclk};
Assertion on rclk { ... }; When And Like
set_chk()@rclk is { ... }; Events
DPI Temporal Expressions
UVM Tutorial Temporal Operators 1
Temporal Operators 2
VMM Tutorial Synchronizing With The
OVM Tutorial Simulator
Wait And Sync
Easy Labs : SV
Physical Virual Feilds
Easy Labs : UVM Packing N Unpacking
Pre Run N On The Fly
Easy Labs : OVM
Coverage
Easy Labs : VMM Commands
AVM Switch TB Extendable Methods
Non Extendable Methods
VMM Ethernet sample And Gate Evc

Report a Bug or Comment


Verilog on This section - Your
input is what keeps
Verification
Testbench.in improving
Verilog Switch TB with time!
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/SP_13_EVENTS.html[9/26/2012 2:56:44 PM]


WWW.TESTBENCH.IN - Specman E

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SP_13_EVENTS.html[9/26/2012 2:56:44 PM]


WWW.TESTBENCH.IN - Specman E

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS TEMPORAL EXPRESSIONS Index


Introduction
SystemVerilog Temporal expressions provide a declarative way to describe temporal behavior. The e E Basics
Verification language provides a set of temporal operators and keywords that can be use to Data Types
construct temporal expressions. Every temporal expression has a default clock, called Operators
Constructs its sampling event .The temporal language is the basis for capturing behavior over Struct
Interface time for: Units
List
OOPS Methods
--Synchronizing with the DUT
Randomization --Debugging                       Concurrency Actions
--Protocol checking Constraints
Functional Coverage Extend
--Functional coverage      
Assertion When And Like
The language is built of: Events
DPI Temporal Expressions
--Temporal expressions (TEs).
UVM Tutorial --Temporal operators, for defining complex expressions. Temporal Operators 1
--Event struct members, for defining occurrences of events during the run. Temporal Operators 2
VMM Tutorial Synchronizing With The
--Expect struct members, for checking temporal behavio
OVM Tutorial Simulator
Wait And Sync
Easy Labs : SV
Basic Temporal Expressions Physical Virual Feilds
Easy Labs : UVM Packing N Unpacking
Each TE is associated with a sampling event that indicates when the TE should be Pre Run N On The Fly
Easy Labs : OVM
evaluated by Specman Elite. Coverage
Easy Labs : VMM Commands
AVM Switch TB -------------------------------------------------------------------
Extendable Methods
----- Non Extendable Methods
VMM Ethernet sample Temporal Expression                 Sampling Event And Gate Evc
-------------------------------------------------------------------
-----
true(boolean-exp)@sample-event      Every sample-event at which boolean Report a Bug or Comment
Verilog                                     exp is true on This section - Your
rise/fall/change(exp)@sample event  Every sample-event at which exp had input is what keeps
Verification                                     risen/fallen/changed since previous Testbench.in improving
Verilog Switch TB                                     sample-event
cycle @sample-event                 Every sample-event with time!
Basic Constructs [num] * TE                          Above TEs repeated num times
-------------------------------------------------------------------
----

OpenVera
Constructs
Switch TB Temporal Checking
RVM Switch TB
1. The temporal expressions we saw for defining events and using in wait actions in
RVM Ethernet sample
TCMs can also be used for checking behavior through time.
2. The struct member expect spawns a thread that reports an error if a temporal
expression does not succeed.
Specman E
Interview Questions

http://testbench.in/SP_14_TEMPORAL_EXPRESSIONS.html[9/26/2012 2:56:58 PM]


WWW.TESTBENCH.IN - Specman E

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SP_14_TEMPORAL_EXPRESSIONS.html[9/26/2012 2:56:58 PM]


WWW.TESTBENCH.IN - Specman E

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS TEMPORAL OPERATORS 1 Index


Introduction
SystemVerilog Not E Basics
Verification Data Types
The not temporal expression succeeds if the evaluation of the subexpression does not Operators
Constructs succeed during the sampling period. Thus not TE succeeds on every occurrence of the Struct
Interface sampling event if TE does not succeed. Units
List
OOPS Methods
Randomization Fail Concurrency Actions
Constraints
Functional Coverage Extend
A fail succeeds whenever the temporal expression fails. If the temporal expression has
Assertion multiple interpretations (for example, fail (TE1 or TE2)), the expression succeeds if When And Like
and only if all the interpretations fail. The expression fail TE succeeds at the point Events
DPI Temporal Expressions
where all possibilities to satisfy TE have been exhausted. Any TE can fail at most once
UVM Tutorial per sampling event. Temporal Operators 1
Temporal Operators 2
VMM Tutorial Synchronizing With The
OVM Tutorial And Simulator
Wait And Sync
Easy Labs : SV
The temporal and succeeds when both temporal expressions start evaluating in the Physical Virual Feilds
Easy Labs : UVM same sampling period, and succeed in the same sampling period. Packing N Unpacking
Pre Run N On The Fly
Easy Labs : OVM
Coverage
Easy Labs : VMM Or Commands
AVM Switch TB Extendable Methods
The or temporal expression succeeds when either temporal expression succeeds. An or Non Extendable Methods
VMM Ethernet sample operator creates a parallel evaluation for each of its subexpressions. It can create And Gate Evc
multiple successes for a single temporal expression evaluation.
Report a Bug or Comment
Verilog on This section - Your
input is what keeps
Verification
{ Exp ; Exp } Testbench.in improving
Verilog Switch TB with time!
Basic Constructs The semicolon (;) sequence operator evaluates a series of temporal expressions over
successive occurrences of a specified sampling event. Each temporal expression
following a “;†starts evaluating in the sampling period following that in which
the preceding temporal expression succeeded. The sequence succeeds whenever its
OpenVera final expression succeeds.
Constructs
Switch TB
Eventually
RVM Switch TB
RVM Ethernet sample Used to indicate that the temporal expression should succeed at some unspecified
time. Typically, eventually is used in an expect struct member to specify that a
temporal expression is expected to succeed sometime before the quit event occurs
for the struct.
Specman E
Interview Questions
[ Exp ]

Repetition of a temporal expression is frequently used to describe cyclic or periodic


temporal behavior. The [exp] fixed repeat operator specifies a fixed number of
occurrences of the same temporal expression. If the numeric expression evaluates to
zero, the temporal expression succeeds immediately.

[ Exp..Exp ]

http://testbench.in/SP_15_Temporal_operators_1.html[9/26/2012 2:57:07 PM]


WWW.TESTBENCH.IN - Specman E

The first match repeat operator is only valid in a temporal sequence {TE; TE; TE}. The
first match repeat expression succeeds on the first success of the match-expression
between the lower and upper bounds specified for the repeat-expression. First match
repeat also enables specification of behavior over infinite sequences by allowing an
infinite number of repetitions of the repeat-expression to occur before the match-
expression succeeds.
Where @ev_a is an event occurrence, {[..]*TE1;@ev_a} is equivalent to:
 {@ev_a} or {[1]*TE1; @ev_a} or {[2]*TE1; @ev_a} or {[3]*TE1; @ev_a}…

~[ Exp..Exp ]

You can use the true match repeat operator to specify a variable number of
consecutive successes of a temporal expression.True match variable repeat succeeds
every time the subexpression succeeds. This expression creates a number of parallel
repeat evaluations within the range. True match repeat also enables specification of
behavior over infinite sequences by repeating an infinite number of occurrences of a
temporal expression. The expression ~[..]*TE is equivalent to:
 [0] or [1]*TE or [2]*TE

Temporal Yield Operator

=>
The yield operator is used to assert that success of one temporal expression depends
on the success of another temporal expression. The yield expression TE1 => TE2 is
equivalent to (fail TE1) or {TE1 ; TE2}.The yield expression succeeds without
evaluating the second expression if the first expression fails. If
the first expression succeeds, then the second expression must succeed in sequence.
Yield is typically used in conjunction with the expect struct member to express
temporal rules. The sampling event from the context applies to both sides of the yield
operator expression. The entire expression is essentially a single temporal expression,
so that (TE1 => TE2)@sampling_event is effectively (TE)@sampling_event where TE is
the temporal expression made up of TE1 => TE2.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SP_15_Temporal_operators_1.html[9/26/2012 2:57:07 PM]


WWW.TESTBENCH.IN - Specman E

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS TEMPORAL OPERATORS 2 Index


Detach Introduction
SystemVerilog E Basics
Verification A detached temporal expression is evaluated independently of the expression in which Data Types
it is used. It starts evaluation when the main expression does. Whenever the detached Operators
Constructs TE succeeds it emits an “implicit†event which will only be recognized by the Struct
Interface main TE. The detached temporal expression inherits the sampling event from the Units
main temporal expression. List
OOPS Methods
Randomization Concurrency Actions
Delay Constraints
Functional Coverage Extend
Assertion Succeeds after a specified simulation time delay elapses. A callback to Specman Elite When And Like
occurs after the specified time. A delay of zero succeeds immediately. Events
DPI Temporal Expressions
Attaching a sampling event to delay has no effect. The delay ignores the sampling
UVM Tutorial event and succeeds as soon as the delay period elapses. Temporal Operators 1
Temporal Operators 2
VMM Tutorial Synchronizing With The
OVM Tutorial @ Unary Event Operator Simulator
Wait And Sync
Easy Labs : SV
An event can be used as the simplest form of a temporal expression. The temporal Physical Virual Feilds
Easy Labs : UVM expression @event-type succeeds every time the event occurs. Success of the Packing N Unpacking
expression is simultaneous with the occurrence of the event. The struct-exp is an Pre Run N On The Fly
Easy Labs : OVM
expression that evaluates to the struct instance that contains the event instance. If Coverage
Easy Labs : VMM no struct expression is specified, the default is the current struct instance. Commands
AVM Switch TB Extendable Methods
Non Extendable Methods
VMM Ethernet sample @ Sampling Operator And Gate Evc

Used to specify the sampling event for a temporal expression. The specified sampling Report a Bug or Comment
Verilog event overrides the default sampling event. Every temporal expression has a sampling on This section - Your
event. The sampling event applies to all subexpressions of the temporal expression. It input is what keeps
Verification
can be overridden for a subexpression by attaching a different sampling event to the Testbench.in improving
Verilog Switch TB subexpression. A sampled temporal expression succeeds when its sampling event with time!
Basic Constructs occurs with or after the success of the temporal expression.

Cycle
OpenVera
Constructs Represents one cycle of some sampling event.With no explicit sampling event
Switch TB specified, this represents one cycle of the default sampling event. With a sampling
event specified, cycle is equivalent to @sys.any@sampling-event.
RVM Switch TB
RVM Ethernet sample
True(Exp)

Use a Boolean expression as a temporal expression. Each occurrence of the sampling


Specman E event causes an evaluation of the Boolean expression. The Boolean expression is
Interview Questions evaluated only at the sampling point. The temporal expression succeeds each time the
expression evaluates to TRUE.

Change(Exp), Fall(Exp), Rise(Exp)

Detects a change in the sampled value of an expression.

Consume

http://testbench.in/SP_16_TEMPORAL_OPERATORS_2.html[9/26/2012 2:57:17 PM]


WWW.TESTBENCH.IN - Specman E

Removes the occurrence of an event so that it is not available for other temporal
expressions. The consume expression succeeds whenever the event occurs. If the
event occurs more than once during any given cycle, all occurrences are consumed.
After an event occurrence is consumed, that occurrence will not be recognized by any
temporal expression during the current Specman Elite tick, unless the event is
emitted again. An event cannot be consumed by more then one consume expression.
Care should be used to avoid creating race conditions between multiple events that
use an event that is consumed.

Exec

Invokes an action block when a temporal expression succeeds. The actions are
executed immediately upon the success of the expression, but not more than once per
Specman Elite tick.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SP_16_TEMPORAL_OPERATORS_2.html[9/26/2012 2:57:17 PM]


WWW.TESTBENCH.IN - Specman E

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS SYNCHRONIZING WITH THE SIMULATOR Index


Introduction
SystemVerilog To synchronize Specman Elite with a simulator, we need to define callbacks. E Basics
Verification Data Types
Start of callback: When the simulator pauses and gives control to Specman Elite. Operators
Constructs Pauses are triggered by @sim events in e. Struct
Interface Units
End of callback: When Specman Elite pauses and gives control back to the simulator. List
OOPS Methods
Pauses are caused by wait/sync actions in e.
Randomization Concurrency Actions
Constraints
Functional Coverage
The @sim EventThe simulator will apuse and give control to Specman Elite when it Extend
Assertion sees change in a signmal in an @sim event.    event clock_e is rise(‘~/top/clkâ When And Like
€™)@sim; Events
DPI Temporal Expressions
UVM Tutorial Temporal Operators 1
Temporal Operators 2
VMM Tutorial Synchronizing With The
OVM Tutorial Simulator
Wait And Sync
Easy Labs : SV
Physical Virual Feilds
Easy Labs : UVM Packing N Unpacking
Pre Run N On The Fly
Easy Labs : OVM
Coverage
Easy Labs : VMM Commands
AVM Switch TB Extendable Methods
Non Extendable Methods
VMM Ethernet sample And Gate Evc

Report a Bug or Comment


Verilog on This section - Your
input is what keeps
Verification
Testbench.in improving
Verilog Switch TB with time!
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/SP_17_SYNCHRONIZING_WITH_THE_SIMULATOR.html[9/26/2012 2:57:27 PM]


WWW.TESTBENCH.IN - Specman E

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SP_17_SYNCHRONIZING_WITH_THE_SIMULATOR.html[9/26/2012 2:57:27 PM]


WWW.TESTBENCH.IN - Specman E

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS WAIT AND SYNC Index


Introduction
SystemVerilog E Basics
Verification There are two actions that are used to synchronize temporal activities within e and Data Types
between the Design under test and specman simulator. Operators
Constructs Struct
Interface Units
Wait Action List
OOPS Methods
Randomization The wait action suspends the execution of the current TCM until a given temporal Concurrency Actions
expression succeeds. A TCM can't continue during the same cycle in which it reaches a Constraints
Functional Coverage Extend
wait. Even if the temporal execution succeeds in the current simulator callback, the
Assertion TCM won't proceed. The TCM has to wait at least until the next simulator callback. When And Like
Therefore, the wait action always requires at least one cycle of TCM's sampling event Events
DPI Temporal Expressions
before execution continues.
UVM Tutorial Temporal Operators 1
Temporal Operators 2
VMM Tutorial Synchronizing With The
Sync Action
OVM Tutorial Simulator
The sync action suspends the execution of the current TCM until a given temporal Wait And Sync
Easy Labs : SV
expression succeeds. With a sync action, execution can continue in the same Physical Virual Feilds
Easy Labs : UVM simulator callback. Packing N Unpacking
Pre Run N On The Fly
Easy Labs : OVM
Coverage
Easy Labs : VMM Difference Between Wait And Sync Commands
AVM Switch TB Extendable Methods
- Wait action will not proceed in the same callback in which   it is encountered. Non Extendable Methods
VMM Ethernet sample - Sync action may proceed in the same callback(if the   condition is currently valid). And Gate Evc

Report a Bug or Comment


Verilog on This section - Your
input is what keeps
Verification
Testbench.in improving
Verilog Switch TB with time!
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/SP_18_WAIT_AND_SYNC.html[9/26/2012 2:57:34 PM]


WWW.TESTBENCH.IN - Specman E

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SP_18_WAIT_AND_SYNC.html[9/26/2012 2:57:34 PM]


WWW.TESTBENCH.IN - Specman E

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PHYSICAL VIRUAL FEILDS Index


Introduction
SystemVerilog Physical Fields E Basics
Verification Data Types
A field defined as a physical field (with the “%†option) is packed when the struct Operators
Constructs is packed. Fields that represent data that is to be sent to the HDL device in the Struct
Interface simulator or that are to be used for memories in the simulator or in Specman Elite, Units
need to be physical fields. Nonphysical fields are called virtual fields and are not List
OOPS Methods
packed automatically when the struct is packed, although they can be packed
Randomization individually. If no range is specified, the width of the field is determined by the fieldâ Concurrency Actions
€™s type. For a physical field, if the field’s type does not have a known width, you Constraints
Functional Coverage Extend
must use the (bits | bytes : num) syntax to specify the width.
Assertion When And Like
Events
DPI Temporal Expressions
Ungenerated Fields
UVM Tutorial Temporal Operators 1
A field defined as ungenerated (with the “!†option) is not generated Temporal Operators 2
VMM Tutorial Synchronizing With The
automatically. This is useful for fields that are to be explicitly assigned during the
OVM Tutorial test, or whose values involve computations that cannot be expressed in constraints. Simulator
Wait And Sync
Easy Labs : SV
Ungenerated fields get default initial values (0 for scalars, NULL for structs, empty Physical Virual Feilds
Easy Labs : UVM list for lists). An ungenerated field whose value is a range (such as [0..100]) gets the Packing N Unpacking
first value in the range. If the field is a struct, it will not be allocated and none of the Pre Run N On The Fly
Easy Labs : OVM
fields in it will be generated. Coverage
Easy Labs : VMM Commands
AVM Switch TB The “!†and “%†options can be used together, in either order. Extendable Methods
Non Extendable Methods
VMM Ethernet sample And Gate Evc

Report a Bug or Comment


Verilog on This section - Your
input is what keeps
Verification
Testbench.in improving
Verilog Switch TB with time!
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/SP_19_PHYSICAL_VIRUAL_FEILDS.html[9/26/2012 2:57:43 PM]


WWW.TESTBENCH.IN - Specman E

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SP_19_PHYSICAL_VIRUAL_FEILDS.html[9/26/2012 2:57:43 PM]


WWW.TESTBENCH.IN - Specman E

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PACKING N UNPACKING Index


Introduction
SystemVerilog Packing and Unpacking Packing performs concatenation of scalars, strings, list E Basics
Verification elements, or struct fields in the order that you specifyUnpacking performs the reverse Data Types
operation, splitting a single expression into multiple expressions. Operators
Constructs Struct
Interface Units
List
OOPS Methods
Packing.High
Randomization Concurrency Actions
Places the least significant bit of the last physical field declared or the highest list Constraints
Functional Coverage Extend
item at index [0] in the resulting list of bit.  
Assertion When And Like
Events
DPI Temporal Expressions
EXAMPLE:
UVM Tutorial <' Temporal Operators 1
struct instruction { Temporal Operators 2
VMM Tutorial Synchronizing With The
%opcode : uint (bits : 3);
OVM Tutorial %operand : uint (bits : 5); Simulator
%address : uint (bits : 8); Wait And Sync
Easy Labs : SV
!data_packed_high : list of bit; Physical Virual Feilds
Easy Labs : UVM keep opcode == 0b100; Packing N Unpacking
keep operand == 0b11001; Pre Run N On The Fly
Easy Labs : OVM
keep address == 0b00001111; Coverage
Easy Labs : VMM Commands
AVM Switch TB do_packs () is { Extendable Methods
data_packed_high = pack(packing.high, opcode, operand); Non Extendable Methods
VMM Ethernet sample }; And Gate Evc
};
Report a Bug or Comment
Verilog extend sys { on This section - Your
instruction : instruction; input is what keeps
Verification
run() is also { Testbench.in improving
Verilog Switch TB instruction.do_packs(); with time!
Basic Constructs print instruction;
print "----------------------------";
out (" %b \n",instruction.data_packed_high );
}
OpenVera };
Constructs '>
Switch TB
RVM Switch TB RESULT:
RVM Ethernet sample
  instruction = instruction-@0: instruction
                                                        @test
0       %opcode:                        4
Specman E 1       %operand:                       25
Interview Questions 2       %address:                       15
3       !data_packed_high:              (8 items)
  "----------------------------" = "----------------------------"
 %b
10011001

Packing.Low

Places the least significant bit of the first physical field declared or lowest list item at
index [0] in the resulting list of bit.  

http://testbench.in/SP_20_PACKING_N_UNPACKING.html[9/26/2012 2:57:53 PM]


WWW.TESTBENCH.IN - Specman E

 Syntax Example    i_stream = pack(packing.high, opcode, operand1, operand2);

EXAMPLE:
<'
struct instruction {
%opcode : uint (bits : 3);
%operand : uint (bits : 5);
%address : uint (bits : 8);
!data_packed_low : list of bit;
keep opcode == 0b100;
keep operand == 0b11001;
keep address == 0b00001111;

do_packs () is {
data_packed_low = pack(packing.low, opcode, operand);
};
};

extend sys {
instruction : instruction;
run() is also {
instruction.do_packs();
print instruction;
print "----------------------------";
out (" %b \n",instruction.data_packed_low );
}
};
'>

RESULT:

 instruction = instruction-@0: instruction


                                                        @test
0       %opcode:                        4
1       %operand:                       25
2       %address:                       15
3       !data_packed_low:               (8 items)
  "----------------------------" = "----------------------------"
 %b
00110011

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/SP_20_PACKING_N_UNPACKING.html[9/26/2012 2:57:53 PM]


WWW.TESTBENCH.IN - Specman E

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SP_20_PACKING_N_UNPACKING.html[9/26/2012 2:57:53 PM]


WWW.TESTBENCH.IN - Specman E

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS PRE RUN N ON THE FLY Index


Introduction
SystemVerilog There are two ways to generate data: E Basics
Verification 1.Pre-run generation Data Types
2.On-the-fly generation Operators
Constructs Struct
Interface Units
Pre-Run Generation List
OOPS Methods
Randomization -Specman Elite solves the constraints for each field under sys and randomly generates Concurrency Actions
values for them when the ‘Test’ command is issued. Constraints
Functional Coverage
-Pre-run generation is automatic for every struct and unit whose instance is under sys. Extend
Assertion -Structs and units generated in this way are static in nature. When And Like
-User can also suppress pre-run generation using “!†(do not generate) Events
DPI Temporal Expressions
-Advantage: Quickly shows what the generator will produce
UVM Tutorial Temporal Operators 1
Temporal Operators 2
VMM Tutorial Synchronizing With The
OVM Tutorial On-The-Fly Generation Simulator
Wait And Sync
Easy Labs : SV
-Is activated explicitly using gen action. Physical Virual Feilds
Easy Labs : UVM -Can be used to generate fields or method variables. Packing N Unpacking
-Saves memory when generated structs are disposable. Pre Run N On The Fly
Easy Labs : OVM
-Is recommended for generating stimulus data structs. Coverage
Easy Labs : VMM -Cannot be used to generate units. Commands
AVM Switch TB -On-the-fly generation is done with the gen action, which can  be called from Extendable Methods
methods or TCMs.    gen expression [keeping {constraint-block}]; Non Extendable Methods
VMM Ethernet sample -Lets the generator react to the DUT current state And Gate Evc

Report a Bug or Comment


Verilog on This section - Your
input is what keeps
Verification
Testbench.in improving
Verilog Switch TB with time!
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/SP_21_PRE_RUN_N_ON_THE_FLY.html[9/26/2012 2:58:03 PM]


WWW.TESTBENCH.IN - Specman E

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SP_21_PRE_RUN_N_ON_THE_FLY.html[9/26/2012 2:58:03 PM]


WWW.TESTBENCH.IN - Specman E

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS COVERAGE Index


Introduction
SystemVerilog Functional coverage is a method which allows the verification engineer to objectively E Basics
Verification evaluate how well a user defined abstraction space is covered. This space can be Data Types
internal or external to the DUT and can occur at any abstraction level. Operators
Constructs Struct
Interface Functional coverage indicates how well your testbase fulfills the test plan goals.Test Units
plan goals might include:     List
OOPS Methods
-Testing a complete range of interesting input stimuli    
Randomization -Testing a complete set of key internal states     Concurrency Actions
-Testing a complete set of sequences of stimuli or states     Constraints
Functional Coverage Extend
-Evaluating performance
Assertion When And Like
The three types of coverage data that you might want to collect are: Events
DPI Temporal Expressions
--Coverage data for the finite state machine (FSM).
UVM Tutorial --Coverage data for the generated instructions. Temporal Operators 1
--Coverage data for the corner case. Temporal Operators 2
VMM Tutorial Synchronizing With The
OVM Tutorial Simulator
Wait And Sync
Easy Labs : SV
Coverage Groups Physical Virual Feilds
Easy Labs : UVM Packing N Unpacking
Coverage groups are struct(or unit) members - Pre Run N On The Fly
Easy Labs : OVM
They have an associated event to know when to sample data. The event must be Coverage
Easy Labs : VMM declared in the same struct or unit as the coverage group. Coverage groups can be Commands
AVM Switch TB defined with “coverage group optionsâ€. Controls collection, grading, and display Extendable Methods
of the group. Coverage groups contains coverage items. The value of each coverage Non Extendable Methods
VMM Ethernet sample item is recorded when the coverage event occurs. And Gate Evc

Syntax   cover event-type [using coverage-group-option, ...] is     {coverage-item- Report a Bug or Comment
Verilog definition; ...};   on This section - Your
 cover event_type is empty; input is what keeps
Verification
Testbench.in improving
Verilog Switch TB with time!
Basic Constructs

Cover Group Options


OpenVera
Constructs -------------------------------------------------------------------
Switch TB ---
Option                  Description
RVM Switch TB -------------------------------------------------------------------
---
RVM Ethernet sample count-only            Reduces memory usage:no time info stored
                      and no post-process cross.
text = string         Text description for this coverage group
                      shown in coverage report.
when = bool-exp       Collects coverage only when boolean
Specman E                       expression evaluates to TRUE
Interview Questions radix = DEC\HEX\BIN   Displays radix for each item’s bucets.
weight = uint         Specifies grading weight relative to other
                      groups. Default is 1.
at_least = uint       Minimum number of samples for each bucket.
                      If less reports a coverage hole.
ignore = bool_exp     Ignores sample if bool_exp is TRUE
illegal = bool_exp    Causes dut_error() if bool_exp is TRUE
ranges = {range(parameters);
                      Specifies interesting ranges for int/uint types.
-------------------------------------------------------------------
---

http://testbench.in/SP_22_COVERAGE.html[9/26/2012 2:58:12 PM]


WWW.TESTBENCH.IN - Specman E

Cross-Coverage

 ItemA cross coverage item is the cross product(matrix) of two or more previously
declared basuic items. It Can cross any number of items declared in the same
coverage    group. This can also be done in e code or interactively, using Coverage
GUI. Options for cross are  same  as for basic items are available, except using ranges.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SP_22_COVERAGE.html[9/26/2012 2:58:12 PM]


WWW.TESTBENCH.IN - Specman E

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS COMMANDS Index


Introduction
SystemVerilog To run a simple hello.e file E Basics
Verification Data Types
$ specman –c “load hello.e;test;†Operators
Constructs Struct
Interface To change seed, Units
List
OOPS Methods
specman –c “load enumerate.e;test;test –seed=randomâ€
Randomization Concurrency Actions
Constraints
Functional Coverage Extend
Assertion When And Like
Events
DPI Temporal Expressions
UVM Tutorial Temporal Operators 1
Temporal Operators 2
VMM Tutorial Synchronizing With The
OVM Tutorial Simulator
Wait And Sync
Easy Labs : SV
Physical Virual Feilds
Easy Labs : UVM Packing N Unpacking
Pre Run N On The Fly
Easy Labs : OVM
Coverage
Easy Labs : VMM Commands
AVM Switch TB Extendable Methods
Non Extendable Methods
VMM Ethernet sample And Gate Evc

Report a Bug or Comment


Verilog on This section - Your
input is what keeps
Verification
Testbench.in improving
Verilog Switch TB with time!
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/SP_23_COMMANDS.html[9/26/2012 2:58:22 PM]


WWW.TESTBENCH.IN - Specman E

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SP_23_COMMANDS.html[9/26/2012 2:58:22 PM]


WWW.TESTBENCH.IN - Specman E

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS EXTENDABLE METHODS Index


Introduction
SystemVerilog global.init() - actions that relate to interactive work before test execution E Basics
Verification global.setup_test() - configuration and preparation for the run Data Types
struct.init() -  initialization within structs that are instantiated using the new Operators
Constructs expression Struct
Interface struct.pre_generate() - preparations for generation Units
struct.post_generate() - actions that concern generation and require the struct's List
OOPS Methods
generated data
Randomization global.start_test() - actions at the beginning of simulation that require all the Concurrency Actions
generated data Constraints
Functional Coverage Extend
struct.run() - invocation of TCMs and explicit emission of events
Assertion global.extract_test() - global preparation of data after simulation and before checking When And Like
struct.extract() - struct-specific preparation of data after simulation and before Events
DPI Temporal Expressions
checking
UVM Tutorial struct.check() - post-run checking Temporal Operators 1
global.finalize_test() - post-test actions Temporal Operators 2
VMM Tutorial Synchronizing With The
OVM Tutorial Simulator
Wait And Sync
Easy Labs : SV
Physical Virual Feilds
Easy Labs : UVM Packing N Unpacking
Pre Run N On The Fly
Easy Labs : OVM
Coverage
Easy Labs : VMM Commands
AVM Switch TB Extendable Methods
Non Extendable Methods
VMM Ethernet sample And Gate Evc

Report a Bug or Comment


Verilog on This section - Your
input is what keeps
Verification
Testbench.in improving
Verilog Switch TB with time!
Basic Constructs

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/SP_24_Extendable_Methods.html[9/26/2012 2:58:29 PM]


WWW.TESTBENCH.IN - Specman E

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SP_24_Extendable_Methods.html[9/26/2012 2:58:29 PM]


WWW.TESTBENCH.IN - Specman E

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS NON EXTENDABLE METHODS Index


Introduction
SystemVerilog global.generate_test() - generates the tree of structs E Basics
Verification struct.generate() - generates a specific struct Data Types
global.run_test() - executes the run() method and starts event threads for all the Operators
Constructs structs Struct
Interface global.stop_run() - ends the simulation run and calls the quit() method for all the Units
structs List
OOPS Methods
struct.quit() - deactivates all TCMs and events of the struct
Randomization global.check_test() - executes the check() method for all the structs Concurrency Actions
Constraints
Functional Coverage Extend
Assertion When And Like
Events
DPI Temporal Expressions
UVM Tutorial Temporal Operators 1
Temporal Operators 2
VMM Tutorial Synchronizing With The
OVM Tutorial Simulator
Wait And Sync
Easy Labs : SV
Physical Virual Feilds
Easy Labs : UVM Packing N Unpacking
Pre Run N On The Fly
Easy Labs : OVM
Coverage
Easy Labs : VMM Commands
AVM Switch TB Extendable Methods
Non Extendable
VMM Ethernet sample Methods
And Gate Evc

Verilog Report a Bug or Comment


on This section - Your
Verification
input is what keeps
Verilog Switch TB Testbench.in improving
Basic Constructs with time!

OpenVera
Constructs
Switch TB
RVM Switch TB
RVM Ethernet sample

Specman E
Interview Questions

http://testbench.in/SP_25_Non_Extendable_Methods.html[9/26/2012 2:58:38 PM]


WWW.TESTBENCH.IN - Specman E

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SP_25_Non_Extendable_Methods.html[9/26/2012 2:58:38 PM]


WWW.TESTBENCH.IN - Specman E

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS AND GATE EVC Index


Introduction
SystemVerilog CODE : item.e E Basics
Verification <' Data Types
type vector_kind: [INPUT, OUTPUT]; Operators
Constructs Struct
Interface struct vector_s  like any_sequence_item{ Units
  kind : vector_kind; List
OOPS Methods
  a: bit;
Randomization   b: bit; Concurrency Actions
  output : bit; Constraints
Functional Coverage Extend
};
Assertion '> When And Like
Events
DPI Temporal Expressions
CODE : sequence.e
UVM Tutorial <' Temporal Operators 1
Temporal Operators 2
VMM Tutorial Synchronizing With The
sequence vector_sequence using item = vector_s,
OVM Tutorial                                created_driver = seq_driver, Simulator
                               created_kind = seq_kind_t; Wait And Sync
Easy Labs : SV
Physical Virual Feilds
Easy Labs : UVM Packing N Unpacking
extend vector_sequence { Pre Run N On The Fly
Easy Labs : OVM
   !vector : vector_s; Coverage
Easy Labs : VMM }; Commands
AVM Switch TB Extendable Methods
'> Non Extendable Methods
VMM Ethernet sample And Gate Evc
CODE : main_seq.e
<' Report a Bug or Comment
Verilog  extend MAIN vector_sequence { on This section - Your
input is what keeps
Verification
     // Limit the no. of sequences (use predefined count) Testbench.in improving
Verilog Switch TB      keep soft count == 10; with time!
Basic Constructs
     // Start start assertion ...
     pre_body() @sys.any is first {
        driver.raise_objection(TEST_DONE);
OpenVera      };
Constructs
Switch TB      // Call's stop_run after end of all sequences (refer erm)
     post_body() @sys.any is also {
RVM Switch TB         wait [20] * cycle @driver.clock;
RVM Ethernet sample         driver.drop_objection(TEST_DONE);
     };
 };
Specman E '>
Interview Questions
CODE : seq_driver_h.e
<'
extend seq_driver {
agent : agent_u;
};
'>

CODE : seq_driver.e
<'

http://testbench.in/SP_26_AND_GATE_EVC.html[9/26/2012 2:58:47 PM]


WWW.TESTBENCH.IN - Specman E

extend seq_driver {
   event clock is only @agent.clk;
   keep bfm_interaction_mode == PULL_MODE;

   send_items() @clock is {
      var item: vector_s;
      while TRUE {
         item = get_next_item();
         agent.bfm.send_vector(item);
         emit item_done;
     };
   };

   run() is also {
      start send_items();
   };
};

'>

CODE : testcase.e
<'
extend MAIN vector_sequence {

  body()@driver.clock is only{
     //for i from 0 to 9 {
        do vector keeping {
           .kind == INPUT;
        };
        print vector.a;
        print vector.b;
        do vector keeping {
           .kind == OUTPUT;
        };
        print vector.output;
     //};

   };
};
'>

CODE : agent_h.e
<'
unit agent_u {
};
'>
CODE : agent.e
<'
extend agent_u {

  keep hdl_path() == "~/and_gate_tb";

  bfm: bfm_u is instance;

http://testbench.in/SP_26_AND_GATE_EVC.html[9/26/2012 2:58:47 PM]


WWW.TESTBENCH.IN - Specman E

  driver : seq_driver is instance;


  coverage : coverage_u is instance;
  sb: scoreboard_u is instance;
  monitor: monitor_u is instance;
  
  sig_a  :string;
  sig_b  :string;
  sig_c  :string;
  sig_clk:string;
  
  verilog task '$shm_close'();
  
  verilog variable 'a' using wire;
  verilog variable 'b' using wire;
  verilog variable 'c' using wire;
  
  keep bfm.agent == me;
  keep driver.agent == me;
  keep coverage.agent == me;
  keep monitor.agent == me;
  
  keep sig_a =="a";
  keep sig_b == "b";
  keep sig_c == "c";
  keep sig_clk == "clk";
  event clk is rise('(sig_clk)')@sim;
    
  close_waveform() @clk is {
        '$shm_close'();
        wait [2]* cycle;
        sys.drop_objection(TEST_DONE);
  };

};
'>

CODE : coverage_h.e
<'
   unit coverage_u {
   agent:agent_u;
   event cover_event;
   };
'>
~    
CODE : coverage.e
<'
extend coverage_u {

   cover cover_event using text="coverage for inputs a,b" is {


   item a : bit = agent.sb.a;
   item b : bit = agent.sb.b;
   cross a,b using text="cross coverage";
   };
};

'>
CODE : scoreboard_h.e
<'
unit scoreboard_u {
};
'>

CODE : scoreboard.e
'
extend scoreboard_u {
a:bit;
b:bit;
output:bit;
};

'>

CODE : monitor_h.e
<'

http://testbench.in/SP_26_AND_GATE_EVC.html[9/26/2012 2:58:47 PM]


WWW.TESTBENCH.IN - Specman E

unit monitor_u {
agent: agent_u;
};
'>
CODE : monitor.e
<'
extend monitor_u {

   checker() is{

      if ((agent.sb.a & agent.sb.b) == agent.sb.output) {
      }
      else {
         dut_error("output mismatch");
      };
   };
};

'>

CODE : bfm_h.e
<'

  unit bfm_u {
     agent: agent_u;

  };

'>
    
CODE : bfm.e
<'
extend bfm_u {

   event clk is @agent.clk;

   send_vector(vec:vector_s)@clk is {
      if vec.kind == INPUT {
         '(agent.sig_a)'=  vec.a;
         '(agent.sig_b)'=  vec.b;
          wait[1];
          agent.sb.a= vec.a;
          agent.sb.b= vec.b;
          emit agent.coverage.cover_event;
      };
      if vec.kind == OUTPUT {
          vec.output='(agent.sig_c)';
          agent.sb.output=vec.output ;
          wait[1];
          agent.monitor.checker();
      };
   };
};
'>

CODE : env.e
<'
unit env_u{
   agent: agent_u is instance;

};

'>

CODE : top.e
<'
   import import_files.e;

   extend sys{
      env : env_u is instance;

    stop_wave: bool;

http://testbench.in/SP_26_AND_GATE_EVC.html[9/26/2012 2:58:47 PM]


WWW.TESTBENCH.IN - Specman E

    keep soft stop_wave == FALSE;
    all_objections_dropped(kind: objection_kind) is also {
        if kind == TEST_DONE and !stop_wave {
            raise_objection(TEST_DONE);
            start env.agent.close_waveform();
            message(LOW,"close_waveform()");
            stop_wave = TRUE;
        };
    };

   };
'>

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/SP_26_AND_GATE_EVC.html[9/26/2012 2:58:47 PM]


WWW.TESTBENCH.IN - Systemverilog Interview Questions

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS FUNCTIONAL VERIFICATION QUESTIONS Index


Functional Verification
SystemVerilog Questions
Verification (Q i1)Explaino ehowi tooinject qare crc ierroroq jinre a ipacket owhichqhas justz Functional Verification
datau yande ocrczx fields. Questions 2
Constructs Ans: Test Your Systemverilog
Interface Skills 1
Crc ierroro einjecttioni canobe qdonere by imodifyingoq jthere crc ivalue oonly.q Test Your Systemverilog
OOPS Skills 2
If idatao eisi modifiedoto qinjectre crc ierror,oq jthenre it imay oendqup inz au
Randomization ysituatione othatzx the new modified packet may have the same crc. Test Your Systemverilog
Skills 3
Functional Coverage Test Your Systemverilog
For iexampleo e,i aopacket qofre length i5oq jbitsre with i3 obitsqof dataz andu y2e
Assertion obitszx of crc value. Skills 4
Then ithereo ewilli beo8 qpacketsre of idifferentoq jdata.re There iare oonlyq4 Test Your Sva Skills
DPI Test Your Verilog Skills 1
possiblez crcu yvalues.e o
UVM Tutorial So, iforo eonei crcovalue, qtherere could ibeoq jmorere than ione odataqvalues Test Your Verilog Skills 2
whichz areu ycorrect. Test Your Verilog Skills 3
VMM Tutorial Test Your Verilog Skills 4
www.testbench.in
OVM Tutorial If iyouo emodifyi theodata, qthenre the inewoq jdatare may ihave otheqsame crcz Test Your Verilog Skills 5
value,u ywhiche owillzx not be resulted as crc error. Test Your Verilog Skills 6
Easy Labs : SV
Test Your Verilog Skills 7
Easy Labs : UVM For ioneo edatai field,othere qwillre one ionlyoq jonere crc ivalue, obyqchanging Test Your Verilog Skills 8
thez crcu yvalue,e ocrczx error will be injected for sure. Test Your Verilog Skills 9
Easy Labs : OVM
Test Your Verilog Skills
Easy Labs : VMM (Q i2)o eHowi dooyou qknowre when iverificationoq jcompleted? 10
AVM Switch TB Ans: i Test Your Verilog Skills
11
VMM Ethernet sample Verification iiso eneveri completedoas qperre me. i Test Your Verilog Skills
I icano eonlyi sayothat qmyre verification itaskoq jisre completed iwhen oIqverified 12
allz theu ypointse omentionszx in test plan. Test Your Verilog Skills
Verilog 13
(Q i3)o eHowi toodetect qdeadlockre conditions iinoq jFSMsre ? Test Your Verilog Skills
Verification
14
Verilog Switch TB .....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n Test Your Verilog Skills
(Q i4)o eHowi tooavoid qracere condition ibetweenoq jTestbenchre and iDUT o? 15
Basic Constructs
www.testbench.in Test Your Verilog Skills
Ans: 16
Test Your Verilog Skills
OpenVera In iverilogo eori VHDL,o 17
Constructs   Test Your Specman Skills
1)The iclocko ewhichi isogiven qtore DUT iandoq jTestbenchre should ihave oaqphase 1
Switch TB Test Your Specman Skills
difference.z
RVM Switch TB 2)DUT ishouldo eworki oroposedge qofre clock iandoq jtestbenchre should iwork 2
Test Your Specman Skills
RVM Ethernet sample oonqnegedge ofz clock.
3)Testbench ioutputo eandi DUTooutput qpinsre should ialwaysoq jbere driven iusing 3
ononqblocking statements. Test Your Specman Skills
4
Specman E In iSV,o e Test Your Sta Skills 1
1)The iaboveo edefinei 3otechniques. Test Your Sta Skills 2
Interview Questions
2)Clocking iblocks. Test Your Sta Skills 3
www.testbench.in Test Your Sta Skills 4
3)Program iblock. Test Your Sta Skills 5
Test Your Sta Skills 6
Test Your Sta Skills 7
(Q i5)o eWhati isomutex? Test Your Dft Skills 1
Ans: Test Your Dft Skills 2
Test Your Dft Skills 3
A imutualo eexclusioni oroMUTEX  essential qfunctionre is itooq jmakere it ipossible Test Your Dft Skills 4
oforqa multiplez processesu ytoe omakezx use of a single resource. Test Your Uvm Ovm Skills

http://testbench.in/IQ_01_FUNCTIONAL_VERIFICATION_QUESTIONS.html[9/26/2012 2:58:56 PM]


WWW.TESTBENCH.IN - Systemverilog Interview Questions

When iao esinglei resourceois qrequiredre by imultipleoq jprocesses,re MUTEX iwill


omakeqsure thatz onlyu yonee oprocesszx will be granted the access at a time. Report a Bug or Comment
For iexample, on This section - Your
A iDUTo ehasi aomemory qtore store itheoq jconfigurationre registers. iTo input is what keeps
oaccessqthe memory,z letsu ysay,e oazx protocol is defined to read the memory of Testbench.in improving
one location at a time. with time!
.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n
Testbench imayo erequirei tooaccess qthere configuration/status/interrupt
iregistersoq jatre times ifrom odifferentqplaces. Forz example,u yae omonitorzx is
reading register location of status bit, while the testcase is reading a configuration
register.
To iaccesso ethei memory,oTestcase qandre monitor iwilloq jsendre the iaddress
oofqthe locationsz andu yreade ocommand.zx But the DUT can accept only one read
request at a time.
www.testbench.in
By iusingo eMUTEX,i accessoto qmemoryre interface icanoq jbere granted ionce
oatqa time,z sou ythee oreadzx operations by monitor and testcases will not collide.

In iSV,o etoi createoa qMUTEX,re construct iaoq jsemaphorere with ione okey.
A ikeyo eisi given  tooeither qmonitorre or itestcaseoq jtore read ioperation
obasedqon whoz comesu yfirst.e oOncezx the key is returned, other waiting
component can take the key and start its operation.

Some itimes,o ethei keyowhich qisre consumed imayoq jnotre be iretuned


owhichqleads toz deadu ylocke ocondition.zx So if a key is not returned, then a
timeout should happen and a error message should be triggered.

(Q i6)o eWhati isosemaphore?


Ans:

Conceptually, iao esemaphorei isoa qbucket.re When iaoq jsemaphorere is iallocated,


oaqbucket thatz containsu yae ofixedzx number of keys is created. Processes using
semaphores must first procure a key from the bucket before they can continue to
execute. If a specific process requires a key, only a fixed number of occurrences of
that process can be in progress simultaneously. All others must wait until a sufficient
number of keys is returned to the bucket. Semaphores are typically used for mutual
exclusion, access control to shared resources, and basic synchronization.

www.testbench.in

(Q i7)o eWhati isothe qneedre of iregression?


Ans:

1) iChangeso eini theoRTL q(re development, ienhancementoq jorre bug ifix)


omayqcause existingz functionalityu ytoe obreak.zx
2) iToo ecreatei newoscenarios qbyre giving idifferentoq jseedsre to irandomization
oengine.q

(Q i8)o eWhati isorandomization?


Ans:

It iiso enoti possibleoto qlistre out ieveryoq jpossiblere real itime oscenarioqwhile
verifyingz DUT.
.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n
If iweo etryi toolist qoutre the iscenarios,oq jthenre we imay omissqsome ofz them.u
ySo,e ousingzx randomization, based on the specification, scenarios are generated in
a randomfashion.
For iexample,o etoi generateoa qpacketre of ilengthoq jwhichre ranges ifrom  0
otoq9, inz verilogu y{$random()}e o%zx 10 should be used.
With ithis,o epacketsi ofolength qarere generated irandomly.oq j
www.testbench.in

(Q i9)o eWhati isothe qsignificancere of iseedoq jinre randomization?


Ans:

Seed iiso eusedi toochange qthere sequence iofoq jrandomre numbers igenerated.
The iseedo einitializes  thei randomonumber qgenerator.re
All itheo erandomi numbersowhich qarere generated ifrom  aoq jparticularre seed
ivalue ocanqbe recreated  byz givingu ythee osamezx seed.

http://testbench.in/IQ_01_FUNCTIONAL_VERIFICATION_QUESTIONS.html[9/26/2012 2:58:56 PM]


WWW.TESTBENCH.IN - Systemverilog Interview Questions

In iouro eregressions,i stimulusogeneration qisre done irandomly.oq jRunningre the


icomplete oregressionqwill generatez sameu yrandome onumberszx if we use same
seed.
So iouro eregressioni usesothe qtimere of itestoq jcasere simulation istarted oasqthe
seedz tou yrandome onumberzx generator, with this we are able to generate
different stimulus for each regressions.

(Q i10)o eWhati isothe qdifferencere between icodeoq jcoveragere and ifunctional


ocoverage?
Ans:
www.testbench.in

Coverage iiso eusedi toocheck qwhetherre the iTestbenchoq jhasre satisfactory


iexercised otheqdesign orz not?u y
Code icoverageo ewilli giveoinformation qaboutre how imanyoq jlinesre are
iexecuted, ohowqmany timesz expressions,u ybranchese oexecuted.zx This coverage
is collected by the simulation tools. Users use this coverage to reach those corner
cases which are not hit by the random testcases. Users have to write the directed
testcases to reach the missing code coverage areas.

Functional icoverageo e,i byothe qnamere itself i,oq jisre related ito
otheqfunctionality ofz theu ydesigne oandzx it is defined by the user. User will define
the coverage points for the functions to be covered in DUT. This is completely under
user control.

Both iofo ethemi haveoequal qimportancere in itheoq jverification.re


100  0.000000unctional icoverage odoesqnot meanz thatu ythee oDUTzx is completely
exercised and vice-versa. Verification engineers will consider both coverages to
measure the verification progress.
.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n

(Q i11)o eIfi CodeoCoverage qisre 100% iandoq jfunctionalre coverage iis onot,qwhat
doesz itu ymeane o?
Ans:

The ireasono ecouldi beoany qonere of itheoq jfollowing.


www.testbench.in
1)User ididnoto eexercisei allothe qscenarios.re User ineedoq jtore write itestcases
otoqfill thez functionalu ycoveragee oholes.
2)There icouldo ebei aobug qinre the ifunctionaloq jcoveragere block iwhich oisqnot
recordingz theu yexecutede oscenario.zx User need to debug to find and fix the issue.

(Q i12)o eIfi Functionalocoverage qisre 100% iandoq jcodere coverage iis onot,qthen
whatz doesu yite omean?
Ans:

1) iIfo etherei isoa qbugre in itestoq jenvironment,re due ito othisqtest mayz falseu
yPass.e oThezx functional coverage will hit due to this false pass but some of the dut
code may not get exercised.
2) iIfo ethei dutois qare legacy icode  oroq jIP,re it imay ohaveqsome usez lessu
yblockse otozx support extra functionality. Due to this code coverage will not be 100%
achieved.  
3) iIno emyi firstocompany,  there qwasre some iuseoq jlessre logic iwhich odidqnot
getz exercised.u yWhene oIzx approached the RTL designer, he said that fixing this
use less code will break the whole design. So he did not fix it. In this situation ,
functional coverage is 100%, but not the code coverage.
4)My ifriendso eexperience,i onceoRTL qdesignerre added iaoq jcodere for ia
onewqfeature.  Because ofz missu ycommunication,e omyzx friend didnt know that
RTL designer added this new functionality.
When imyo efriendi didothe qcodere coverage, iheoq jfoundre some iunexercised
ologicqwhich hez didntu yunderstoode oandzx approached RTL designer. Then they
figured out that because of miscommunication,  they found a feature in the spec
which was implemented, but not verified.

www.testbench.in
I idonto ethinki ,opoint q2)re can ibeoq javoided.re Point i1), o3)qand 4)z canu ybee
osolved.zx

(Q i13)o eWhati isothe qdifferencere between ipassiveoq jmonitorre and iactive


omonitor.
Ans:

http://testbench.in/IQ_01_FUNCTIONAL_VERIFICATION_QUESTIONS.html[9/26/2012 2:58:56 PM]


WWW.TESTBENCH.IN - Systemverilog Interview Questions

Monitor ireportso ethei protocoloviolation qandre identifies ialloq jthere


transactions. iMonitors oareqtwo types,z Passiveu yande oactive.zx Passive monitors
do not drive any signals, all the signals are inputs.  Active monitors can drive the DUT
signals. Sometimes this is also refered as receiver.  Monitor converts the state of the
design and its outputs to a transaction abstraction level so it can be stored in a 'score-
boards' database to be checked later on.  Monitor converts the pin level activities in
to high level.

.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n

(Q i14)o eIni simulationoenvironment, qunderre what iconditionoq jthere simulation


ishould oend?
Ans:

1) iPacketo ecounti match.


2) iError
3) iErroro ecount
www.testbench.in
4) iInterfaceo eidlei count
5) iGlobalo etimeout

(Q i15)o eWhati isoscoreboard?


Ans:

The itermo eSCOREBOARDi isonot qwell-definedre in itheoq jindustry.re It isometimes


orefersqto thez storageu ydatae ostructurezx only, sometimes it includes the transfer
function as well, and sometimes it includes the comparison function. In vmm
methodology, the term scoreboard is used to refer to the entire dynamic response-
checking structure.

(Q i16)o eHowi theotest qcasesre are iincludedoq jinre to isimulation oenvironment?


Ans:

There iareo emultiplei waysoto qdore this. i


Two iveryo esimplei stylesoare qdiscussedre in ibelowoq jlink.
Click on the below link
http://www.testbench.in/TB_29_HANDLING_TESTCASE_FILES.html
www.testbench.in

(Q i17)o eWhati areothe qdifferentre ways itestcaseoq jarere included ifor


osimulationsq?
Ans:

1)Compile ionce,o esimulatei multipleotimes qwithre different itestcases:oq j


.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n
Compile iTestbencho e+i Allotestcases qatre once iandoq jduringre the isimulation,
ousingqthe $plusargs,z selectu ythee ologiczx of a particular testcase and execute it.
This istyleo eisi suedoin qOVMre and iUVM.oq j
This istyleo eshouldi makeosure qthat,re when itheoq jtestre is iexecuted
ofromqcommand line,  onlyz Testbenchu y+e orequiredzx testcase should be
compiled. Other wise, compiling all the testcases will consume huge time.
In iregression,o eCompilingi allothe qtestcasesre + itestbenchsoq jatre once iwill
osaveqtime.

2)Separate icompilation:
www.testbench.in
 Compile itheo etestbenchi once.  Toorun qare testcase, icompileoq jthere testcase i,
olinkqthe testcasez tou ytestbenche ocompiledzx code and simulate.

3)Compile ionce,o esimulatei once:o


 All itestcaseso ewithi similaroconfiguration qsettingre and itestbenchoq jarere
compiled ionce oandqsimulated inz oneu ysinglee orun.  Afterzx executing each
testcase logic, HARD reset should be applied to DUT and BFMs, so that the simulation
looks as if it started fresh for the next testcase code.
This istyleo eisi usedoin qVMMre 1.2.  This istyleoq jsavesre lot iof otimeqin
regressions.

4)Compile ionce,o esimulatei multipleotimes qwithre different idata:oq j


In isomeo everificationi environments,otestcase qcodere doesnt ineedoq jtore be
icompiles. oTestcaseqfile containsz someu ydatae owhichzx is read by testbench to
create different scenarios. Testcase file can be read using $fopen or $plusargs in
Verilog.

http://testbench.in/IQ_01_FUNCTIONAL_VERIFICATION_QUESTIONS.html[9/26/2012 2:58:56 PM]


WWW.TESTBENCH.IN - Systemverilog Interview Questions

There icouldo ebei manyomore qwaysre to idooq jthis.re


www.testbench.in
If iyouo eknowi somethingowhich qisre not imentionedoq jabovere , iplease otakeqa
minutez tou ymaile oitzx to gopi@testbench.in   

.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n
(Q i18)o eExplaini howomessages qarere implemented iinoq jyourre testbench?
Ans:

In iVMM/RVM/AVM/OVM/UVM/ERM/Truss&Tealo emethodologies,  messagei
handlingologic qisre predefined. iUseoq jcanre use ithese opredefinedqmessage
servicesz andu yprinte omessageszx as required by testbench. If above methodology
base classes are not used, then user can define his own message handling logic.

I ihaveo edefinedi aosimple qverilogre logic, ilookoq jforre Message iControl


oSystemqtopic inz theu ybelowe olink
Click on the below link http://www.testbench.in/TB_23_DEBUGGING.html

www.testbench.in

(Q i19)o eWritei codeofor qclockre generator?


Ans:

reg iclk;
initial iclko e=i 0;o
always i#10o eclki =o~clk; q

(Q i20)o eHowi toopass qare value itooq jtestbenchre from icommand oline?
Ans:
Click on the below link
http://www.testbench.in/TB_22_COMPILATION_N_SIMULATION_SWITCHS.html

(Q i21)o eWhati isotest qplanre ? iWhatoq jitre contains i?


Ans:
www.testbench.in
Click on the below link
http://www.testbench.in/TS_24_VERIFICATION_PLAN.html

(Q i22)o eExplaini someocoding qguidelinesre which iyouoq jfollowedre in iyour


oenvironment?
.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n

(Q i23)o eExplaini aboutowhite qbox/blockre box iandoq jgrayre box itesting.


Ans:
Click on the below link
http://www.testbench.in/TB_34_WHITE_GRAY_BLACK_BOX.html

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/IQ_01_FUNCTIONAL_VERIFICATION_QUESTIONS.html[9/26/2012 2:58:56 PM]


WWW.TESTBENCH.IN - Systemverilog Interview Questions

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS FUNCTIONAL VERIFICATION QUESTIONS 2 Index


Functional Verification
SystemVerilog (Q i24)o eWhati areothe qadvantagesre and idisadvantagesoq jofre State imachine Questions
Verification obasedqand taskz basedu yverificatione oenvironment. Functional Verification
Ans: Questions 2
Constructs Test Your Systemverilog
Interface state imachineo ebasedi BFMouses qare state imachineoq jtore generate ithe Skills 1
obusqcycles. SMz wouldu ygeneratee omemoryzx read, memory write, I/O read, and Test Your Systemverilog
OOPS Skills 2
I/O write cycles.
Randomization State imachineso earei alsoogood qatre handling iburstingoq jandre early Test Your Systemverilog
itermination. oItqcould alsoz beu ysetupe otozx handle special cycles like interrupt Skills 3
Functional Coverage Test Your Systemverilog
acknowledge or shutdown.
Assertion Skills 4
Use itasko ebasedi BFMofor qunitre testing. iUnitsoq jarere often iless Test Your Sva Skills
DPI Test Your Verilog Skills 1
ocomplexqthan thez wholeu ysystem,e oandzx hence, do not need a robust test
UVM Tutorial bench. A simple BFM can facilitate the early testing of a complex block especially if Test Your Verilog Skills 2
the unit has a simple interface or just one bus interface. The task based BFM is Test Your Verilog Skills 3
VMM Tutorial Test Your Verilog Skills 4
extremely efficient if the device under test performs many calculations but uses
OVM Tutorial relatively few bus access cycles to keep it going. The reason for this is, the BFM is not Test Your Verilog Skills 5
looping through an idle state every clock cycle. The BFM does not toggle any signals Test Your Verilog Skills 6
Easy Labs : SV
when a task is not active. Nor, does it make any decisions based on input when a task Test Your Verilog Skills 7
Easy Labs : UVM is not active. Test Your Verilog Skills 8
Test Your Verilog Skills 9
Easy Labs : OVM
(Q i25)o eIni aopacket qprotocol,re where itheoq jpacketre comparison iis odone? Test Your Verilog Skills
Easy Labs : VMM Ans: 10
AVM Switch TB Test Your Verilog Skills
In iscoreboard. 11
VMM Ethernet sample www.testbench.in Test Your Verilog Skills
12
(Q i26)o eWhati areotypes qofre code icoveragesoq jarere there? Test Your Verilog Skills
Verilog Ans: 13
Click on the below link Test Your Verilog Skills
Verification
http://www.testbench.in/TS_11_TYPES_OF_CODE_COVERAGE.html 14
Verilog Switch TB Test Your Verilog Skills
(Q i27)o eWhati typesoof qfunctionalre coverages iareoq jthere? 15
Basic Constructs
Ans: Test Your Verilog Skills
Click on the below link 16
http://www.testbench.in/TS_20_FUNCTIONAL_COVERAGE.html Test Your Verilog Skills
OpenVera 17
Constructs (Q i28)o eExplaini aboutodriver qandre monitor i? Test Your Specman Skills
Ans: 1
Switch TB Test Your Specman Skills
RVM Switch TB Driver: 2
.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n Test Your Specman Skills
RVM Ethernet sample
The idriverso etranslatei theooperations qproducedre by itheoq jgeneratorre into ithe 3
oactualqinputs forz theu ydesigne ounderzx verification. Generators create inputs at Test Your Specman Skills
a high level of abstraction namely, as transactions like read write operation. The 4
Specman E drivers convert this input into actual design inputs, as defined in the specification of Test Your Sta Skills 1
the designs interface. If the generator generates read operation, then read task is Test Your Sta Skills 2
Interview Questions
called, in that, the DUT input pin "read_write" is asserted. Test Your Sta Skills 3
www.testbench.in Test Your Sta Skills 4
Test Your Sta Skills 5
Monitor: Test Your Sta Skills 6
Monitor ireportso ethei protocoloviolation qandre identifies ialloq jthere Test Your Sta Skills 7
transactions. iMonitors oareqtwo types,z Passiveu yande oactive.zx Passive monitors Test Your Dft Skills 1
do not drive any signals.  Active monitors can drive the DUT signals. Sometimes this is Test Your Dft Skills 2
also refered as receiver.  Monitor converts the state of the design and its outputs to a Test Your Dft Skills 3
transaction abstraction level so it can be stored in a 'score-boards' database to be Test Your Dft Skills 4
checked later on.  Monitor converts the pin level activities in to high level. Test Your Uvm Ovm Skills

http://testbench.in/IQ_02_FUNCTIONAL_VERIFICATION_QUESTIONS_2.html[9/26/2012 2:59:08 PM]


WWW.TESTBENCH.IN - Systemverilog Interview Questions

Report a Bug or Comment


(Q i29)o eWhati typeoof qdatare structure iisoq jusedre to iimplement on This section - Your
ostimulusqstorage? input is what keeps
Ans: Testbench.in improving
with time!
1) iIno eSV,i Queueois qbestre to ido.oq j
2) iIno everai ,olinked qlistre is itheoq jbestre one ito ouse.
3) iDatao ecani alsoobe qstoredre in iexternaloq jfilesre also iusing ofileIOqor
externalz languageu yinterface.

www.testbench.in
I ilikeo epointi 3.oThe qexternalre file iwilloq jbere availabe iafter osimulation.qSo
,z thisu yfilee ocouldzx be used for debugging.  

(Q i30)o eHowi registers(configurationoregisters) qarere verified?


Ans:

In iVMM,o ereadi aboutoRAL.

Read ithiso etopici also:


Click on the below link
http://www.testbench.in/TB_32_REGISTER_VERIFICATION.html

(Q i31)o eWhati isoBFM?


.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n

(Q i32)o eWhati isoshadow qregister?


www.testbench.in
Ans:

Analogous istructureo eof  DUTi configuration,ostatus, qinterruptre registers iareoq


jimplementedre in itestbench. oTheseqare calledz shadowu yregisters.
These iareo erequiredi fororegister qverification.re In inormaloq
jverification,  Testbenchre requires ithe oDUT  registerqinformation forz takingu
ydecisions.e o

(Q i33)o eExplaini aboutothe qbackre door iaccessoq jtore registers.


Ans:

DUT iConfiguration,o estatusi andointerrupt qregisterre can ibeoq jaccessedre as iper


otheqprotocol.
To iaccesso ethesei registersousing qthere protocol iwilloq jconsumere cycles. i
Generally i,o eonlyi onceoregister qisre allowed itooq jaccessre as iper oprotocol.

www.testbench.in
To iovero ethei aboveomentioned qdisadvantage,  hierarchalre path icanoq jbere
used. iThis oisqcalled backdoorz access.

While iverifyingo ethei registers,oa qwritere operation iisoq jdonere to ia


olocationqand thenz au yreade oiszx done. Then the written data is compared against
the read data to verify the access path.
But iwhato eifi theoaddress qdecoderre and iencoderoq jhasre the isame obugq? Toz
findu youte othis,zx write operation is done as per the protocol and read is done using
backdoor.  Then the written data is compared against the read data to verify the
access path.

(Q i34)o eWhati areoReference qandre behavioral imodelsoq j?


Ans:
.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n

The itermo e'Referencei Model'odefines qwhatre it's iusedoq jfor,re whereas


i'Behavioral oModel'qdefines howz it'su ybeene oimplemented.zx

(Q i35)o eWhati isothe qusere of ilintingoq jtoolre ?


Ans:
www.testbench.in

http://testbench.in/IQ_02_FUNCTIONAL_VERIFICATION_QUESTIONS_2.html[9/26/2012 2:59:08 PM]


WWW.TESTBENCH.IN - Systemverilog Interview Questions

Linting itoolso earei theotools qthatre flag isuspiciousoq jlanguagere usage iand
oerror-proneqsyntactical constructs.z Lintingu ytoolse ogenerallyzx perform static
analysis of source code. Linting tools can help programmer find dangerous code before
a compiler turns them into run-time bugs.

Sone ilintingo etools:i Leda,oHDLint, qnLint,re Surelite ietc

(Q i36)o eWhati areothe qkeyre tools iforoq jfunctionalre verification?


Ans:
Version icontrolo esystem,makei utility, scriptingolanguages, bug
qtracker, Simulatorre ,debugger.

(Q i37)  Whato edoesi TestoAutomation qmean?


Ans:

Building iano eenvironmenti thatotests qthere DUT iautomaticallyoq jInsteadre of


ichecking otheqDUT byz eye,u ygete ocomputerszx to do the work for us.
www.testbench.in

(Q i38)o eHowi tooassure qyourre verification ienvironmentoq jisre correct/complete


i?
Ans:

Im inoto esure.i Ifou qknowre send imeoq janswerre to igopi@testbench.in

What iIo ecani thinkoare:


.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n
1)Connect imonitoro etoi driverosuch qthatre driver icyclesoq jarere monitored iby
omonitor.  Injectqerror fromz driveru yande ocheckzx whether monitor an catch the
error.  
2)If iyouo ehave  RTL,i thenochange qsomere lines iofoq jRTLre code iand
oseeqwhether testbenchz canu ycatche othezx errors.

(Q i39)o eWhoi shouldodo qthere rtl idebugoq j?re The idesigner o?qThe VEz ?
Ans:
www.testbench.in

RTL icano ebei debuggedoby qdesignerre or iverificationoq jengineer.re I ipersonally


ofeelqthat Verificationz shouldu ydebuge oRTLzx issues.

Designer icano edebugi theortl qfasterre than iVerificationoq jengineerre as ithe


odesignerqhas morez knowledgeu yone othezx RTL architecture.
More itimeo eisi requiredoby qverificationre engineer itooq jdebug.

If iVerificationo eengineeri isodebugging, qhere gets ichanceoq jtore think iabout


omoreqscenarios toz verifyu ythee oRTLzx by looking at RTL architecture.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/IQ_02_FUNCTIONAL_VERIFICATION_QUESTIONS_2.html[9/26/2012 2:59:08 PM]


WWW.TESTBENCH.IN - Systemverilog Interview Questions

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS TEST YOUR SYSTEMVERILOG SKILLS 1 Index


Functional Verification
SystemVerilog Questions
Verification (Q i1)o eWhati isothe qnamere of itheoq jmethodre in iwhich ocovergroupqis Functional Verification
constructedz inu yyoure oprojectzx ? Questions 2
Constructs Test Your Systemverilog
Interface (Q i2)o eAi methodois qdefinedre a ivirtual.oq jUsingre extended iclass Skills 1
ohandle/object,qhow toz callu ythee ovirtualzx method defined in base class? Test Your Systemverilog
OOPS Skills 2
Randomization (Q i3)o eWhati isothe qdifferencere B/W itheoq jvariablere in imodel oandqstatic Test Your Systemverilog
variablez inu yclasse o? Skills 3
Functional Coverage Test Your Systemverilog
Assertion (Q i4)o eWhati isothe qdifferencere B/W istatic,oq jautomaticre and idynamic Skills 4
ovariablesq? Test Your Sva Skills
DPI Test Your Verilog Skills 1
UVM Tutorial www.testbench.in Test Your Verilog Skills 2
(Q i5)o eWhati isothe qdifferencere B/W iverilogoq jfunctionre and iSV ofunctionq? Test Your Verilog Skills 3
VMM Tutorial Test Your Verilog Skills 4
OVM Tutorial (Q i6)o eWhati isothe qoutputre of itheoq jfollowingre program i? Test Your Verilog Skills 5
Test Your Verilog Skills 6
Easy Labs : SV
program main(); Test Your Verilog Skills 7
Easy Labs : UVM Test Your Verilog Skills 8
   iinitial begin Test Your Verilog Skills 9
Easy Labs : OVM
       ifork Test Your Verilog Skills
Easy Labs : VMM             #25 $display("time i=o e0i #oT25 q",$time); 10
AVM Switch TB .....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n Test Your Verilog Skills
       ijoin_none 11
VMM Ethernet sample www.testbench.in Test Your Verilog Skills
       ifork 12
              #20  $display(" itimeo e=i 0o# qT20  ",$time ); Test Your Verilog Skills
Verilog               #10  $display(" itimeo e=i 0o# qT10  ",$time ); 13
              #5    $display(" itimeo e=i 0o# qT5  ",$time ); Test Your Verilog Skills
Verification
         ijoin_any 14
Verilog Switch TB         disable fork; Test Your Verilog Skills
    end  15
Basic Constructs
Test Your Verilog Skills
   iinitial 16
   i#100 $finish; Test Your Verilog Skills
OpenVera www.testbench.in 17
Constructs Test Your Specman Skills
endprogram 1
Switch TB Test Your Specman Skills
RVM Switch TB (Q i7)o eWhyi Constructorois qnotre virtual i? 2
Test Your Specman Skills
RVM Ethernet sample
(Q i8)o eDoi weoneed q"virtualre constructor" ifunctionalityoq j?re If iyes, othenqwhy 3
isz itu yrequirede o? Test Your Specman Skills
4
Specman E (Q i9)o eHowi tooachieve q"virtualre constructor" ifunctionalityoq j? Test Your Sta Skills 1
.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n Test Your Sta Skills 2
Interview Questions
Test Your Sta Skills 3
(Q i10)o eLetsi sayoI qhavere transactions ia,b,c,d,e. Test Your Sta Skills 4
www.testbench.in Test Your Sta Skills 5
Test Your Sta Skills 6
       iIo ewouldi likeoto qgeneratere transaction iseriesoq jlike Test Your Sta Skills 7
       i(1)A,o e Test Your Dft Skills 1
       i(2)o eBi oroC, Test Your Dft Skills 2
       i(3)D, Test Your Dft Skills 3
       i(4)o eifi Bois qgeneratedre in isecondoq jpositionre then igenerate oDqand nextz Test Your Dft Skills 4
gou ytoe o(5)zx or jump to (1) again, Test Your Uvm Ovm Skills

http://testbench.in/IQ_03_TEST_YOUR_SYSTEMVERILOG_SKILLS_1.html[9/26/2012 2:59:21 PM]


WWW.TESTBENCH.IN - Systemverilog Interview Questions

       i(5)o eE,i gooback qtore (1)


Report a Bug or Comment
     iHowo etoi implementothis q? on This section - Your
input is what keeps
Testbench.in improving
(Q i11)o eWritei ao$display qstamenre to iprintoq jthere value iin oaqenumerated with time!
variable.z
www.testbench.in

(Q i12)o eWhati isothe qdifferentre between i`defineoq jandre "let" i?

(Q i13)o eWhyi defaultoclocking qblockre is irequiredoq j?

(Q i14)o eWhati isothe qoutputre of itheoq jfollowingre ?

.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n
module ques();

    string strin[7] ;
www.testbench.in
    int i,j,k,file;

    initial begin
        string s;
        file i=$fopen("file.txt","r");
        while (!$feof(file))begin
            k= $fscanf(file,"",s);
            strin[i] =s;
            i++;
        end
www.testbench.in
        $fclose(file);
    foreach(strin[j])
        $display("index ij=o e0  stringi =",j,strin[j]);
    $finish;
    end
endmodule
.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n

content iino efile.txt


www.testbench.in
================
aa
bb
cc
================

Ans:

Index ij=0  stringo e=i aa


Index ij=1  stringo e=i bb
Index ij=2  stringo e=i cc
www.testbench.in
Index ij=3  stringo e=i cc

The idatao e"cc"i isoread qtwice.re


This iiso ebecausei ofo$feof. q

(Q i15)o eHowi toodeallocate qanre object i?


.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n
Ans:

When iano eobjecti isono qlongerre needed, iSystemVerilogoq jautomaticallyre


reclaims ithe omemory,qmaking itz availableu yfore oreuse.zx The automatic memory
management system is an integral part of SystemVerilog.

If iusero ewanti toodeallocate, qhere can ijustoq jassignre null ito otheqobject.

http://testbench.in/IQ_03_TEST_YOUR_SYSTEMVERILOG_SKILLS_1.html[9/26/2012 2:59:21 PM]


WWW.TESTBENCH.IN - Systemverilog Interview Questions

www.testbench.in

EXAMPLE:
testclass ib; //  Declareo eai handleob qforre testclass
b i= new;    //o eConstruct  ai testclassoobject qandre stores itheoq jaddressre in ib
o."new"qallocate spacez foru ytestclass
b=null;     i//Deallocateo ethei object.MeansoDeallocate qthere memory ispaceoq
jforre object.

(Q i16)o eWhati isocallback q?


Ans:

Testbenches  must iprovideo eai "hook"owhere qthere test iprogramoq jcanre inject


inew ocodeqwithout modifyingz theu yoriginale oclasses.
Take iano eexample:i Supposeou qwantre to iinjectoq jare new ifunctionality  in
otheqdriver withoutz modifyingu ythee ocode.zx You can add the new functionality in
pre_callback task  or post-callback task,without modifying Driver task.

task Driver::run;
www.testbench.in
forever begin
...
<pre_callback>  //It icallso ethei functionopre_callback.
     i
.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n
transmit(tr);
end
endtask

task pre_callback;
www.testbench.in

endtask

For imoreo einformation,i


Click on the below link http://www.testbench.in/VM_08_VMM_CALLBACK.html

(Q i17)o eWhati isofactory qpatternre ?


Ans:
EXAMPLE::
class Generator;
Transaction itr;
mailbox mbx;
www.testbench.in
tr i= new;
task run;
  repeat (10)
.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n
    begin
    assert(tr.randomize);
    mbx.put(tr); // iSendo eouti transaction
    end
endtask
endclass

Bug::Here iObjecto e"tr"i isoconstructed qoncere outside itheoq jloop.re Then i"tr"
oisqrandomized andz putu ytheme ointozx mailbox "mbx".But mailbox "mbx" holds
only handles,not objects.Therefore Mailbox contains multiple handles pointing to
single object.Here code gets the last set of random values.
www.testbench.in

Solution::Loop ishouldo econtaini


1)Constructing iobject                                                                o e
2)Randomizing iobject  
3)Puttting iintoo emailbox

task run;
  repeat (10)
    begin
    tr i=new();          o e//1.Constructing
    assert(tr.randomize);//2.Randomize
www.testbench.in

http://testbench.in/IQ_03_TEST_YOUR_SYSTEMVERILOG_SKILLS_1.html[9/26/2012 2:59:21 PM]


WWW.TESTBENCH.IN - Systemverilog Interview Questions

    mbx.put(tr);         i//3.Puttingo eintoi mailbox


    end
.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n
endtask

Second iBug:o eThei runotask qconstructsre a  transaction iandoq jimmediatelyre


randomizes iit. oMeansqtransaction "tr"z usesu ywhatevere oconstraintszx are turned
on by default.
Solution i:o eSeparatei theoconstruction qofre tr ifromoq jitsre randomization iby
ousingqa methodz called  "Factoryu yPattern".

Factory iPattern:  
1)construct iao eblueprinti objecto
2)Randomize ithiso eblueprint(i Itohas qcorrectre random ivaluesoq j)
3)Make iao ecopyi ofothis qobjectre
www.testbench.in
4)Put iintoo emailbox

class Generator;
mailbox mbx;
Transaction iblueprint;
  blueprint i= new;//1.Constructingo eBluei print
task run;
Transaction itr;
Repeat(10}
  begin
www.testbench.in
  assert(blueprint.randomize); //2.Randomizing iBlueo eprint
.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n
  tr i= blueprint.copy; //  3.Copyo ethei blueprint
  mbx.put(tr); // i4.Puto eintoi mailbox
  end
endtask
endclass

(Q i18)o eExplaini theodifference qbetweenre data itypesoq jlogicre and ireg


oandqwire .
Ans:
www.testbench.in

WIRE:
1. iWireo eisi justoan qinterconnectionre between itwooq jelementsre which idoes
onotqhave anyz drivingu ystrength
2. iIto eisi usedofor qmodelingre combinational icircuitoq jasre it icannot ostoreqa
value.
3. iWireo ehasi aodefault qvaluere of i"z""oq jandre get ivalues ocontinuouslyqfrom
thez outputsu yofe odeviceszx to which they are connected to.
4.Example:

      wire A;
      assign A i= b&c; 

Note:wire iAo eisi evaluatedofor qeveryre simulation ideltaoq jtime.re So ithere


oisqno needz tou ystoree othezx value.

REG
www.testbench.in
1. iRego eisi ao4 qstatere unsigned ivariableoq jthatre can ihold oaqvalue andz
retainsu yuntile oazx new value is assigned to it.
2. iRegistero edatai typeocan qbere used iforoq jmodelingre both icombinational
oandqsequential logic
3. iDefaulto evaluei fororegister qisre "x" iandoq jitre doesn't irequire oanyqdriver
toz assignu yvaluee olikezx wire. It can be driven from initial and always block.
Values of the register can be changed anytime in the simulation by assigning a new
value to register.
4.Example: i

            reg A;
            always @ (b ior c)
            begin
            A=b&c;
            end 

http://testbench.in/IQ_03_TEST_YOUR_SYSTEMVERILOG_SKILLS_1.html[9/26/2012 2:59:21 PM]


WWW.TESTBENCH.IN - Systemverilog Interview Questions

Note:A iiso edeclaredi asoreg qwhichre can ibeoq jevaluatedre only iwhen othereqis
az changeu yine oanyzx of the signal in the sensitivity list. So reg needs to store the
value until there is a change in sensitivity list.
www.testbench.in

LOGIC: i
1. i4o estatei unsignedodata qtypere introduced iinoq jSystemre verilog.
2.System iVerilogo eimprovesi theoclassic qregre data itypeoq jsore that iit ocanqbe
drivenz by
  a. iContinuouso eassignments,  (ex:assigni crc=~crc;    )
  b. iGates,o e(ex:i andog1(q_out, qd);re )
  c. iModules,o e(ex:i Flp_fopsof1 q(q,re q_out, iclk,rst);oq j)
3.In iadditiono etoi beingoa qvariable.re It iisoq jgivenre the isynonym ologicqso
thatz itu ydoese onotzx look    
.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n
   ilikeo eai registerodeclaration. q
www.testbench.in
4.If iyouo eonlyi madeoprocedural qassignmentsre to i'logic'oq jthenre it iwas
osemanticallyqequivalent toz 'reg'.u y
5.A ilogic  signalo ecani beoused qanywherere a inetoq jisre used, iexcept othatqa
logicz variableu ycannote obezx driven by    
   imultipleo estructurali drivers,osuch qasre when iyouoq jarere modeling ia
obidirectionalqbus.
6.Example: i

      module sample1;
      logic crc, sa i,d, q_out;
      logic clk,rst;
      initial
      begin
              clk=1'b0; //procedural iassignment
www.testbench.in
             i#10 clko e=1'b1;
      end
      assign crc=~crc;    //continuous iassignment
      and g1(q_out, id);o e//q_outi isodriven qbyre gate
      Flp_fops if1o e(q,i q_out,oclk,rst); q//qre is idrivenoq jbyre module
      endmodule

.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n

(Q i19)o eWhati isothe qneedre of iclockingoq jblocksre ?


www.testbench.in
Ans:

Any isignalo eini aoclocking qblockre is idrivenoq jorre sampled isynchronously,


oensuringqthat yourz testbenchu yinteractse owith  thezx signals at the right time.
The i"skew"o eavoidsi raceoconditions qbetweenre Testbench iandoq jDUT.

EXAMPLE:  
clocking cb i@(posedge clk);//  clockingo eblocki cbodeclares, qsignalsre inside
ir  activeoq jon  positivere edge iof oclk.
            default input  #1ns ioutput #2ns;  //o eInputi skewoand qoutputre skew, i
            output request; //output ifrom  DUT  too etestbench
            input  grant i; //Inputo efromi testbenchoto qDUT
endclocking

Note: iIinputo esignals(grant)  arei sampledoat q1nsre before iclockoq jeventre and


ioutput(request) oareqdriven atz 2nsu ytime  aftere ocorrespondingzx clock event
www.testbench.in
 If iskewo eisi notospecified, qdefaultre input iskewoq jisre 1step iand ooutputqskew
isz 0.

(Q i20)o eWhati areothe qwaysre to iavoidoq jracere condition ibetween otestqbench


andz RTLu yusing  SystemVeriloge o?
Ans:

 
1)The iclocko ewhichi isogiven qtore DUT iandoq jTestbenchre should ihave oaqphase

http://testbench.in/IQ_03_TEST_YOUR_SYSTEMVERILOG_SKILLS_1.html[9/26/2012 2:59:21 PM]


WWW.TESTBENCH.IN - Systemverilog Interview Questions

difference.z
.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n
2)DUT ishouldo eworki oroposedge qofre clock iandoq jtestbenchre should iwork
oonqnegedge ofz clock.
3)Testbench ioutputo eandi DUTooutput qpinsre should ialwaysoq jbere driven iusing
ononqblocking statements.
4)Clocking iblocks.
www.testbench.in
5)Program iblock.

(Q i21)o eExplaini Eventoregions qinre SV i.

(Q i22)o eWhati areothe qtypesre of icoveragesoq javailablere in iSV o?

(Q i23)o eCani aoconstructor qbere qualified iasoq jprotectedre or ilocal oinqSV ?

(Q i24)o eHowi toohave qare #delay istatementoq jwhichre is iindependent


oofqtimescale ?z Iu yveriloge o,zx the #delay is dependent on timescale.

www.testbench.in
(Q i25)o eIsi itopossible qtore pass istructoq jorre union ifrom oSVqto Cz usingu yDPIe
o?zx If yes, then how is it done ?

(Q i26)o eWhati isoOOPS?

(Q i27)o eWhati isoinheritance q?

.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n
(Q i28)o eHowi toowrite qare message itooq jare string i?

(Q i29)o eSignalsi insideothe qinterfacere should ibeoq jwiresre or ilogic o?

www.testbench.in
(Q i30)o eGivei examplesoof qstaticre cast iandoq jdynamicre cast i.

(Q i31)o eHowi theoStatic qcastre and iDynamicoq jcastre errors iare oreportedq?

(Q i32)o eHowi Parameterizedomacros qcanre be idebuggedoq j?

(Q i33)o eWhati isoTLM q?

(Q i34)o eWhati willobe qthere values iofoq jrandre and irandc ovariablesqif
randomizationz failsu y?

www.testbench.in
(Q i35)o eExplaini aboutothe  Timeunit, qTimeprecisionre and i`timescaleoq j.

(Q i36)o eIsi itopossible qtore access iaoq jmemberre of ia ostructqthat isz returnedu
ybye oazx function in side the function ?

(Q i37)o eHowi toorandomize qare real idataoq jtypere variable i?


.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n

(Q i38)o eWhati iso$ qinre SV i?

(Q i39)o eWhati areothe qtypesre of iparameterizedoq jclass?

www.testbench.in
(Q i40)o eWhati isothe qdefaultre value iofoq jenumeratedre data itype o?

(Q i41)o eWhati isopolymorphism q?

(Q i42)o eGivei anoexample qofre polymorphism i.

(Q i43)o eWhati areothe qtypesre of ipolymorphismoq j?

(Q i44)o eHowi tooconvert qare command ilineoq jdefinedre value ito oaqstring inz
SystemVerilogu y?

www.testbench.in
(Q i45)o eWhati areovirtual qmethodsre ?

(Q i46)o ewhati isoan qinstancere of iaoq jclassre ?

http://testbench.in/IQ_03_TEST_YOUR_SYSTEMVERILOG_SKILLS_1.html[9/26/2012 2:59:21 PM]


WWW.TESTBENCH.IN - Systemverilog Interview Questions

.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n
(Q i47)o ewhati isoa qvirtualre class?

(Q i48)o eWhati isoa qscopere resolution ioperator?

(Q i49)o eWhati isodeep qcopyre ?

www.testbench.in
(Q i50)o eWhati isoshallow qcopyre ?

(Q i51)o ewhati isoMethod qOverloading?

(Q i52)o ewhati isoMethod qOverRidingd?

(Q i53)o eWhati isomeant qbyre abstraction?

(Q i54)o eWhati isoa qbasere class? i

www.testbench.in
(Q i55)o eWhati isoa qsuperclass?re

(Q i56)o eWhati isothe qdifferencere between iAggregationoq jandre Composition?


.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n

(Q i57)o eWhati isothe qneedre of ivirtualoq jinterfacesre ? i

(Q i58)o eWhati areothe qadvantagesre of iOOP?


Ans:

Data ihidingo ehelpsi createosecure qprograms.


Redundant icodeo ecani beoavoided qbyre using iinheritance.
www.testbench.in
Multiple iinstanceso eofi objectsocan qbere created.
Work icano ebei dividedoeasily qbasedre on iobjects.
Inheritance ihelpso etoi saveotime qandre cost.

(Q i59)o eIni whatocontext q,re you iuseoq jforeachre loop i?

(Q i60)o eWritei codeoto  print qthere contents iof  array_2doq j[][]re using iforeach


oloopq?

(Q i61)o eImplementedi codeoto qmergere double ilinkedoq jlist.  Definere each


ielement oofqlinked listz usingu yclass.e o

www.testbench.in
(Q i62)o eWhati willothe qprintedre value i?
     iBito e[7:0] a,b;
.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n
     iAo e= 8<92>hff; Bi = 8<92>h01;
   i$display("0",Ao e+ B);

(Q i63)o eWhyi checker...endcheckerois qusedre ?

(Q i64)o eIi wantoto qdelayre simulation ibyoq jsmallestre unit iof otime.qi.e
minimumz ofu yalle othezx timeprecision. How to do it ?

(Q i65)o eExplaini stratifiedoevent qqueuere ?


www.testbench.in

(Q i66)o eDefinei enumeratedodata qtypere ,with ioneoq jofre its ielements


ovalueqto bez X.

(Q i67)o eIsi thisoa qvalidre syntax i?


enum {a=0, b=7, c, d=8} alphabet;

(Q i68)o eWhati areothe qdifferentre types iofoq jparametersre available iin oSV?

(Q i69)o eWhati isothe qusere of i"type"oq joperatorre ?

www.testbench.in
(Q i70)o eWhati typeois qthere index iforoq jintre array_name i[*]? o
.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n

http://testbench.in/IQ_03_TEST_YOUR_SYSTEMVERILOG_SKILLS_1.html[9/26/2012 2:59:21 PM]


WWW.TESTBENCH.IN - Systemverilog Interview Questions

(Q i71)o eIni aoArray, qIf  indexre is ioutoq jofre the iaddress obounds,qthen whatz
willu ybee othezx return value ?

(Q i72)o eWhati isothe qreturnre type iofoq jArrayre locator imethod ofind_indexq?

(Q i73)o eWritei aoprogram qtore choose ielementsoq jrandomlyre from iQueue.


oNoqelement shouldz beu yreputede ountilzx all elements are chosen. Queue may
have elements repeated.
 
(Q i74)o eDeclarei aoqueue qofre integers iwithoq jmaximumre number iof
oelementsqto 256.

www.testbench.in
(Q i75)o eExplaini howoyou qdebuggedre randomization ifailure.

(Q i76)o eWhati isozero qdelayre loop iandoq jWhatre is ithe oproblemqwith zeroz
delayu yloope o?

(Q i77)o eWhati isothe qdifferencere between izerooq jdelayre loop iin odesignqand
testbenchz ?

(Q i78)o eIsi randomize()omethod qisre virtual i?

(Q i79)o eWritei codeofor qthere below ispec:oq j

       i2o evariblesi a,boare qdeclaredre in imodule.oq j


www.testbench.in
       iGenerateo erandomi runbersosuch qthatre a i>oq jb.re
       iDoo enoti useo$random qorre $urandom. i

(Q i80)o eIni aoclass, qare variable iisoq jdeclaredre as irandc. oButqwhen


randomized,z theu yrandome ovaluezx doesn<92>t seem to be cyclic.     What could
be the reason ?

(Q i81)o ePre_randomize()i isovirtual qorre not i?

       iIfo e"yes",i didoyou qusere the ikeywordoq j"virtual"re in ifront


oofqpre_randomize() ?
       iIfo e"not",i thenowhat qaboutre the ipre_randomize()oq jdefinitionre defined iin
oextendedqclass ?  

(Q i82)o eHowi toogenerate qrandomre numbers ibwoq jare range iof ovalues?

www.testbench.in

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/IQ_03_TEST_YOUR_SYSTEMVERILOG_SKILLS_1.html[9/26/2012 2:59:21 PM]


WWW.TESTBENCH.IN - Systemverilog Interview Questions

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS TEST YOUR SYSTEMVERILOG SKILLS 2 Index


Functional Verification
SystemVerilog Questions
Verification (Q i83)o eWritei codeofor qthere below irequiremnt. Functional Verification
Questions 2
Constructs     DUT ihaso edatai busoof q64re bit iwhichoq jisre driven ion oposedgeqof clock. Test Your Systemverilog
Interface     TESTBENCH ihaso edatai busoof q32re bit iwhichoq jcanre sample ion Skills 1
obothqposedge andz negedge. Test Your Systemverilog
OOPS Skills 2
    On iposedge,o eDrivei [0oto q31]re bits iofoq jDUTre to iTB obusqand onz
Randomization negedgeu ydrivee o[32zx to 63] bits of DUT to TB bus. Test Your Systemverilog
Skills 3
Functional Coverage Test Your Systemverilog
    Write icodeo efori theoabove qrequirement.re All itheoq jabovere logic ishould
Assertion obeqdone insidez theu yinterfacee oitself. Skills 4
Test Your Sva Skills
DPI Test Your Verilog Skills 1
UVM Tutorial (Q i84)o eWritei aoStatemechine qwithoutre using ialwaysoq jblockre . Test Your Verilog Skills 2
www.testbench.in Test Your Verilog Skills 3
VMM Tutorial Test Your Verilog Skills 4
OVM Tutorial (Q i85)o eWhati isoan qbindre statement? Test Your Verilog Skills 5
Test Your Verilog Skills 6
Easy Labs : SV
(Q i86)o eExplaini aboutothe qvirtualre task iandoq jmethodsre . Test Your Verilog Skills 7
Easy Labs : UVM Test Your Verilog Skills 8
(Q i87)o eWhati isothe qusere of itheoq jabstractre class i? Test Your Verilog Skills 9
Easy Labs : OVM
Test Your Verilog Skills
Easy Labs : VMM (Q i88)o eWhati isothe qdifferencere between imailboxoq jandre queue i? 10
AVM Switch TB Test Your Verilog Skills
.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n 11
VMM Ethernet sample (Q i89)o eWhati dataostructure qyoure used itooq jbuildre score iboard o? Test Your Verilog Skills
www.testbench.in 12
Test Your Verilog Skills
Verilog (Q i90)o eWhati areothe qadvantagesre of ilinkedoq jlistre over ithe oqueueq? 13
Test Your Verilog Skills
Verification
(Q i91)o eHowi parallelocase qandre full icaseoq jproblemsre are iavoided oinqSV ? 14
Verilog Switch TB Test Your Verilog Skills
(Q i92)o eWhati isothe qdifferencere between ipureoq jfunctionre and iordinary 15
Basic Constructs
ofunctionq? Test Your Verilog Skills
16
(Q i93)o eWhati isothe qdifferencere between i$randomoq jandre $urandom i? Test Your Verilog Skills
OpenVera 17
Constructs (Q i94)o eWhati isoscope qrandomizationre ? Test Your Specman Skills
www.testbench.in 1
Switch TB Test Your Specman Skills
RVM Switch TB (Q i95)o eListi theopredefined qrandomizationre methods. 2
Test Your Specman Skills
RVM Ethernet sample
(Q i96)  What'so eai Class? 3
Test Your Specman Skills
(Q i97)  What'so eani Object? 4
Specman E Test Your Sta Skills 1
(Q i98)  What'so ethei relationobetween qClassesre and iObjects? Test Your Sta Skills 2
Interview Questions
.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n Test Your Sta Skills 3
Test Your Sta Skills 4
(Q i99)  Whato earei differentoproperties qprovidedre by iObject-orientedoq Test Your Sta Skills 5
jsystems? Test Your Sta Skills 6
www.testbench.in Test Your Sta Skills 7
Test Your Dft Skills 1
(Q i100)  What'so edifferencei betweenoStatic qandre Non-Static ifieldsoq jofre a Test Your Dft Skills 2
iclass? Test Your Dft Skills 3
Test Your Dft Skills 4
(Q i101)o eWhati areopackages? Test Your Uvm Ovm Skills

http://testbench.in/IQ_04_TEST_YOUR_SYSTEMVERILOG_SKILLS_2.html[9/26/2012 2:59:32 PM]


WWW.TESTBENCH.IN - Systemverilog Interview Questions

(Q i102)o eWhati isoa qconstructorre in iclass? Report a Bug or Comment


on This section - Your
(Q i103)o eExplaini aboutoparameterised qclass. input is what keeps
Testbench.in improving
(Q i104)o eExplaingi aboutothe qNestedre class. with time!
www.testbench.in

(Q i105)o eDefinei casting?oWhat qarere the idifferentoq jtypesre of iCasting?

(Q i106)o eGivei exampleoof qStaticre and iDynamicoq jcasting.

(Q i107)o eWhati isothe qdifferencere between ialways_combooq jandre always@(*)


i?

.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n
(Q i108)o eWhati isothe qusere of ipackagesoq j?

(Q i109)o eWhati isodifference qbetweenre void iandoq jnullre pointer?


www.testbench.in

(Q i110)o eWhati isodifference qbetweenre overloading iandoq joverriding?

(Q i111)  Whato eisi theodifference qbetweenre class iandoq jstructure?    

(Q i112)o eWhati dooyou qmeanre by ipureoq jvirtualre functions?

(Q i113)o eWhati isothe qusere of i$castoq j?

(Q i114)o eHowi toocall qthere task iwhichoq jisre defined iin oparentqobject intoz
derivedu yclasse o?zx
www.testbench.in

(Q i115)o eWhati isoan qexpectre statement?

(Q i116)o eWhati isothe qdifferencere between irandoq jandre randc i?

(Q i117)o eWhati iso$root q?


.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n

(Q i118)o eWhati iso$unit q?

(Q i119)o eWhati areobi-directional qconstraints?


www.testbench.in

(Q i120)o eWhati isosolve...before qconstraintre ?

(Q i121)o eWithouti usingorandomize qmethodre or irandc,oq jgeneratere an iarray


oofqunique values?

(Q i122)o eExplaini aboutopass qbyre ref iandoq jpassre by ivalue o?

(Q i123)o eWhati isothe qdifferencere between i


    bit[7:0] sig_1;
    byte     isig_2;
www.testbench.in

(Q i124)o eWhati isothe qdifferencere between iprogramoq jblockre and imodule o?

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/IQ_04_TEST_YOUR_SYSTEMVERILOG_SKILLS_2.html[9/26/2012 2:59:32 PM]


WWW.TESTBENCH.IN - Systemverilog Interview Questions

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/IQ_04_TEST_YOUR_SYSTEMVERILOG_SKILLS_2.html[9/26/2012 2:59:32 PM]


WWW.TESTBENCH.IN - Systemverilog Interview Questions

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS TEST YOUR SYSTEMVERILOG SKILLS 3 Index


Functional Verification
SystemVerilog (Q i125)o eHowi tooconvert qreadre data itooq jintegerre data i? Questions
Verification Functional Verification
(Q i126)o eIi haveoa qobjectre of iaoq jclass.re I iwould olikeqto printz theu yclasse Questions 2
Constructs oname.zx How to print the class name using object handle? Test Your Systemverilog
Interface Skills 1
(Q i127)o eIi haveoa qmultire dimensional iarray.oq jIre don<92>t iknow otheqnumber Test Your Systemverilog
OOPS Skills 2
ofz dimensionsu yite ohas.zx How to know the number of dimensions of multi
Randomization dimensional array? Test Your Systemverilog
Skills 3
Functional Coverage Test Your Systemverilog
(Q i128)o eHowi programoblock qisre different ifromoq jmodule?re
Assertion Skills 4
(Q i129)o eWhati isoan qinterfacere and iwhyoq jitre is iused? Test Your Sva Skills
DPI Test Your Verilog Skills 1
www.testbench.in
UVM Tutorial Test Your Verilog Skills 2
(Q i130)  Ifo eclockingi blockois qnotre used ithenoq jwhat  happens?re Test Your Verilog Skills 3
VMM Tutorial Test Your Verilog Skills 4
OVM Tutorial (Q i131)o eWhati isofinal qblockre ? Test Your Verilog Skills 5
Test Your Verilog Skills 6
Easy Labs : SV
(Q i132)o eHowi tooimplement qare always iblockoq jlogicre in iprogram oblockq? Test Your Verilog Skills 7
Easy Labs : UVM Test Your Verilog Skills 8
(Q i133)o eWhati isothe qdifferencere between ifor/joinoq j,re fork/join_none iand Test Your Verilog Skills 9
Easy Labs : OVM
ofork/join_anyq? Test Your Verilog Skills
Easy Labs : VMM 10
AVM Switch TB .....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n Test Your Verilog Skills
(Q i134)o eWhati isothe qusere of imodoq jportsre ? 11
VMM Ethernet sample www.testbench.in Test Your Verilog Skills
12
(Q i135)o eWritei aoclock qgeneratorre without iusingoq jalwaysre block. Test Your Verilog Skills
Verilog 13
(Q i136)o ewhati isomodports q?re difference ibetweenoq jmodportsre and iinterface? Test Your Verilog Skills
Verification
o 14
Verilog Switch TB Test Your Verilog Skills
(Q i137)o eHowi dooyou qusesre classes itooq jrandomize?re 15
Basic Constructs
Test Your Verilog Skills
(Q i138)o eStatici andoautomatic qfunctions? 16
Test Your Verilog Skills
OpenVera (Q i139)o eWhati isoforward qreferencingre and ihowoq jtore avoid ithis oproblem? 17
Constructs www.testbench.in Test Your Specman Skills
1
Switch TB Test Your Specman Skills
(Q i140)o eWhati isocircular qdependencyre and ihowoq jtore avoid ithis oproblemq?
RVM Switch TB 2
Test Your Specman Skills
RVM Ethernet sample (Q i141)o eWhati isocross qcoveragere ?
3
(Q i142)o eDescribei theodifference qbetweenre Code iCoverageoq jandre Functional Test Your Specman Skills
iCoverage oWhichqis morez importantu yande oWhyzx we need them 4
Specman E Test Your Sta Skills 1
(Q i143)o eHowi tookill qare process iinoq jare fork/join i? Test Your Sta Skills 2
Interview Questions
.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n Test Your Sta Skills 3
Test Your Sta Skills 4
(Q i144)o eDifferencei betweenoAssociative qarrayre and iDynamicoq jarrayre ? Test Your Sta Skills 5
www.testbench.in Test Your Sta Skills 6
Test Your Sta Skills 7
(Q i145)o eWhati areothe qadvantagesre of iSystemoq jVerilogre DPI i? Test Your Dft Skills 1
Test Your Dft Skills 2
(Q i146)o ehowi toorandomize qare dynamic iarrayoq jofre objects? Test Your Dft Skills 3
Test Your Dft Skills 4
(Q i147)o eWhati isorandsequence qandre what iisoq jitsre use i? Test Your Uvm Ovm Skills

http://testbench.in/IQ_05_TEST_YOUR_SYSTEMVERILOG_SKILLS_3.html[9/26/2012 2:59:41 PM]


WWW.TESTBENCH.IN - Systemverilog Interview Questions

(Q i148)o eWhati isobin q? Report a Bug or Comment


on This section - Your
(Q i149)o e input is what keeps
www.testbench.in Testbench.in improving
Initial i with time!
wait_order (a,b,c);

 Which ifromo ebelowi initial processowill qcausere that iaboveoq jwait orderre will


ipass.
a)
    initial begin
    #1;
.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n
     i->a;
     i->b;
     i->c;
www.testbench.in
    end

b)
    initial begin
    #1;
     i->a;
    end
   ialways @ao e->b;
   ialways @bo e-> c;

www.testbench.in
c)

    initial begin
    #1;
     i->a;
     i#0 ->b;
.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n
     i->>c;
end

d)
www.testbench.in

    initial begin
     i#1 ->a;
     i#1 ->b;
     i#1 ->c;
    end

(Q i150)o eWhyi alwaysoblock qisre not iallowedoq jinre program iblock o?

www.testbench.in
(Q i151)o eWhichi isobest qtore use itooq jmodelre a itransaction o?qStruct orz classu
y?

(Q i152)o eHowi SVois qmorere random istableoq jthenre Verilog i?

(Q i153)o eWhati isothe qdifferencere between i"staticoq jtaskre abc()" iand


otaskqstatic abd()"z ?
.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n

(Q i154)o eHowi tooadd qare new iprocessoq jwithoutre disturbing ithe


orandomqnumber generatorz stateu y?

(Q i155)o eWhati isothe qneedre of ialiasoq jinre SV i?

www.testbench.in

http://testbench.in/IQ_05_TEST_YOUR_SYSTEMVERILOG_SKILLS_3.html[9/26/2012 2:59:41 PM]


WWW.TESTBENCH.IN - Systemverilog Interview Questions

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/IQ_05_TEST_YOUR_SYSTEMVERILOG_SKILLS_3.html[9/26/2012 2:59:41 PM]


WWW.TESTBENCH.IN - Systemverilog Interview Questions

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS TEST YOUR SYSTEMVERILOG SKILLS 4 Index


Functional Verification
SystemVerilog (Q i156)o eWhati wouldobe qthere output iofoq jthere following icode oandqhow toz Questions
Verification avoidu yite o? Functional Verification
for (int i=0; i<N; i++) begin Questions 2
Constructs         fork Test Your Systemverilog
Interface           int j i= i; Skills 1
          begin Test Your Systemverilog
OOPS Skills 2
           i#10 $display("o eJi valueois q0re ",j);
Randomization           end Test Your Systemverilog
        join_none Skills 3
Functional Coverage Test Your Systemverilog
      end 
Assertion www.testbench.in Skills 4
Test Your Sva Skills
DPI Test Your Verilog Skills 1
J iiso ealways Ni , Byousing qautomatic Keyre word, This iproblemoq jcanre be
UVM Tutorial iavoided o. Test Your Verilog Skills 2
for (int i=0; i<N; i++) begin Test Your Verilog Skills 3
VMM Tutorial Test Your Verilog Skills 4
        fork
OVM Tutorial           automatic int j i= i; Test Your Verilog Skills 5
          begin Test Your Verilog Skills 6
Easy Labs : SV
           i#10 $display("o eJi valueois q0re ",j); Test Your Verilog Skills 7
Easy Labs : UVM           end Test Your Verilog Skills 8
        join_none Test Your Verilog Skills 9
Easy Labs : OVM
.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n Test Your Verilog Skills
Easy Labs : VMM       end  10
AVM Switch TB www.testbench.in Test Your Verilog Skills
11
VMM Ethernet sample (Q i157)o eIsi itopossible qforre a ifunctionoq jtore return ia oarray(qmemory) ? Test Your Verilog Skills
  12
(Q i158)o eHowi toocheck qwhetherre randomization iisoq jsuccessfulre or inot? Test Your Verilog Skills
Verilog 13
(Q i159)o eDoi weoneed qtore call isuper.new()oq jwhenre extending ia oclassq? Test Your Verilog Skills
Verification
Whatz happensu yife owezx don't call ? 14
Verilog Switch TB Test Your Verilog Skills
(Q i160)o eWhati isothe qneedre to iimplementoq jexplicitlyre a icopy() 15
Basic Constructs
omethodqinside az transactionu y,e owhenzx we can simple assign one object to Test Your Verilog Skills
other ? 16
Test Your Verilog Skills
OpenVera (Q i161)o eHowi differentois qthere implementation iofoq jare struct iand ounionqin 17
Constructs SV.z Test Your Specman Skills
www.testbench.in 1
Switch TB Test Your Specman Skills
RVM Switch TB (Q i162)o eWhati iso"this" q? 2
Test Your Specman Skills
RVM Ethernet sample
(Q i163)o eWhati isotagged qunionre ? 3
Test Your Specman Skills
(Q i164)o eWhati iso"scope qresolutionre operator" i? 4
Specman E Test Your Sta Skills 1
(Q i165)o eWheni aoSequence qMatches? Test Your Sta Skills 2
Interview Questions
.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n Test Your Sta Skills 3
Test Your Sta Skills 4
(Q i166)o eWhati isoa qProperty? Test Your Sta Skills 5
www.testbench.in Test Your Sta Skills 6
Test Your Sta Skills 7
(Q i167)o eWhati isothe qdifferencere between iVerilogoq jParameterizedre Macros Test Your Dft Skills 1
iand oSystemVerilogqParameterized Macrosz ? Test Your Dft Skills 2
  Test Your Dft Skills 3
(Q i168)o eWhati isothe qdifferencere between i Test Your Dft Skills 4
 logic data_1; Test Your Uvm Ovm Skills

http://testbench.in/IQ_06_TEST_YOUR_SYSTEMVERILOG_SKILLS_4.html[9/26/2012 2:59:49 PM]


WWW.TESTBENCH.IN - Systemverilog Interview Questions

 var logic data_2;
 wire logic data_3 i; Report a Bug or Comment
 bit data_4; on This section - Your
 var bit data_5; input is what keeps
  Testbench.in improving
www.testbench.in with time!
(Q i169)o eWhati isothe qdifferencere between ibitoq jandre logic i?

(Q i170)o eWritei aoState qmachinere in iSVoq jstylere .

(Q i171)o eWhati isoadvantage qofre program iblockoq joverre clock iblocks


ow.r.tqrace conditionz ?

(Q i172)o eHowi tooavoid qthere race iconditionoq jbetweenre 2 iprogram oblockq?


.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n

(Q i173)o eWhati isocoverage qdrivenre verification i?

www.testbench.in
(Q i174)o eWhati isolayered qarchitecturere ?

(Q i175)o eWhati areothe qsimulationre phases iinoq jyourre verification


ienvironment o?

(Q i176)o eHowi toopick qare element iwhichoq jisre in iqueue ofromqrandom indexz
?

(Q i177)o eWhati dataostructure qisre used itooq jstorere data iin


oyourqenvironment andz whyu y?

(Q i178)o eWhati isocasting q?re Explain iaboutoq jthere various itypes oofqcasting
availablez inu ySVe o.

www.testbench.in
(Q i179)o eHowi tooimport qallre the iitemsoq jdeclaredre inside ia opackageq?

(Q i180)o eExplaini howothe qtimescalere unit iandoq jprecisionre are itaken


owhenqa modulez doesu ynote ohavezx any timescale declaration in RTL ?

(Q i181)o eWhati isostreaming qoperatorre and iwhatoq jisre its iuse o?

.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n
(Q i182)o eWhati areovoid qfunctionsre ?

(Q i183)o eHowi toomake qsurere that iaoq jfunctionre argument ipassed oasqref isz
notu ychangede obyzx the function ?

www.testbench.in
(Q i184)o eWhati isothe qusere of i"extern"oq j?

(Q i185)o eWhati isothe qdifferencere between iinitialoq jblockre and ifinal oblock?
Ans:

   iYouo ecan'ti scheduleoan qeventre or ihaveoq jdelaysre in ifinal oblock.

(Q i186)o eHowi toocheck qwhetherre a ihandleoq jisre holding iobject oorqnot ?

(Q i187)o eHowi toodisable qmultiplere threads iwhichoq jarere spawned iby


ofork...joinq

www.testbench.in

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/IQ_06_TEST_YOUR_SYSTEMVERILOG_SKILLS_4.html[9/26/2012 2:59:49 PM]


WWW.TESTBENCH.IN - Systemverilog Interview Questions

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/IQ_06_TEST_YOUR_SYSTEMVERILOG_SKILLS_4.html[9/26/2012 2:59:49 PM]


WWW.TESTBENCH.IN - Systemverilog Interview Questions

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS TEST YOUR SVA SKILLS Index


Functional Verification
SystemVerilog (Q i188)o eWhati isothe qdifferencere between i$roseoq jandre posedge i? Questions
Verification Functional Verification
(Q i189)o eWheni anoassert qpropertyre or iassumeoq jpropertyre matches? Questions 2
Constructs Test Your Systemverilog
Interface (Q i190)  Tello eoni AssertionoSeverity qLevels? Skills 1
Test Your Systemverilog
OOPS Skills 2
(Q i191)o eExplaingi aboutoSVA qLayers?
Randomization Test Your Systemverilog
(Q i192)o eWheni aocover qpropertyre matches? Skills 3
Functional Coverage Test Your Systemverilog
www.testbench.in
Assertion Skills 4
(Q i193)o eDifferencei b/woProcedural qandre Concurrent iAssertionsoq j? Test Your Sva Skills
DPI Test Your Verilog Skills 1
UVM Tutorial (Q i194)o eHowi manyotypes qofre assertions? iExplain? Test Your Verilog Skills 2
Test Your Verilog Skills 3
VMM Tutorial Test Your Verilog Skills 4
(Q i195)o eEquivalenti constructoto q|->re 1 i?oq j
OVM Tutorial Ans:  |=> Test Your Verilog Skills 5
  Test Your Verilog Skills 6
Easy Labs : SV
(Q i196)o eWhati isoSequence? Test Your Verilog Skills 7
Easy Labs : UVM .....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n Test Your Verilog Skills 8
Test Your Verilog Skills 9
Easy Labs : OVM
www.testbench.in Test Your Verilog Skills
Easy Labs : VMM (Q i197)o eWhati isothe qdifferencere between iassumeoq jandre assert i? 10
AVM Switch TB Test Your Verilog Skills
(Q i198)o eHowi toocheck qforre only ioneoq jsuccessre in iassertions o?q 11
VMM Ethernet sample Test Your Verilog Skills
(Q i199)o eWritei anoassertion qforre Glitch idetectionoq j. 12
Test Your Verilog Skills
Verilog (Q i200)o ewhati isothe qdifferencere between iexpectoq jandre assert istatement? o 13
Test Your Verilog Skills
Verification
14
Verilog Switch TB  "Write itheo eSVAi assertionocode qforre the ifollowingoq jdescription" Test Your Verilog Skills
15
Basic Constructs www.testbench.in
Test Your Verilog Skills
(Q i201)o eAsi longoas qsig_are is istilloq jup,re sig_b ishould onotqbe asserted. 16
Test Your Verilog Skills
OpenVera (Q i202)o eThei signalosig_a qisre a ipulse:oq jItre can ionly obeqasserted forz oneu 17
Constructs ycycle,e oandzx must be deasserted in the next cycle. Test Your Specman Skills
1
Switch TB Test Your Specman Skills
(Q i203)o esig_ai isoa qpulse,re unless isig_boq jisre asserted.
RVM Switch TB 2
Test Your Specman Skills
RVM Ethernet sample (Q i204)o esig_ai andosig_b qcanre only ibeoq jassertedre together ifor ooneqcycle;
inz theu ynexte ocycle,zx at least one of them must be deasserted. 3
.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n Test Your Specman Skills
4
Specman E (Q i205)o eIfi sig_aois qassertedre for itheoq jfirstre time, ithen oitqmust havez Test Your Sta Skills 1
beenu yprecedede obyzx a sig_b. Test Your Sta Skills 2
Interview Questions
www.testbench.in Test Your Sta Skills 3
Test Your Sta Skills 4
(Q i206)o esig_ai mustonot qbere asserted ibeforeoq jthere first isig_b o(mayqbe Test Your Sta Skills 5
assertedz onu ythee osamezx cycle as sig_b). Test Your Sta Skills 6
Test Your Sta Skills 7
(Q i207)o eWheni sig_aois qasserted,re sig_b imustoq jbere asserted, iand Test Your Dft Skills 1
omustqremain upz untilu yonee oofzx the signals sig_c or sig_d is asserted. Test Your Dft Skills 2
Test Your Dft Skills 3
(Q i208)o eAfteri oneoof qthere signals isig_aoq jisre asserted, isig_b omustqbe Test Your Dft Skills 4
deasserted,z andu ymuste ostayzx down until the next sig_a. Test Your Uvm Ovm Skills

http://testbench.in/IQ_07_TEST_YOUR_SVA_SKILLS.html[9/26/2012 2:59:58 PM]


WWW.TESTBENCH.IN - Systemverilog Interview Questions

(Q i209)o eThei signalsosig_a qandre sig_b imayoq jonlyre be iasserted oifqsig_c isz Report a Bug or Comment
asserted. on This section - Your
input is what keeps
(Q i210)o eTherei existsoa qtransactionre that ireachesoq jitsre end  either  sig_a  or Testbench.in improving
isig_b. with time!
www.testbench.in

(Q i211)o eIfi sig_aois qreceivedre while isig_boq jisre inactive, ithen oonqthe nextz
cycleu ysig_ce omustzx be inactive, and sig_b must be asserted.

(Q i212)o esig_ai mustonot qrisere before itheoq jfirstre sig_b.

(Q i213)o esig_ai mustonot qbere asserted itogetheroq jwithre sig_b  or iwith osig_c.

.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n
(Q i214)o esig_ai mustonot qbere asserted ibetweenoq janre sig_b iand
otheqfollowing sig_cz (fromu yonee ocyclezx after the sig_b until one cycle after the
sig_c).

(Q i215)o esig_ai mustonot qbere asserted itogetheroq jwithre sig_b ior owithqsig_c.
www.testbench.in

(Q i216)o eIfi weoare qatre the iendoq jofre a itransaction o(sig_aqis down,z sig_bu
yise oup),zx and sig_c is down, then sig_c must be asserted before the next time that
sig_a is asserted.

(Q i217)o eIfi sig_aois qdown,re sig_b imayoq jonlyre rise ifor ooneqcycle beforez
theu ynexte otimezx that sig_a is asserted.

(Q i218)o esig_ai mustonot qrisere if iweoq jhavere seen isig_b oandqhavent seenz
theu ynexte osig_czx yet (from the cycle after the sig_b until the cycle of the sig_c).

(Q i219)o eThei auxiliaryosignal qsig_are indicates ithatoq jwere have iseen oaqsig_b,
andz haventu yseene oazx sig_c since then. It rises one cycle after the sig_b, and falls
one cycle after the sig_c.

(Q i220)o esig_ai mayobe qassertedre only iwhileoq jsig_bre is itrue, oi.e.,qwe arez
atu yleaste oonezx cycle after a sig_c and havent seen a sig_d since then (except
perhaps in the current cycle)
www.testbench.in

(Q i221)o esig_ai mayobe qassertedre only iduringoq jthere time iframe


obeginningqwith sig_bz (inclusive)u yande ocontinuingzx until sig_c rises (inclusive).

(Q i222)o esig_ai mustonot qrisere if iweoq jhavere seen isig_b oandqhavent seenz
theu ynexte osig_czx yet (from the cycle after the sig_b until the cycle before the
sig_c).

(Q i223)o eWhilei sig_aois qdown,re sig_b imayoq jrisere only iif osig_cqis down.
.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n

(Q i224)o eIfi sig_aois qassertedre with isig_boq jinactive,re and isig_c owasqinactive
inz theu ypreviouse ocyclezx and remains inactive in the next cycle, then sig_a must
be deasserted in the next cycle.

(Q i225)o eIfi thereoare qarere two ioccurencesoq jofre sig_a irising


owithqSTATE=active1, andz nou ysig_be ooccurszx between them, then within 3
cycles of the second rise of sig_a, START must occur.
www.testbench.in

(Q i226)o eShowi aosequence qwithre 3 itransactionsoq j(inre which isig_a


oisqasserted 3z times).

(Q i227)o eIfi theostate qmachinere reaches iSTATE=active1,oq jitre will ieventually


oreachqSTATE=active2.

(Q i228)o esig_ai isoeventually qasserted,re after isig_boq jhasre fallen.

http://testbench.in/IQ_07_TEST_YOUR_SVA_SKILLS.html[9/26/2012 2:59:58 PM]


WWW.TESTBENCH.IN - Systemverilog Interview Questions

(Q i229)o esig_ai isoeventually qassertedre without isig_boq jindication,re after isig_c


ohasqfallen.

(Q i230)o eIfi sig_aois qactive,re then isig_boq jwasre active i3 ocyclesqago.


www.testbench.in

(Q i231)o eIfi sig_aois qactive,re then isig_boq jwasre active isomewhere oinqthe
past.

(Q i232)o eIfi thereois qare sig_a, ifollowedoq jbyre 3 iconsecutive osig_b,qthen inz
eachu yofe othezx 3 cycles the data written (DO) is equal to the data read (DI).

.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n
(Q i233)o eAlways,i ifoon q3re consecutive isig_a,oq jsig_bre appears, ithen oonqthe
nextz sig_cu ycycle,e osig_azx holds.

(Q i234)o eEveryi sig_aomust qeventuallyre be iacknowledgedoq jbyre sig_b, iunless


osig_cqappears

(Q i235)o esig_ai occurson qcyclesre after isig_b.


www.testbench.in

(Q i236)o esig_ai andosig_b qarere environment isignals,oq jwhichre can ibe


ogivenqat anyz time,u ybute oshouldzx never be given together.

(Q i237)o eIfi sig_aois qactive,re it imustoq jbere deactivated ione ocycleqafter


sig_bz arrives.u yNotee othatzx sig_a may already be active when sig_b is asserted.

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/IQ_07_TEST_YOUR_SVA_SKILLS.html[9/26/2012 2:59:58 PM]


WWW.TESTBENCH.IN - Systemverilog Interview Questions

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS TEST YOUR VERILOG SKILLS 1 Index


Functional Verification
SystemVerilog Questions
Verification (Q i1)o eIdentifyi theoerror qinre the ifollowingoq jcode. Functional Verification
b[7:0] = {2{5}}; Questions 2
Constructs Test Your Systemverilog
Interface (Q i2)  Wheno earei instanceonames qoptional? Skills 1
Test Your Systemverilog
OOPS Skills 2
(Q i3)o eIni theofollowing qprogram,  whatre is itheoq jproblemre and ihow otoqavoid
Randomization itz ? Test Your Systemverilog
task driver; Skills 3
Functional Coverage Test Your Systemverilog
input read;
Assertion www.testbench.in Skills 4
input [7:0] write_d; Test Your Sva Skills
DPI Test Your Verilog Skills
begin
UVM Tutorial #30 date_valid i= 1'b1; 1
wait(read i== 1'b1); Test Your Verilog Skills 2
VMM Tutorial Test Your Verilog Skills 3
#20 cpu_data i= write_data;
OVM Tutorial $display("End iofo etask"); Test Your Verilog Skills 4
end Test Your Verilog Skills 5
Easy Labs : SV
endtask Test Your Verilog Skills 6
Easy Labs : UVM Test Your Verilog Skills 7
Test Your Verilog Skills 8
Easy Labs : OVM .....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n
(Q i4)o eHowi manyolevels qcanre be inestedoq jusingre `include i? Test Your Verilog Skills 9
Easy Labs : VMM www.testbench.in Test Your Verilog Skills
AVM Switch TB Ans: 10
You icano enesti theo`include compiler qdirectivere to iatoq jleastre 16 levels. Test Your Verilog Skills
VMM Ethernet sample 11
(Q i5)o eWhati isothe qusere of i$countdriversoq j? Test Your Verilog Skills
Ans: 12
Verilog Test Your Verilog Skills
The i$countdriverso esystemi functionois qprovidedre to icountoq jthere number iof 13
Verification
odriversqon az specifiedu ynete osozx that bus contention can be identified. Test Your Verilog Skills
Verilog Switch TB 14
Test Your Verilog Skills
Basic Constructs
(Q i6)o eWhati isothe qusere of i$getpatternoq j? 15
Ans: Test Your Verilog Skills
16
OpenVera The isystemo efunctioni $getpatternoprovides qforre fast iprocessingoq jofre stimulus Test Your Verilog Skills
Constructs ipatterns othatqhave toz beu ypropagatede otozx a large number of scalar inputs. 17
The function reads stimulus patterns that have been loaded into a memory using the Test Your Specman Skills
Switch TB 1
$readmemb or $readmemh system tasks.
RVM Switch TB www.testbench.in Test Your Specman Skills
2
RVM Ethernet sample
Test Your Specman Skills
reg [1:in_width] in_mem[1:patterns]; 3
integer index; Test Your Specman Skills
Specman E assign {i1,i2,i3,i4,i5,i6,i7,i8,i9,i10} = $getpattern(in_mem[index]); 4
Test Your Sta Skills 1
Interview Questions
(Q i7)o eWhati isothe qfunctionalityre of i&&&  (notoq j&&re , inot o&)q? Test Your Sta Skills 2
Test Your Sta Skills 3
(Q i8)o eHowi tooget qcopyre of ialloq jthere text ithat oisqprinted toz theu Test Your Sta Skills 4
ystandarde ooutputzx in a log file ? Test Your Sta Skills 5
.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n Test Your Sta Skills 6
Ans: i Test Your Sta Skills 7
Using i$log("filename"); Test Your Dft Skills 1
www.testbench.in Test Your Dft Skills 2
Test Your Dft Skills 3
(Q i9)o eWhati isothe qusere of iPATHPULSE$  ? Test Your Dft Skills 4
Test Your Uvm Ovm Skills

http://testbench.in/IQ_08_TEST_YOUR_VERILOG_SKILLS_1.html[9/26/2012 3:00:08 PM]


WWW.TESTBENCH.IN - Systemverilog Interview Questions

Ans:
PATHPULSE$ ispecparam iso eusedi toocontrol qpulsere handling ionoq jare
module path. Report a Bug or Comment
on This section - Your
(Q i10)  ino estatementi (o(a==b) q&&re (c i==oq jd)re ) i, owhatqis thez expressionu input is what keeps
ycoveragee oifzx always a=0,b=0,c=0,d=0 ? Testbench.in improving
with time!
(Q i11)o eDifferencei betweenoReduction qandre Bitwise ioperators?
Ans:

The idifferenceo eisi thatobitwise qoperationsre are ionoq jbitsre from itwo
odifferentqoperands, whereasz reductionu yoperationse oarezx on the bits of the
same operand. Reduction operators work bit by bit from right to left. Reduction
operators perform a bitwise operation on a single vector operand and yield a 1-bit
result Bitwise operators perform a bit-by-bit operation on two operands. They take
each bit in one operand and perform the operation with the corresponding bit in the
other operand.
www.testbench.in

(Q i12)  Whato eisi theodifference qbetweenre the ifollowingoq jtwore lines iof


oVerilogqcode?
#5 a i= b;
a i= #5 b;
Ans:
 #5 a i= b; 

Wait ifiveo etimei unitsobefore qdoingre the iactionoq jforre "a i= ob;".
.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n
The ivalueo eassignedi tooa qwillre be itheoq jvaluere of ib o5qtime unitsz hence.

a i= #5 b; 

The ivalueo eofi bois qcalculatedre and istoredoq jinre an iinternal otemp
www.testbench.in
register. iAftero efivei timeounits, qassignre this istoredoq jvaluere to ia.

(Q i13)  Whato eisi theodifference qbetween:re c i=oq jfoore ? ia o:qb; andz ifu


y(foo)e oczx = a; else c = b;

Ans: i

The i?o emergesi answersoif qthere condition iisoq j"x",re so ifor oinstanceqif fooz =u
y1'bx,e oazx = 'b10, and b = 'b11, you'd get c = 'b1x.
On itheo eotheri hand,oif qtreatsre X's ioroq jZsre as iFALSE, osoqyou'd alwaysz getu
yce o=zx b.

(Q i14)o eHowi isoVerilog qimplementationre independent iandoq jwhyre is ithis


oanqadvantage?

www.testbench.in

(Q i15)o eWhati leveloof qVerilogre is iusedoq jin:


a. Test ibenches
b. Synthesized idesign
c. Net ilist

.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n

(Q i16)  whato eisi theodifference qbetweenre $fopen("filename"); iandoq


j$fopen("filename","w");
Ans:

If itypeo eisi omitted,othe qfilere is iopenedoq jforre writing, iand oaqmulti channelz
descriptoru ymcde oiszx returned. If type is supplied, the file is opened as specified
by the value of type, and a file descriptor fd is returned. So in first statements , type
is omitted and mcd is returned and in the second statement, fd is returned.

http://testbench.in/IQ_08_TEST_YOUR_VERILOG_SKILLS_1.html[9/26/2012 3:00:08 PM]


WWW.TESTBENCH.IN - Systemverilog Interview Questions

www.testbench.in

In itheo efirsti statement,othe qfilere is iopenedoq jforre read iand owrite.


But iino esecondi statement,o"w" qisre specified, isooq jthere file iis oopenedqfor
onlyz writing.u y

(Q i17)  Whato eisi theodifference qbetweenre multi ichanneloq jdescriptors(mcd)re


and ifile odescriptors(fd)?
Ans:

The imultio echanneli descriptoromcd qisre a i32oq jbitre reg iin owhichqa singlez
bitu yise osetzx indicating which file is opened. Unlike multi channel descriptors, file
descriptors can not be combined via bitwise or in order to direct output to multiple
files. Instead, files are opened via file descriptor for input, output, input and output,
as well as for append operations, based on the value of type.

(Q i18)  Howo etoi generateoa qrandomre number?

www.testbench.in
(Q i19)o eHowi toogenerate qare random inumberoq jwhichre is iless otheq100 ?

(Q i20)o eHowi toogenerate qare random inumberoq jwhichre is ibetween o0qto 100z
?

(Q i21)  Whato eisi theoadvantage qofre Named iPortoq jConnectionre over iOrdered


oPortqConnection ?
.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n

<< PREVIOUS PAGE TOP NEXT PAGE >>

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/IQ_08_TEST_YOUR_VERILOG_SKILLS_1.html[9/26/2012 3:00:08 PM]


WWW.TESTBENCH.IN - Systemverilog Interview Questions

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS TEST YOUR VERILOG SKILLS 2 Index


Functional Verification
SystemVerilog (Q i22)o eHowi toogenerate qare random inumberoq jbetweenre 44 ito o55q? Questions
Verification Functional Verification
(Q i23)o eHowi tooget qdifferentre random inumbersoq jinre different isimulations? Questions 2
Constructs Test Your Systemverilog
Interface (Q i24)  whato eisi theodifferent qbetweenre $sformat iandoq j$swrite? Skills 1
Ans: Test Your Systemverilog
OOPS Skills 2
Randomization The isystemo etaski $sformatois qsimilarre to itheoq jsystemre task i$swrite, owithqa Test Your Systemverilog
onez majoru ydifference.e oUnlikezx the display and write family of output system Skills 3
Functional Coverage Test Your Systemverilog
tasks, $sformat always interprets its second argument, and only its second argument
Assertion as a format string. This format argument can be a static string, such as "data is 0" , or Skills 4
can be a reg variable whose content is interpreted as the format string. No other Test Your Sva Skills
DPI Test Your Verilog Skills 1
arguments are interpreted as format strings. $sformat supports all the format
UVM Tutorial specifiers supported by $display, Test Your Verilog Skills
2
VMM Tutorial Test Your Verilog Skills 3
OVM Tutorial (Q i25)  Whato eisi theodifference qbetweenre wire iandoq jreg? Test Your Verilog Skills 4
www.testbench.in Test Your Verilog Skills 5
Easy Labs : SV
Ans: Test Your Verilog Skills 6
Easy Labs : UVM Test Your Verilog Skills 7
Net itypes:o e(wire,tri)Physicali connectionobetween qstructuralre elements. Test Your Verilog Skills 8
Easy Labs : OVM
iValueoq jassignedre by ia ocontinuousqassignment orz au ygatee ooutput. Test Your Verilog Skills 9
Easy Labs : VMM Register itype:o e(reg,i integer,otime, qreal,re real itime)oq jrepresentsre abstract Test Your Verilog Skills
AVM Switch TB idata ostorageqelement. Assignedz valuesu yonlye owithinzx an always statement or 10
an initial statement. Test Your Verilog Skills
VMM Ethernet sample 11
The imaino edifferencei betweenowire qandre reg iisoq jwirere cannot ihold Test Your Verilog Skills
o(store)qthe valuez whenu ythee onozx connection between a and b like 12
Verilog a-------------b, iifo etherei isono qconnectionre in iaoq jandre b, iwire olooseqvalue Test Your Verilog Skills
wherez asu yrege ocanzx hold the value even if there in no connection. 13
Verification
Test Your Verilog Skills
Verilog Switch TB Default ivalues:wireo eisi Z,regois qx. 14
Test Your Verilog Skills
Basic Constructs
15
.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n Test Your Verilog Skills
(Q i26)o eWhati happensoif qare port iisoq junconnectedre ? 16
OpenVera www.testbench.in Test Your Verilog Skills
Constructs Ans: 17
Test Your Specman Skills
Switch TB 1
Unconnected iinputo eportsi initializeoto qzre and ifeedoq jthatre value iinto
RVM Switch TB otheqcomponent, whichz canu ycausee oproblems.zx More common are redundant or Test Your Specman Skills
2
RVM Ethernet sample unwanted outputs which are left unconnected to be optimized away in synthesis.
Test Your Specman Skills
3
(Q i27)  Whato eisi theodifference qbetweenre === iandoq j==re ? Test Your Specman Skills
Specman E Ans i: 4
Test Your Sta Skills 1
Interview Questions
output iofo e"=="i canobe q1,re 0 ioroq jX. Test Your Sta Skills 2
output iofo e"==="i canoonly qbere 0 ioroq j1. Test Your Sta Skills 3
Test Your Sta Skills 4
When iyouo earei comparingo2 qnosre using i"=="oq jandre if ione/both Test Your Sta Skills 5
otheqnumbers havez oneu yore omorezx bits as "x" then the output would be "X" . But Test Your Sta Skills 6
if use "===" output would be 0 or 1. Test Your Sta Skills 7
Test Your Dft Skills 1
www.testbench.in Test Your Dft Skills 2
e.g iAo e=i 3'b1x0 Test Your Dft Skills 3
B i=o e3'b10x Test Your Dft Skills 4
Test Your Uvm Ovm Skills

http://testbench.in/IQ_09_TEST_YOUR_VERILOG_SKILLS_2.html[9/26/2012 3:00:18 PM]


WWW.TESTBENCH.IN - Systemverilog Interview Questions

A i==o eBi willogive qXre as ioutput.


A i===o eBi willogive q0re as ioutput.
"==" iiso eusedi forocomparison qofre only i1'soq jandre 0's i.It ocan'tqcompare X's.z Report a Bug or Comment
Ifu yanye obitzx of the input is X output will be X on This section - Your
"===" iiso eusedi forocomparison qofre X ialso... input is what keeps
Testbench.in improving
"==" icano ebei synthesized,owhere qasre "===" icannot. with time!
.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n

www.testbench.in
(Q i28)  Whato eisi theodifference qamongre case,casex iandoq jcasez?
Ans:

case itreatso eonlyi 0oor q1re values iinoq jcasere alternative iand oisqis notz
dealingu ywithe odon'tzx care condition.
casex itreatso ealli xoand qzre values iinoq jcasere alternative ior ocaseqexpression
asz au ydon'te ocare.
casez itreatso ealli zovalues qinre case ialternatives.oq jallre bit ipositions owithqz
canz treatu yase oazx don't care

(Q i29)o eWhati isothe qdifferencere between i@(aoq jorre b) iand o@(aq| b)

(Q i30)o eWhati isofull qcasere and iparalleloq jcase.??

www.testbench.in
(Q i31)o eWhati isothe qdifferencere between icompiled,oq jinterpreted,re event
ibased oandqcycle basedz simulatoru y?

(Q i32)o eWhati isocompilation q?


Ans:

To isimulateo eai Verilogomodel, qwere must ifirstoq jconvertre our isource


ofilesqinto az binaryu yforme othatzx can be recognized by the simulator. The
process of checking the syntax and producing the binary file is known as compilation.

(Q i33)o eWhati dataotypes qcanre be iusedoq jforre input iport, ooututqport andz
inoutu yporte o?
.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n

(Q i34)o eWhati isothe qfunctionalityre of itriregoq j?

www.testbench.in
(Q i35)o eWhati isothe qfunctionalityre of itri1oq jansre tri0 i?

(Q i36)o eDifferencei betweenoconditional qcompilationre and i$plusargs??

(Q i37)o eWhati isothe qbenefitre of iusingoq jBehaviorre modeling istyle ooverqRTL


modeling?

(Q i38)o eWhati isothe qdifferencere between itaskoq jandre function?

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/IQ_09_TEST_YOUR_VERILOG_SKILLS_2.html[9/26/2012 3:00:18 PM]


WWW.TESTBENCH.IN - Systemverilog Interview Questions

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/IQ_09_TEST_YOUR_VERILOG_SKILLS_2.html[9/26/2012 3:00:18 PM]


WWW.TESTBENCH.IN - Systemverilog Interview Questions

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS TEST YOUR VERILOG SKILLS 3 Index


Functional Verification
SystemVerilog (Q i39)  Whato eisi theodifference qbetweenre static ifunctionoq jandre automatic Questions
Verification ifunction? Functional Verification
Ans: Questions 2
Constructs Test Your Systemverilog
Interface Automatic ifunctiono elocali variablesoCan qnotre seen iinoq jwavere form iviewer. Skills 1
We icannoto eusei $Monitoroand q$strobere on ilocaloq jvariablesre also i. Test Your Systemverilog
OOPS Skills 2
Randomization Test Your Systemverilog
(Q i40)  Whato eisi theodifference qbetweenre static itaskoq jandre automatic itask? Skills 3
Functional Coverage Test Your Systemverilog
Assertion Skills 4
(Q i41)o eWhati isoadvantage qofre wand iandoq jworre over iwire o? Test Your Sva Skills
DPI Test Your Verilog Skills 1
www.testbench.in
UVM Tutorial Ans: Test Your Verilog Skills 2
Test Your Verilog Skills
VMM Tutorial 3
It isupporto eTechnology-dependenti logicoconflict qresolutionre . i
OVM Tutorial wired-AND iforo eopeni collector Test Your Verilog Skills 4
wired-OR iforo eECL Test Your Verilog Skills 5
Easy Labs : SV
Test Your Verilog Skills 6
Easy Labs : UVM Test Your Verilog Skills 7
(Q i42)o eIdentifyi theoerror qinre the ifollowingoq jcode. Test Your Verilog Skills 8
Easy Labs : OVM
a[7:0] = {4{'b10}}; Test Your Verilog Skills 9
Easy Labs : VMM Test Your Verilog Skills
AVM Switch TB 10
.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n Test Your Verilog Skills
VMM Ethernet sample (Q i43)o eWhati isothe qdifferencere between i&&oq jandre &, iif oany? 11
www.testbench.in Test Your Verilog Skills
12
Verilog (Q i44)o eIsi itosynthesysable q? Test Your Verilog Skills
always @(negedge clk ior rst) 13
Verification
Test Your Verilog Skills
Verilog Switch TB (Q i45)o eWhati isothe qdifferencere between iinitialoq jandre always iblock? 14
Ans: Test Your Verilog Skills
Basic Constructs
15
NOTE: iInitialo eblocki canoalso qbere synthesized. iRefoq jtore IEEE iVerilog Test Your Verilog Skills
oSynthesisqslandered. 16
OpenVera Test Your Verilog Skills
Constructs 17
(Q i46)o ewhati isothe qdifferencere between i$stopoq jandre $finish itask Test Your Specman Skills
Switch TB 1
ofunctions?
RVM Switch TB Test Your Specman Skills
www.testbench.in 2
RVM Ethernet sample
(Q i47)o eDifferencei betweenoparameter qandre define i? Test Your Specman Skills
3
(Q i48)  Whato ethei differenceobetween qthere following itwooq jstatements? Test Your Specman Skills
Specman E 4
@( val i== 2) Test Your Sta Skills 1
Interview Questions
wait(val i== 2) Test Your Sta Skills 2
Test Your Sta Skills 3
(Q i49)o eWhati areothe qdifferencere while ispecifyingoq jthere parameters iusing Test Your Sta Skills 4
otheqdefparam constructz vs.u yspecifyinge oduringzx instantiation? Test Your Sta Skills 5
.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n Test Your Sta Skills 6
Test Your Sta Skills 7
(Q i50)  Differenceo ebetweeni Vectoredoand qscalaredre nets? Test Your Dft Skills 1
www.testbench.in Test Your Dft Skills 2
Test Your Dft Skills 3
(Q i51)  Differenceo ebwi realoand qrealtimere ? Test Your Dft Skills 4
Test Your Uvm Ovm Skills

http://testbench.in/IQ_10_TEST_YOUR_VERILOG_SKILLS_3.html[9/26/2012 3:00:27 PM]


WWW.TESTBENCH.IN - Systemverilog Interview Questions

(Q i52)  whato eisi theodifference qbetweenre arthamatic iandoq jlogicalre shift


iregister? Report a Bug or Comment
on This section - Your
(Q i53)  Whato eisi theodifference qbwre following itwooq jregisters?? input is what keeps
Testbench.in improving
reg [1:n] rega; // iAno en-biti registerois qnotre the isame with time!
reg mema i[1:n]; //o easi aomemory qofre n i1-bitoq jregisters

www.testbench.in
(Q i54)  Howo ethei aboveotwo qarere handled iin  assignments,oq jports,functionsre
and itask o?

(Q i55)  Whato eisi theodifference qbetweenre parameters iandoq jspecparams?

(Q i56)o eIsi itopossible qtore synthesize iforoq jloopre ?


Ans:
.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n

for iloopo ewithi fixedolimits qcanre be  Synthesized i

(Q i57)o eHowi isotime qadvancedre in iaoq jsimulation?


www.testbench.in

(Q i58)o eNamei threeomethods qofre timing icontrol?

(Q i59)o eWhati isobehavioral qmodelingre used ifor?

(Q i60)o eHowi dooyou qdefinere the istatesoq jforre an iFSM?

(Q i61)  Whato eisi theodifference qbetweenre force ireleaseoq jandre assign


ideassign?

(Q i62)  Whato eisi theodifference qbetweenre posedge iandoq jnegedge?re


www.testbench.in
And:

A inegedgeo eshalli beodetected qonre the itransitionoq jfromre 1 ito ox,qz, orz 0,u
yande ofromzx x or z to 0 where as  posedge shall be detected on the transition from
0 to x, z, or 1, and from x or z to 1

(Q i63)  whato eisi theodifference qbetweenre $display iandoq j$write?


Ans: i

The itwoo esetsi ofotasks qarere identical iexceptoq jthatre $display iautomatically
oaddsqa newlinez characteru ytoe othezx end of its output, whereas the $write task
does not. The $display task, when invoked without arguments, simply prints a newline
character. A $write task supplied without parameters prints nothing at all.
.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n

(Q i64)  Whato eisi theodifference qbetweenre $display iandoq j$monitor?

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/IQ_10_TEST_YOUR_VERILOG_SKILLS_3.html[9/26/2012 3:00:27 PM]


WWW.TESTBENCH.IN - Systemverilog Interview Questions

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/IQ_10_TEST_YOUR_VERILOG_SKILLS_3.html[9/26/2012 3:00:27 PM]


WWW.TESTBENCH.IN - Systemverilog Interview Questions

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS TEST YOUR VERILOG SKILLS 4 Index


Functional Verification
SystemVerilog (Q i65)  Whato eisi theodifference qbetweenre $display iandoq j$strobe? Questions
Verification Functional Verification
(Q i66)  Whato eisi theodifference qbetweenre 0 iandoq j%zre format ispecification? Questions 2
Constructs Ans: Test Your Systemverilog
Interface Skills 1
0 ioro e0i Unformattedo2 qvaluere data Test Your Systemverilog
OOPS Skills 2
%z ioro e%Zi Unformattedo4 qvaluere data
Randomization Test Your Systemverilog
Skills 3
Functional Coverage Test Your Systemverilog
(Q i67)o eWhati isothe qdifferencere between i0.000000e+00,0.000000oq janre d0?
Assertion Ans: Skills 4
www.testbench.in Test Your Sva Skills
DPI Test Your Verilog Skills 1
UVM Tutorial 0.000000e+00 ioro e0.000000E+00i Displayoreal qinre an iexponentialoq jformat Test Your Verilog Skills 2
0.000000 ioro e0.000000i Displayoreal qinre a idecimaloq jformat Test Your Verilog Skills 3
VMM Tutorial Test Your Verilog Skills
0 ioro e0i Displayoreal qinre exponential ioroq jdecimalre format, iwhichever
OVM Tutorial oformatqresults inz theu yshortere oprintedzx output 4
Test Your Verilog Skills 5
Easy Labs : SV
Test Your Verilog Skills 6
Easy Labs : UVM (Q i68)  Whato eisi theodifference qbetweenre $finish iadoq j$stop? Test Your Verilog Skills 7
Test Your Verilog Skills 8
Easy Labs : OVM
The i$finisho esystemi taskosimply qmakesre the isimulatoroq jexitre and ipass Test Your Verilog Skills 9
Easy Labs : VMM ocontrolqback toz theu yhoste ooperatingzx system. Test Your Verilog Skills
AVM Switch TB The i$stopo esystemi taskocauses qsimulationre to ibeoq jsuspended. 10
Test Your Verilog Skills
VMM Ethernet sample 11
(Q i69)  Whato eisi theodifference qbetweenre PLI iandoq jVPI? Test Your Verilog Skills
.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n 12
Verilog Ans: Test Your Verilog Skills
www.testbench.in 13
Verification
Test Your Verilog Skills
Verilog Switch TB Verilog iProceduralo eInterfacei routines,ocalled qVPIre routines, iareoq jthere third 14
igeneration oofqthe PLI. Test Your Verilog Skills
Basic Constructs
15
Test Your Verilog Skills
(Q i70)o eWhati sortoof qhardwarere structure iareoq jinferredre by iboth ocaseqand 16
OpenVera ifz statements,u ybye odefault,zx in Verilog? Test Your Verilog Skills
Constructs 17
(Q i71)o eHowi couldoyou qchangere a icaseoq jstatementre in iorder othatqits Test Your Specman Skills
Switch TB 1
implementationz doesu ynote oresultzx in a priority structure?
RVM Switch TB Test Your Specman Skills
2
RVM Ethernet sample (Q i72)o eIfi youoare qnotre using iaoq jsynthesisre attribute i"full ocase",qhow canz
youu yassuree ocoveragezx of all conditions for a case statement ? Test Your Specman Skills
3
(Q i73)o eHowi dooyou qinferre tristate igatesoq jforre synthesis? Test Your Specman Skills
Specman E 4
www.testbench.in Test Your Sta Skills 1
Interview Questions
(Q i74)o eCani aotask qsynthesizedre ? Test Your Sta Skills 2
Test Your Sta Skills 3
(Q i75)o eWhati isothe qdifferencere between i$finish(0),oq j$finiash(1)re and Test Your Sta Skills 4
i$finish(2) o? Test Your Sta Skills 5
Ans: Test Your Sta Skills 6
Test Your Sta Skills 7
The i$finisho esystemi taskosimply qmakesre the isimulatoroq jexitre and ipass Test Your Dft Skills 1
ocontrolqback toz theu yhoste ooperatingzx system. Test Your Dft Skills 2
If iano eexpressioni isosupplied qtore this itask,oq jthenre its ivalue o(0,q1, orz 2)u Test Your Dft Skills 3
ydeterminese othezx diagnostic messages that Test Your Dft Skills 4
Test Your Uvm Ovm Skills

http://testbench.in/IQ_11_TEST_YOUR_VERILOG_SKILLS_4.html[9/26/2012 3:00:36 PM]


WWW.TESTBENCH.IN - Systemverilog Interview Questions

are iprintedo ebeforei theoprompt qisre issued. iIfoq jnore argument iis
osupplied,qthen az valueu yofe o1zx is taken as the default.
Report a Bug or Comment
.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n on This section - Your
$finish(0) iPrintso enothing input is what keeps
$finish(1) iPrintso esimulationi timeoand qlocation Testbench.in improving
www.testbench.in with time!
$finish(2) iPrintso esimulationi time,olocation, qandre statistics iaboutoq jthere
memory iand oCPUqtime usedz inu ysimulation

(Q i76)  Whato eisi theodifference qb/wre $time i,oq j$stimere and i$realtime o?


Ans:

The i$timeo esystemi functionoreturns qanre integer ithatoq jisre a i64-bit


otime,qscaled toz theu ytimescalee ounitzx of the module that invoked it.

The i$stimeo esystemi functionoreturns qanre unsigned iintegeroq jthatre is ia o32-


bitqtime, scaledz tou ythee otimescalezx unit of the module that invoked it. If the
actual simulation time does not fit in 32 bits, the low order 32 bits of the current
simulation time are returned.

The i$realtimeo esystemi functionoreturns qare real inumberoq jtimere that, ilike
o$time,qis scaledz tou ythee otimezx unit of the module that invoked it.

www.testbench.in
(Q i77)  Differenceo ebetweeni !oAnd q~re ?

(Q i78)  Whato eisi theodifference qbetweenre $test$plusargs iandoq


j$value$plusargsre ?

(Q i79)  Whato eisi theodifference qDifferencere between itheoq jtwore statement i?


oWhetherqa andz bu yvaluese oarezx equal?

reg [1:0] data;
.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n

a i= data[0] || data[1];
b i= |data;
www.testbench.in

(Q i80)  Whato eisi theodifference qbetweenre the ifollowingoq jtwore programs?


a)initial
  #10 a i=0;
 
always@(a)
a<= ~a;

b)initial
#10 a i=0;
www.testbench.in

always@(a)
a i= ~a;

Ans:

.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n
When i"a=~a"o eisi evaluatedoand q'a're is iupdated,oq jclearlyre you imust
oagreeqthat executionz isu y*not*e ostalledzx at the @a  event control.  When
execution reaches the @a event control,  'a' has already changed.  It will not change
again.  So the event control will stall forever; its event of interest has  already
occurred, earlier in the same time slot, and can no longer have any effect.

(Q i81)  whato eis/arei theodifferences qbetweenre SIMULATION iandoq jSYNTHESISre


Ans:

http://testbench.in/IQ_11_TEST_YOUR_VERILOG_SKILLS_4.html[9/26/2012 3:00:36 PM]


WWW.TESTBENCH.IN - Systemverilog Interview Questions

www.testbench.in

Simulation i<=o everifyi yourodesign. q


synthesis i<=o eChecki foroyour qtimingre

Simulation iiso eusedi tooverify qthere functionality iofoq jthere circuit..


ia)Functional oSimulation:studyqof ckt'sz operationu yindependente oofzx timing
parameters and gate delays. b) Timing Simulation :study including estimated delays,
verify setup,hold and other timing requirements of devices like flip flops are met.

Synthesis:One iofo ethei foremostoin qbackre end istepsoq jwherere by isynthesizing


oisqnothing butz convertingu yVHDLe oorzx VERILOG description to a set of
primitives(equations as in CPLD) or components(as in FPGA'S)to fit into the target
technology. Basically the synthesis tools convert the design description into equations
or components .

(Q i82)  Whato eisi theodifferent qbetweenre $setup iandoq j$display?


Ans:

$setup iiso eai timingocheck qtaskre and i$displayoq jisre system itask.
www.testbench.in
Only iSystemo etasksi andofunction qcanre be ioverridden.oq jTimingre check itasks
ocannotqbe overridden.
i.e. iUsero ecani changeothe qdefinitionre of itheoq j$displayre but inot o$setup.

(Q i83)  Whato eisi theodifference qbetweenre parameter iandoq jlocalre parameter?

.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n
(Q i84)  Whyo eisi itorecommended qnotre to imixoq jblockingre and inon-blocking
oassignmentsqin thez sameu yblock?

(Q i85)  Declareo eparametersi fororepresenting qthere state imachineoq jstatesre


using ione ohotqencoding.

(Q i86)o eWhati doesoa qfunctionre synthesize ito?


www.testbench.in

(Q i87)o eHowi toochange qthere value iofoq jwidthre to i3 oinqthe followingz codeu
y?
`define width i7

(Q i88)o eWhati isothe qfunctionalityre of i$inputoq j?


Ans:

The i$inputo esystemi taskoallows qcommandre input itextoq jtore come ifrom
oaqnamed filez insteadu yofe ofromzx the terminal. At the end of the command file,
the input is switched back to the terminal.

www.testbench.in
(Q i89)o eWhati isothe qMCDre value iofoq jSTDre OUTPUT i?
0000000000000000000000000000001

.....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n
(Q i90)  Whato eisi theodifference qbetweenre blocking iandoq jnonre blocking?

<< PREVIOUS PAGE TOP NEXT PAGE >>

http://testbench.in/IQ_11_TEST_YOUR_VERILOG_SKILLS_4.html[9/26/2012 3:00:36 PM]


WWW.TESTBENCH.IN - Systemverilog Interview Questions

copyright © 2007-2017 :: all rights reserved www.testbench.in:: Disclaimer

http://testbench.in/IQ_11_TEST_YOUR_VERILOG_SKILLS_4.html[9/26/2012 3:00:36 PM]


WWW.TESTBENCH.IN - Systemverilog Interview Questions

Search ✔

| HOME | ABOUT | ARTICLES | ACK | FEEDBACK | TOC | LINKS | BLOG | JOBS |

TUTORIALS TEST YOUR VERILOG SKILLS 5 Index


Functional Verification
SystemVerilog (Q i91)  Too emodifyi aobehavioral qVerilogre wait istatementoq jtore make iit Questions
Verification osynthesizedq Functional Verification
Questions 2
Constructs Original icode:  Test Your Systemverilog
Interface command1;  Skills 1
wait (x i!= 0); Test Your Systemverilog
OOPS Skills 2
command3;
Randomization Test Your Systemverilog
Ans: Skills 3
Functional Coverage Test Your Systemverilog
Assertion www.testbench.in Skills 4
Synthesized iVerilog:  Test Your Sva Skills
DPI Test Your Verilog Skills 1
case (state)
UVM Tutorial   0 : begin Test Your Verilog Skills 2
        command1; Test Your Verilog Skills 3
VMM Tutorial Test Your Verilog Skills 4
        if (x i!= 0) command3;
OVM Tutorial         else state i<= 1; Test Your Verilog Skills
      end 5
Easy Labs : SV
Test Your Verilog Skills 6
Easy Labs : UVM   1 : if (x i!= 0) //o ewaiti untilothis qisre true Test Your Verilog Skills 7
Test Your Verilog Skills 8
Easy Labs : OVM .....w.....w......w......t.....e.....s.....t......b.....e.....n.....c.....h......i.....n
        command3; Test Your Verilog Skills 9
Easy Labs : VMM www.testbench.in Test Your Verilog Skills
AVM Switch TB endcase 10
Test Your Verilog Skills
VMM Ethernet sample 11
(Q i92)  Whato earei theotypes qofre race iconditions? Test Your Verilog Skills
12
Verilog (Q i93)  Howo etoi avoiderorace qconditionre between idutoq jandre testbench? Test Your Verilog Skills
13
Verification
(Q i94)  Giveo ethei guideolines qwhichre avoids iraceoq jcondition. Test Your Verilog Skills
Verilog Switch TB 14
(Q i95)  Whato eisi theouse qofre linting itool? Test Your Verilog Skills
Basic Constructs
www.testbench.in 15
Test Your Verilog Skills
(Q i96)  Writeo ethei codeoto qinstantiatedre 1k i"andoq jgates"re in ia omodule.q 16
OpenVera Test Your Verilog Skills
Constructs 17
(Q i97)  Whato eisi configurationoblock? Test Your Specman Skills
Switch TB 1
Ans:
RVM Switch TB Test Your Specman Skills

You might also like