Blog_Insider

RTL Code

Top Visited Posts

Dec 17, 2015

File Handling in Verilog


The Verilog language has a rich set of system functions to write files ($fdisplay, $fwrite, etc.) but only reads files with a single, fixed format ($readmem). In the past if you wanted to read a file that was not in $readmem format, you would have to learn the Programming Language Interface (PLI) and the C language, write C code to read the file and pass values into Verilog, then debug the combined C and Verilog code. In addition, the Verilog is limited to 32 open files at a time.


To Write into a file -> 

module tb;

integer fl1;

initial begin
  fl1 = $fopen("file.xyz");
  
  forever  begin
    @(posedge clk)
    $fdisplay(fl1, "value to print = %h", value);
 end
 $fclose(fl1);
end 

endmodule


Read a file in Verilog.

file = $fopen("filename");

Reading data for per clock cycle ->  (In System Verilog)

integer data_file ; // file handler
integer scan_file ; // file handler
logic signed [21:0] capture_data;

`define NULL 0

 initial begin
   data_file = $fopen("data_file.txt", "r");
   if (data_file == `NULL) begin
     $display("data_file handle was NULL");
     $finish;
  end
end

always @(posedge clk) begin
  scan_file = $fscanf(data_file, "%d\n", capture_data);
  if (!$feof(data_file)) begin //use capture_data;
 end
end

NEXT

Dec 8, 2015

Selective Signal dumping in VPD VCS


Q. How to dump waveform using command line option in VCS ?


initial begin

$vcspluson();

end

If you are trying to dump VCD format, it is very obvious that this file occupies more space because it contains ASCII format (readable).

If you are trying to dump as VCS's own format called VPD, then you have the following control over that.
$vcdplusfile("my_dump.vpd");
$vcdpluson(<level>, <scope>);
ex: $vcdpluson(0, top.dut.sub);
<level> - default is 0. Dumps all the levels.

$vcdplusoff(<level>, <scope>);
ex: $vcdplusoff(2, top.dut.sub.sub_2);
<level> - default is 0. Switch offs the dump upto the specified
levels.

Q. How to dump waveform in VHDL ?

A. I am searching , if you know please put that in comments.


initial begin
$vcdpluson(0,tb);
$fsdbDumpvars;
$dumpfile("file.vcd");
$dumpvars();
end


Dumping of signal value changes in VCD format can be enabled in verilog by including the $dumpvars system task.

In addition to this method, VCS provides a way to enable VCD dumping at compile time.

This can be achieved by including the following switch  at compile time: "+vcs+dumpvars[+filename]"

For example, consider the following case:

cat test.v

module test;

reg clk;
initial begin
clk = 1'b0;
forever #5 clk = ~clk;
end

initial begin
#100 $finish;
end
endmodule


vcs test.v -V -l logfile -R +vcs+dumpvars+test.vcd

The $dumpvars system task is not specified in the verilog code above. Instead, VCD dumping is enabled with the addition of the compile time switch "+vcs+dumpvars+test.vpd".

The result is equivalent to calling the following system tasks:

$dumpvars;
$dumpfile("test.vpd");

If the filename is not specified (ie. only +vcs+dumpvars is used), then the filename defaults to "verilog.dump".

If both the system task ($dumpvars) and the compile-time switch (+vcs+dumpvars) are specified, then the compile-time switch takes precedence.

No additional verilog code is needed when enabling VCD dumping using the compile time switch.

Put your comments ... if you like it.

Thanks

Dec 4, 2015

Timescale in Verilog


Time Scale And Time Precision:

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.

For example : `timescale 1 ns / 100 ps means

time values to be read as ns and to be rounded to the nearest 100 ps.
If timescale is omitted, there is a default time scale.

The following examples demonstrate how the time scale and time precision effect $stime, #delay and toggling in waveform.

`timescale 1ns/1ps

means ur time scale is ns with resolution OR least count of 1ps

#1 ; // 1ns delay

#0.001; // 0.001 ns this is the minimum delay you can have with this time scale!

#0.0001; // this will give 0 ns delay!!

Hope these example helps you understand the verilog timescale!!

let's consider

`timescale 1ns/1ps

reg set;
parameter d = 1.55
initial
begin
#d set = 0;
#d set = l;
end
endmodule

The `timescale tells the system to use 1 ns for all reporting and internally use 1 ps for resolution of time in this part of design. Thus, the value for parameter d is scaled to a delay of 1.55 ns. Had we used timescale directive `timescale 10ns/1ns, 1.55 would mean 15.5 or 16 ns. The first part of `time-scale gives the time-units and the second part gives the time-precision.


Jul 3, 2015

Key Points in Mixed Signal Design Verification


Introduction:

A Mixed Signal Interface could be a high speed interface where data is transferred between two devices through a medium. Transmitting data is not big issue but receiving data contribute major part of its performance. Key points/block for high speed and high performance mixed signals are described in below sections.



Major Blocks in Mixed Signal Design which decides the performance of design:


A. CDR  (Clock Data Recovery)
CDR is major block of receiver, it is Clock and Data recovery circuit. It is very important the behavioral model of CDR must be accurate to measure the overall performance.


B .DFE  (Decision Feedback Equalizer)
Decision Feedback Equalizer is also a major part of mixed signal design if you are talking about performance. This block is useful if data rate is more than 10 Gbps. This block remove the ISI from incoming signal. This is one of the most complicated design in high speed mixed signal design.


C. TX Driver
When you are driving signal on physical medium, then this block play a major role in it. This block drive signal with perfect strength, voltage level, and other factor which are dependent on physical medium, for example 12inch cable , 24 inch cable. It is called channel.

Each channel is having it’s own properties and Tx driver has to adapt those properties to transmit signal with minimum loss and adding noise in that signal.


Key Points in Mixed Signal Verification:

1. Assertion
Assertion play a major role in mixes signal verification, especially on the analog/digital interface. Most of the signals going into analog domain, are asynchronous in nature but there are dependencies with other signals. One should understand the interface carefully and write assertion based on the behavior of the signal.


2. BFM:
BFM plays a critical role to verify mixed signal design. To verify the mixed signal design , behavioral model of analog block must be close be actual behavioral of block.

BFM part can be divided in 2 parts. 


A. Functional Simulation  
Functional simulation will have 1-bit ports as physical medium and this can be tested with CDR BFM to receive data, no noise injection or ISI will be seen on signal as it is 1-bit signal. Here one can verify the Protocol but not performance.

B. Behavioral Simulation
In System Verilog, a ports can be define as real port , So physical interface ( Tx and Rx serial lines) can be instantiate as real ports in TB. This should support inside design also.


On TB having real ports, one can write some BFM which can inject noise, and ability to distort the signal. Noise injection and distortion should be controllable in test bench.

This part of functional simulation is very important as it measure the performance of design. The behavior model (BFM) can have algorithm to inject noise into incoming signal (on Rx serial line of design). Basically there are adaptation and calibration algorithm in mixed signal design which are very much rely on incoming signal on real port. In side analog block, there is serial to parallel conversion, where Rx clock from CDR block is used.


Please feel free to contact me if you have any doubts or questions. 
Rahul J

Jun 9, 2015

Lockup Latches



Q. What is Lockup Latch ?
A. A lockup latch is used to prevent data corruption caused by overwriting of new data over the present data before the clock edge occurs. i.e there is a potential problem of data coming early and overwriting the present actual which has to be fed.

In other words ,
Lockup latches are nothing more than transparent latches. You use them to connect two scan-storage elements in a scan chain in which excessive clock skew exists.



 Let a circuit contains two flip-flops. Flip-flop 1 represents the end of the scan chain that contains only elements that are in the clk1 clock domain. Flip-flop 2 represents the beginning of the scan chain that contains only elements that are in the clk2 clock domain. and these flip-flops have multiplexed inputs. The inputs of these flip-flops represent the scan inputs of the multiplexers. The latch has an active-high enable, which becomes transparent only when clk1 goes low and effectively adds a half clock of hold time to the output of flip-flop 1. In this figure, you assume that the system synchronously asserts clk1 and clk2, which would be the normal case during scan-mode operation. Although the clocks synchronously assert, some amount of clock skew between them still exists because they come from different clock trees.




lockup latches connect scan chains from different clock domains. However, you can just as easily use these latches to connect scan chains from various blocks within a chip that, although on the same scan chain, are physically remote from each other on the die. You want to make the latch transparent during the inactive part of the clock. For example, both flip-flops trigger on the rising edge of the clock. Therefore, you want to make the lockup latch transparent during the low period of the clock. If the flip-flops trigger on the falling edge of the clock, you want the latch to be transparent when the clock is high.


http://www.edn.com/article/CA46603.html




www.eetimes.com/document.asp?doc_id=1225378







During capture, design is in functional mode, hold time violation is solved by STA team during Functional timing closure.

Verilog code for parity checker (even parity/odd parity)



Verilog code for parity Checker -



In the case of even parity, the number of bits whose value is 1 in a given set are counted. If that total is odd, the parity bit value is set to 1, making the total count of 1's in the set an even number. If the count of ones in a given set of bits is already even, the parity bit's value remains 0.


In the case of odd parity, the situation is reversed. Instead, if the sum of bits with a value of 1 is odd, the parity bit's value is set to zero. And if the sum of bits with a value of 1 is even, the parity bit value is set to 1, making the total count of 1's in the set an odd number.

Odd Parity

1'b0  -  odd 1's
1'b1 -   even 1's

For Odd parity , if  input data is 1'b0 then odd parity should be 1'b1 , to make number of 1's odd , and if it is 1'b1 then odd parity should be 1'b0.

below is the code for it -

reg parity_chk_st;

always @(posedge clk or negedge rstn) begin
 if(!rstn)
    parity_chk_st <= 1'b0;
 else
   parity_chk_st <= parity_check;

assign parity_check =  parity_ch_st ^ parity_check;



Even Parity
1'b0  -> 1's are even
1'b1 -> 1's are odd , 1 to make one's even.

Jun 8, 2015

Unateness-> Positive Unate and Negative Unate



Each cell in design will have timing arcs, there are different types of arcs present in design. For example, for sequential cell , timing arc will be from clock to Q , for Combi logic, timing arc will be from input to output.
Each timing arc has a timing sense ,  with this output of cells changes with different types of transition happens on input. Position unate and negative unate is related to transition on timing arcs.

A Positive Unate is , rising transition on input causes output to rise and falling transition on input causes output to fall , a simple example is given below.




A Negative Unate is, rising transition on input causes output to fall , and falling transition on input causes output to rise , a simple example is given below.




A Non Unate is , output transition can not be determined from either on the inputs  , for example a XOR gate where output of XOR depend on both inputs  .. 



Jan 12, 2015

GVIM Help




Search for 2 word in a line ->

/\<\(red\|green\|blue\)\>


.vimrc -> 



"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => General
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Sets how many lines of history VIM has to remember
set history=700

" Enable filetype plugins
filetype plugin on
filetype indent on

" Set to auto read when a file is changed from the outside
set autoread

" With a map leader it's possible to do extra key combinations
" like <leader>w saves the current file
let mapleader = ","
let g:mapleader = ","

" Fast saving
nmap <leader>w :w!<cr>


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => VIM user interface
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Set 7 lines to the cursor - when moving vertically using j/k
set so=7

" Turn on the WiLd menu
set wildmenu

" Ignore compiled files
set wildignore=*.o,*~,*.pyc

"Always show current position
set ruler

" Height of the command bar
set cmdheight=2

" A buffer becomes hidden when it is abandoned
set hid

" Configure backspace so it acts as it should act
set backspace=eol,start,indent
set whichwrap+=<,>,h,l

" Ignore case when searching
set ignorecase

" When searching try to be smart about cases 
set smartcase

" Highlight search results
set hlsearch

" Makes search act like search in modern browsers
set incsearch 

" Don't redraw while executing macros (good performance config)
set lazyredraw 

" For regular expressions turn magic on
set magic

" Show matching brackets when text indicator is over them
set showmatch 
" How many tenths of a second to blink when matching brackets
set mat=2

" No annoying sound on errors
set noerrorbells
set novisualbell
set t_vb=
set tm=500


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Colors and Fonts
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Enable syntax highlighting
syntax enable 

colorscheme desert
set background=dark

" Set extra options when running in GUI mode
if has("gui_running")
    set guioptions-=T
    set guioptions+=e
    set t_Co=256
    set guitablabel=%M\ %t
endif

" Set utf8 as standard encoding and en_US as the standard language
set encoding=utf8

" Use Unix as the standard file type
set ffs=unix,dos,mac


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Files, backups and undo
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Turn backup off, since most stuff is in SVN, git et.c anyway...
set nobackup
set nowb
set noswapfile


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Text, tab and indent related
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Use spaces instead of tabs
set expandtab

" Be smart when using tabs ;)
set smarttab

" 1 tab == 4 spaces
set shiftwidth=4
set tabstop=4

" Linebreak on 500 characters
set lbr
set tw=500

set ai "Auto indent
set si "Smart indent
set wrap "Wrap lines


""""""""""""""""""""""""""""""
" => Visual mode related
""""""""""""""""""""""""""""""
" Visual mode pressing * or # searches for the current selection
" Super useful! From an idea by Michael Naumann
vnoremap <silent> * :call VisualSelection('f')<CR>
vnoremap <silent> # :call VisualSelection('b')<CR>


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Moving around, tabs, windows and buffers
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Treat long lines as break lines (useful when moving around in them)
map j gj
map k gk

" Map <Space> to / (search) and Ctrl-<Space> to ? (backwards search)
map <space> /
map <c-space> ?

" Disable highlight when <leader><cr> is pressed
map <silent> <leader><cr> :noh<cr>

" Smart way to move between windows
map <C-j> <C-W>j
map <C-k> <C-W>k
map <C-h> <C-W>h
map <C-l> <C-W>l

" Close the current buffer
map <leader>bd :Bclose<cr>

" Close all the buffers
map <leader>ba :1,1000 bd!<cr>

" Useful mappings for managing tabs
map <leader>tn :tabnew<cr>
map <leader>to :tabonly<cr>
map <leader>tc :tabclose<cr>
map <leader>tm :tabmove 

" Opens a new tab with the current buffer's path
" Super useful when editing files in the same directory
map <leader>te :tabedit <c-r>=expand("%:p:h")<cr>/

" Switch CWD to the directory of the open buffer
map <leader>cd :cd %:p:h<cr>:pwd<cr>

" Specify the behavior when switching between buffers 
try
  set switchbuf=useopen,usetab,newtab
  set stal=2
catch
endtry

" Return to last edit position when opening files (You want this!)
autocmd BufReadPost *
     \ if line("'\"") > 0 && line("'\"") <= line("$") |
     \   exe "normal! g`\"" |
     \ endif
" Remember info about open buffers on close
set viminfo^=%


""""""""""""""""""""""""""""""
" => Status line
""""""""""""""""""""""""""""""
" Always show the status line
set laststatus=2

" Format the status line
set statusline=\ %{HasPaste()}%F%m%r%h\ %w\ \ CWD:\ %r%{getcwd()}%h\ \ \ Line:\ %l


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Editing mappings
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Remap VIM 0 to first non-blank character
map 0 ^

" Move a line of text using ALT+[jk] or Comamnd+[jk] on mac
nmap <M-j> mz:m+<cr>`z
nmap <M-k> mz:m-2<cr>`z
vmap <M-j> :m'>+<cr>`<my`>mzgv`yo`z
vmap <M-k> :m'<-2<cr>`>my`<mzgv`yo`z

if has("mac") || has("macunix")
  nmap <D-j> <M-j>
  nmap <D-k> <M-k>
  vmap <D-j> <M-j>
  vmap <D-k> <M-k>
endif

" Delete trailing white space on save, useful for Python and CoffeeScript ;)
func! DeleteTrailingWS()
  exe "normal mz"
  %s/\s\+$//ge
  exe "normal `z"
endfunc
autocmd BufWrite *.py :call DeleteTrailingWS()
autocmd BufWrite *.coffee :call DeleteTrailingWS()


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => vimgrep searching and cope displaying
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" When you press gv you vimgrep after the selected text
vnoremap <silent> gv :call VisualSelection('gv')<CR>

" Open vimgrep and put the cursor in the right position
map <leader>g :vimgrep // **/*.<left><left><left><left><left><left><left>

" Vimgreps in the current file
map <leader><space> :vimgrep // <C-R>%<C-A><right><right><right><right><right><right><right><right><right>

" When you press <leader>r you can search and replace the selected text
vnoremap <silent> <leader>r :call VisualSelection('replace')<CR>

" Do :help cope if you are unsure what cope is. It's super useful!
"
" When you search with vimgrep, display your results in cope by doing:
"   <leader>cc
"
" To go to the next search result do:
"   <leader>n
"
" To go to the previous search results do:
"   <leader>p
"
map <leader>cc :botright cope<cr>
map <leader>co ggVGy:tabnew<cr>:set syntax=qf<cr>pgg
map <leader>n :cn<cr>
map <leader>p :cp<cr>


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Spell checking
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Pressing ,ss will toggle and untoggle spell checking
map <leader>ss :setlocal spell!<cr>

" Shortcuts using <leader>
map <leader>sn ]s
map <leader>sp [s
map <leader>sa zg
map <leader>s? z=


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Misc
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Remove the Windows ^M - when the encodings gets messed up
noremap <Leader>m mmHmt:%s/<C-V><cr>//ge<cr>'tzt'm

" Quickly open a buffer for scripbble
map <leader>q :e ~/buffer<cr>

" Toggle paste mode on and off
map <leader>pp :setlocal paste!<cr>



"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Helper functions
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
function! CmdLine(str)
    exe "menu Foo.Bar :" . a:str
    emenu Foo.Bar
    unmenu Foo
endfunction 

function! VisualSelection(direction) range
    let l:saved_reg = @"
    execute "normal! vgvy"

    let l:pattern = escape(@", '\\/.*$^~[]')
    let l:pattern = substitute(l:pattern, "\n$", "", "")

    if a:direction == 'b'
        execute "normal ?" . l:pattern . "^M"
    elseif a:direction == 'gv'
        call CmdLine("vimgrep " . '/'. l:pattern . '/' . ' **/*.')
    elseif a:direction == 'replace'
        call CmdLine("%s" . '/'. l:pattern . '/')
    elseif a:direction == 'f'
        execute "normal /" . l:pattern . "^M"
    endif

    let @/ = l:pattern
    let @" = l:saved_reg
endfunction


" Returns true if paste mode is enabled
function! HasPaste()
    if &paste
        return 'PASTE MODE  '
    en
    return ''
endfunction

" Don't close window, when deleting a buffer
command! Bclose call <SID>BufcloseCloseIt()
function! <SID>BufcloseCloseIt()
   let l:currentBufNum = bufnr("%")
   let l:alternateBufNum = bufnr("#")

   if buflisted(l:alternateBufNum)
     buffer #
   else
     bnext
   endif

   if bufnr("%") == l:currentBufNum
     new
   endif

   if buflisted(l:currentBufNum)
     execute("bdelete! ".l:currentBufNum)
   endif
endfunction


Removing new line at the end of line - >
Certainly. Vim recognizes the \n character as a newline, so you can just search and replace. In command mode type::
"%s/\n/"