Showing posts with label digital design. Show all posts
Showing posts with label digital design. Show all posts

Feb 23, 2025

Cyclic Redundancy Check (CRC) Generator - RTL Code



A Cyclic Redundancy Check (CRC) is a popular error-detection technique used in communication protocols and file storage systems to check for data integrity. It involves the use of a polynomial division method to generate a checksum value (CRC code) based on the input data, which can later be used to detect any alterations in the transmitted data.

To implement a CRC generator in RTL (Register-Transfer Level), we need to design a hardware module that computes the CRC value for a given input. Below is an example of how you can write Verilog RTL code for a CRC-16-CCITT-FALSE generator. This CRC uses a 16-bit polynomial, 0x11021, commonly used in communications.

Verilog Code for CRC-16-CCITT-FALSE Generator:

module crc16_ccitt_false(
    input clk,                    // Clock signal
    input reset,                  // Reset signal
    input [7:0] data_in,          // 8-bit input data
    input data_valid,             // Data valid signal to indicate when data_in is valid
    output reg [15:0] crc_out     // 16-bit CRC output
);

    // Polynomial: 0x11021 (x^16 + x^12 + x^5 + 1)
    reg [15:0] crc_reg;            // Internal CRC register

    // CRC shift register calculation
    always @(posedge clk or posedge reset) begin
        if (reset) begin
            // Reset the CRC register to initial value 16'hFFFF
            crc_reg <= 16'hFFFF;
        end
        else if (data_valid) begin
            // Perform CRC calculation for each byte of data
            crc_reg <= crc_reg ^ {8'b0, data_in};  // XOR input data with CRC register
            // Perform polynomial division (shift and XOR with polynomial if MSB is 1)
            for (int i = 0; i < 8; i = i + 1) begin
                if (crc_reg[15] == 1) begin
                    crc_reg = {crc_reg[14:0], 1'b0} ^ 16'h11021;
                end else begin
                    crc_reg = {crc_reg[14:0], 1'b0};
                end
            end
        end
    end

    // Assign the calculated CRC value to the output
    always @(posedge clk or posedge reset) begin
        if (reset)
            crc_out <= 16'hFFFF;  // Reset CRC to 0xFFFF
        else if (data_valid)
            crc_out <= crc_reg;   // Update CRC output when data is valid
    end

endmodule

Explanation of the Code:

  1. Input/Output Ports:

    • clk: Clock input that synchronizes the module.
    • reset: Asynchronous reset signal that initializes the CRC value to 0xFFFF.
    • data_in: 8-bit input data that will be processed in the CRC calculation.
    • data_valid: A signal that indicates when valid data is present on data_in.
    • crc_out: The 16-bit CRC output, which is the result of the CRC calculation.
  2. Internal CRC Register (crc_reg):

    • The internal CRC register holds the intermediate and final CRC value, which is updated as data is processed.
  3. CRC Calculation (Core Logic):

    • The CRC generator uses a polynomial, specifically 0x11021 (x^16 + x^12 + x^5 + 1), to perform the error-checking.
    • On every valid data input (data_valid), the CRC register is XORed with the incoming data byte (data_in).
    • Then, a bit-shifting loop (for loop) is applied where the bits are shifted, and if the most significant bit (MSB) is 1, the polynomial 0x11021 is XORed with the CRC register. This simulates polynomial division.
  4. Reset and Output Assignment:

    • On a reset, the CRC register is initialized to 0xFFFF.
    • After each valid data cycle, the CRC output is updated with the value in the CRC register.

Key Points:

  • Polynomial: The polynomial used here is 0x11021, which is common in CRC-16-CCITT-FALSE. You may modify this polynomial to suit your specific CRC standard (e.g., CRC-16-ANSI, CRC-32, etc.).
  • Data Processing: Data is processed in 8-bit chunks, typical for many data transmission systems.
  • CRC Register Size: In this example, a 16-bit CRC register (crc_reg) is used. Adjust the register size based on the CRC width for your application (e.g., 32 bits for CRC-32).
  • Reset Behavior: The reset signal initializes the CRC to 0xFFFF, which is a common practice for CRC-16-CCITT-FALSE.

Simulation and Testing:

To verify the functionality of this module, you can write a simple testbench to simulate the CRC generator with some input data:

module tb_crc16_ccitt_false;

    reg clk;
    reg reset;
    reg [7:0] data_in;
    reg data_valid;
    wire [15:0] crc_out;

    // Instantiate the CRC16-CCITT-FALSE module
    crc16_ccitt_false crc_gen (
        .clk(clk),
        .reset(reset),
        .data_in(data_in),
        .data_valid(data_valid),
        .crc_out(crc_out)
    );

    // Clock generation
    always begin
        clk = 1'b0;
        #5 clk = 1'b1;
        #5;
    end

    // Test stimulus
    initial begin
        // Initialize signals
        reset = 1;
        data_in = 8'h00;
        data_valid = 0;
        #10;

        reset = 0;
        data_in = 8'hA5;  // Example input data
        data_valid = 1;
        #10;

        data_in = 8'h5A;  // Next byte of data
        #10;

        data_valid = 0;
        #10;

        // End of simulation
        $stop;
    end

endmodule

Conclusion:

This Verilog RTL code implements a basic CRC-16-CCITT-FALSE generator. It takes in 8-bit data chunks and computes the 16-bit CRC checksum using a standard polynomial division algorithm. The code can be adapted to different CRC standards (e.g., CRC-32) by modifying the polynomial and register size as necessary.

Sep 29, 2017

Synchronizers list dump using SpyGlass Tool



This section will tell you how to dump the list of sync cell using spyglass tool.

There are complexities and different settings which depends on design to design, some fine tuning may require to dump the Synchronizer list.


Spyglass give a lot of options which vary design to design, below are the common settings you can use in spyglass project file.

<Design1.prj>

you can either define the custom goal and dump the sync cell list or you can add options/parameter in standard goal in spyglass prj file.

defining custom goal ->

define_goal <custom_goal>  -policy {clock-reset} {

## only 4 rules required to dump the synchronizers , this will not dump the reset sync cell.
set_goal_option rules { Ac_unsync01 Ac_unsync02 Ac_sync01 Ac_sync02}

#SynchInfo will be the file where spyglass will dump all the sync flop
# moresimple will be dump if defined below.
set_goal_option report { SynchInfo moresimple}

## wild card can be use here , this info tool will use to identify the sync cell , this can be any standard pattern.
set_parameter synchronize_cells "*sync1*, *sync2*"

## Same as above but will recognize the reset sync cell.
set_parameter reset_synchronize_cells "*rst_sync*"

## This is important, this will enable tool to dump the sync list. 
set_parameter dump_sync_info detailed

## This is optional and can be used if you have static mux before the sync cell.
set_parameter allow_combo_logic yes

## This is optional and required if you data signal is coming from different source and then going to sync cell. All source must be quasi-static and should not change simultaneously.
set_parameter allow_merged_qualifier yes

## This parameters can be used , it will reduce the pessimism and will dump all the flops where tool is finding the clock domain crossing.
set_parameter enable_and_sync yes
set_parameter cdc_reduce_pessimism all
set_parameter strict_sync_check yes
set_parameter enable_debug_data yes
}

Hope this information is useful to you , comment or email me if you need any support on this.

Table of Contents

Thanks for reading my blog.
Rahul J

Dec 28, 2016

Verilog Code for Round Robin Algorithm


Round Robin algorithm details :
Round Robin algorithm Verilog code :

What is Round Robin algorithm ?

Round-robin (RR) is one of the algorithms employed by process and network schedulers in computing.As the term is generally used, time slices (also known as time quanta) are assigned to each process in equal portions and in circular order, handling all processes without priority (also known as cyclic executive). Round-robin scheduling is simple, easy to implement, and starvation-free. Round-robin scheduling can also be applied to other scheduling problems, such as data packet scheduling in computer networks. It is an operating system concept.



Below is the diagram.




In the real situation, we can have a modified version of round robin.
Below feature can be include while designing a arbiter using round robin.
  1. If there are no requests,  which ever device/master send request, access will be given in next clock cycle.
  2. For some master, priority can be set. 
  3. Programmable delay to get the access if request is present. 

Below is the block diagram for round robin algorithm with 4 request and 4 grant.




Counter will be controlled by a state machine.




Verilog Code for Round Robin Algorithm



Below are the simulation results




In the same way, request/grant can be increased to n number.

Ref - https://en.wikipedia.org/wiki/Round-robin_scheduling

Dec 7, 2016

Asynchronous FIFO with Programmable Depth


Asynchronous FIFO Design
Asynchronous FIFO Verilog Code
Asynchronous FIFO with block diagram and verilog Code.

This code is written in Verilog 2001.


Here is the block diagram for Asynchronous FIFO.



Verilog Code for Async FIFO



TestBench for Asynchronous FIFO 



Waveform Snapshot -:


Table of Contents


Nov 17, 2016

Verilog Code for FIR Filter


FIR filters are is widely used in different applications such as biomedical, communication and control due to its easily implementation, stability and best performance. Its simplicity makes it attractive for many applications where it is need to minimize computational requirements.

Below is the code for FIR Filter , Any comments/doubts are welcome.

Please contact me if you want a soft copy of the module.

Block diagram :


F is the flopped stage and C1/C2/C3/C4/C5  are the coefficient. One bug adder will required to add all the feedback.

Below is the verilog code for FIR filter with test bench.
-----------

module fir_filter (  a, b, clk, rstn) ;

input signed [31:0] a;
output signed [31:0] b;
input clk;
input rstn;


parameter avg = 20;
parameter  c1 = avg*(8'h1) ;
parameter  c2 = avg*(8'h1) ;
parameter  c3 = avg*(8'h1) ;
parameter  c4 = avg*(8'h1) ;
parameter  c5 = avg*(8'h1) ;


reg signed [31:0] f1 ;
reg signed [31:0] f2 ;
reg signed [31:0] f3 ;
reg signed [31:0] f4 ;
reg signed [31:0] f5 ;


always @(posedge clk or negedge rstn) begin
  if(!rstn)  begin
    f1 <= 32'b0;
    f2 <= 32'b0;
    f3 <= 32'b0;
    f4 <= 32'b0;
    f5 <= 32'b0;
  end
  else begin
    f1 <= a;
    f2 <= f1;
    f3 <= f2;
    f4 <= f3;
    f5 <= f4;
  end
end


assign b = (f1*c1 + f2*c2 + f3*c3 + f4*c4 + f5*c5)/(5*avg) ;


endmodule

module tb_fir;

reg [31:0] in_signal;
reg clk =0;
reg rstn =0;
reg en =0;
wire [31:0] out_signal;

always #5 clk = ~clk;

integer cnt=0;

always @(clk) cnt = cnt +1 ;

always @(*) begin
   if(en ==1 && cnt[2:0] == 3'b111) begin
   #1;
  in_signal = cnt[7:0];
  end
  end

fir_filter dut (
.a(in_signal),
.b(out_signal),
.clk(clk),
.rstn(rstn));

initial begin
  rstn =0 ;
  #100;
  rstn = 1;
  en =1;
  #10000 ;
  $finish;
end

initial
 $monitor("Input signal = %d , out_signal = %d", in_signal, out_signal);

initial begin
  $recordfile("test.trn");
  $recordvars();
  end

endmodule

------------------------- verilog code end -------------------- 

Downloads the verilog file here. 

Sep 9, 2016

Error Correction and Detection - SECDEC


Interview Questions on Error Correction and Detection  ->

1. What is the difference between ECC and CRC ?

2. What are the different technique to detect Error ?

3. Where ECC is useful in design ?

4. How many bits can recover by using ECC ?

5. Why do you need error detection?
Ans: As the signal is transmitted through a media, the signal gets corrupted because of noise and distortion. In other words, the media is not reliable. To achieve a reliable communication through this unreliable media, there is need for detecting the error in the signal so that suitable mechanism can be devised to take corrective actions.

5. Explain different types of Errors?
Ans: The errors can be divided into two types: Single-bit error and Burst error.
• Single-bit Error The term single-bit error means that only one bit of given data unit (such as a byte, character, or data unit) is changed from 1 to 0 or from 0 to 1.
• Burst Error The term burst error means that two or more bits in the data unit have changed from 0 to 1 or vice-versa. Note that burst error doesn’t necessary means that error occurs in consecutive bits.

6. Explain the use of parity check for error detection?
Ans: In the Parity Check error detection scheme, a parity bit is added to the end of a block of data. The value of the bit is selected so that the character has an even number of 1s (even parity) or an odd number of 1s (odd parity). For odd parity check, the receiver examines the received character and if the total number of 1s is odd, then it assumes that no error has occurred. If any one bit (or any odd number of bits) is erroneously inverted during transmission, then the receiver will detect an error.

7. What are the different types of errors detected by parity check?
Ans: If one bit (or odd number of bits) gets inverted during transmission, then parity check will detect an error. In other words, only odd numbers of errors are detected by parity check. But, if two (or even number) of bits get inverted, and then the error remains undetected.

8. How to detect two error bits ?  you can detect single error bit and correct it by using hamming distance , but how will you detect 2 error bits ?

9. What is hamming code distance ?

10. How robust is 2 bit error detection ?

11. How to deal in SECDEC if there is error on overall parity bit ?

12. What are the advantages and disadvantages to use ECC ?
Advantages -:
ECC protects against undetected memory data corruption, and is used in computers where such corruption is unacceptable, for example in some scientific and financial computing applications, or in file servers. ECC also reduces the number of crashes, particularly unacceptable in multi-user server applications and maximum-availability systems

Disadvantages
1. ECC memory usually involves a higher price when compared to non-ECC memory, due to additional hardware required for producing ECC memory modules, and due to lower production volumes of ECC memory and associated system hardware. Motherboards, chipsets and processors that support ECC may also be more expensive
2. It may lower the overall performance of the system , If ECC block is combinational and timings are able to meet then it will not introduce the latency in system , otherwise minimum 1 clock cycle latency will be introduced by ECC.

There are many more questions on ECC, for single bit error correction, it has 100%  error correctable , but when there are more than 1-bit error in data then hamming code turned into worst. different conditions are explained at the bottom.

A SEC-DED Code
For many applications a single error correcting code would be considered unsatisfactory, because it accepts all blocks received. A SEC-DED code seems safer, and it is the level of correction and detection most often used in computer memories.

Different (but equivalent) Hamming codes
Given a specific number N of check bits, there are 2N equivalent Hamming codes that can be constructed by arbitrarily choosing each check bit to have either "even" or "odd" parity within its group of data bits. As long as the encoder and the decoder use the same definitions for the check bits, all of the properties of the Hamming code are preserved.
Sometimes it's useful to define the check bits so that an encoded word of all-zeros or all-ones is always detected as an error.


What happens when multiple bits get flipped in a Hamming codeword
Multible bit errors in a Hamming code cause trouble. Two bit errors will always be detected as an error, but the wrong bit will get flipped by the correction logic, resulting in gibberish. If there are more than two bits in error, the received codeword may appear to be a valid one (but different from the original), which means that the error may or may not be detected.
In any case, the error-correcting logic can't tell the difference between single bit errors and multiple bit errors, and so the corrected output can't be relied on.


Extended Hamming Code
Extending a Hamming code to detect double-bit errors
Any single-error correcting Hamming code can be extended to reliably detect double bit errors by adding one more parity bit over the entire encoded word. This type of code is called a SECDED (single-error correcting, double-error detecting) code. It can always distinguish a double bit error from a single bit error, and it detects more types of multiple bit errors than a bare Hamming code does.
It works like this: All valid code words are (a minimum of) Hamming distance 3 apart. The "Hamming distance" between two words is defined as the number of bits in corresponding positions that are different. Any single-bit error is distance one from a valid word, and the correction algorithm converts the received word to the nearest valid one.
If a double error occurs, the parity of the word is not affected, but the correction algorithm still corrects the received word, which is distance two from the original valid word, but distance one from some other valid (but wrong) word. It does this by flipping one bit, which may or may not be one of the erroneous bits. Now the word has either one or three bits flipped, and the original double error is now detected by the parity checker.
Note that this works even when the parity bit itself is involved in a single-bit or double-bit error. It isn't hard to work out all the combinations.

Table of Contents

Jun 24, 2016

Digital Design for Beginners and Professionals

VLSI Interview Questions ->>>



First Question before starting anything on VLSI or Digital design ....


Are you new to semiconductor ?   
If your answer is  "No" then there is lot of scope to learn in semiconductor which really depends on your interest. Sometime it happens , you have to work on those module which you do not want , but it happens and you should take it in easy and with positive attitude. Even with that work , you can learn a lot of things.

But for above question , if your answer is "Yes" then you need to go though the basic VLSI where CMOS/ npn/ pnp transistor comes in picture. learn how semiconductor device work.

There are few basic skills which are expected from a Digital designer or verification engineer. 




For Design - 



1. Digital fundamentals 
2. Knowledge on building micro-architecture
3. RTL coding , knowledge of any HDL (Verilog or VHDL) 
4. Tool knowledge like ModelSim, Questa, Cadence simulator , VCS 

There are many ways to improve design flow and turn around time to come up with updated and strong design. please see below few points. 

1. If  design is already ported , then one should think of optimizing the logic and should think to reduce gate count with same functionality.
2. If lint and cdc have not run , then work on lint and cdc environment and pass your design through lint and cdc. If you run it at block level, it will be fast and fixing time will be very less, but one should not forget to run at top level, there could be human error while integrating the different blocks .
  
For Verification - 

Today, system verilog is getting used in verification, this SVL giving flexibility to users to drive random stimulus, reusable components and giving a very good command to verify DUT. 

But still a verification engineer should be having good knowledge of design which he/she verifying and always try to think to crack the design. Most of designs are now porting kind of design which having verification environment also and it is very difficult to find a  bug in such design until or unless you are very good verification engineer but there are always a scope of improvement. 

Verification engineer can think of below points.
1. Implementing more checkers (automated way)
2. Coverage analysis on DUT, if it is already done then try to achieve 100% coverage with    waivers.
3. Assertion implementation 
4. Feature list documentation, using that they can generate a top level graph for management to measure the progress,  we have Questa now having verification management and able to generate such kind of reports to management. 
5. Try to make environment in more automated way
6. One thing which is really really very difficult to implement in environment , is model the interface timing such that interface looks like a real silicon. This will not help in functional simulation but will help in gate level simulation. 



Debugging simulation is also in-built art which comes naturally being a engineer.
I have put some points in below link. 

How To debug a simulation


Other Topics -
Contents
Refreshing your brain with Verilog 
Digital Design of Hybrid Memory Cube
Correct way of  Digital design RTL Coding
Clock Gating Circuits
Digital Design Interview Question
Knowledge on Verification


More are yet to come , all comments and suggestions are welcome and will help to put information here.  
Table of Contents