Easy Tutorial
❮ Android Tutorial Colorfilterl2 Html5 Canvas Eccharts ❯

6.4 Verilog Competition and Hazard

Classification Verilog Tutorial

Keywords: Competition, Hazard, Writing Standards

Causes of Occurrence

In digital circuits, signal transmission and state transitions have certain delays.

Due to the presence of the inverter circuit, the signal A' reaches the AND gate input later than signal A, which may cause the final output F of the AND gate to have interference pulses. As shown in the diagram below.

In actual hardware circuits, as long as there are different delays at the input of the gate circuit, competition and hazard may occur.

For example, in a simple AND gate, the input signal sources may not come from the same signal transformation, and due to hardware technology and the presence of other delay circuits, competition and hazard may also occur, as shown in the diagram below.

Judgment Methods

Algebraic Method

In the logical expression, keep one variable fixed and replace the remaining variables with 0 or 1. If the final logical expression can be simplified to:

Y = A + A'

or

Y = A · A'

then it can be determined that this logic has competition and hazard.

For example, the logical expression Y = AB + A'C, when B=C=1, can be simplified to Y = A + A'. Obviously, the change of state A will inevitably cause the circuit to have competition and hazard.

Karnaugh Map Method

If there are two Karnaugh circles that are tangent to each other and there is no other Karnaugh circle surrounding the tangent point, competition and hazard may occur.

For example, the left diagram below has competition and hazard, while the right one does not.

The Karnaugh map is essentially an analysis of the logical expression, but it allows for a visual judgment.

For example, the logical expression in the upper left diagram can be simplified to Y = A'B' + AC. When B=0 and C=1, this logical expression can also be represented as Y = A' + A. Therefore, competition and hazard will definitely exist.

The logical expression in the upper right diagram can be simplified to Y = A'B' + AB. Clearly, whether B is 1 or 0, this expression will not be simplified to Y = A' + A. Therefore, this logic does not have competition and hazard.

It should be noted that the Karnaugh map is contiguous at the ends. As shown in the diagram below, although the two Karnaugh circles do not appear to be tangent, in fact, m6 and m4 are adjacent, so the digital logic represented by the Karnaugh map below will also produce competition and hazard.

For other more complex situations, a "computer-aided analysis + experiment" method may be needed.

Elimination Methods

For digital circuits, common methods to avoid competition and hazard mainly include four types.

1) Add Filter Capacitor to Filter Narrow Pulses

This method requires connecting a small capacitor in parallel at the output to weaken the amplitude of the spike pulse below the threshold of the gate circuit.

Although this method is simple, it will increase the switching time of the output voltage and easily damage the waveform.

2) Modify Logic, Add Redundant Terms

Using the Karnaugh map, add a Karnaugh circle between two tangent circles and include it in the logical expression.

As shown in the diagram below, for the digital logic Y = A'B' + AC, add the redundant term B'C, then the circuit logic can be represented as Y = A'B' + AC + B'C. At this time, the circuit will no longer have competition and hazard.

3) Use Clock Synchronization Circuit, Use Flip-Flop for Delayed Clocking

In a synchronous circuit, signal changes occur at the clock edge. For the D input of the flip-flop, as long as the glitch does not appear at the rising edge of the clock and does not meet the setup and hold time of the data, it will not cause harm to the system. Therefore, it can be considered that the D input of the flip-flop is not sensitive to glitches.

Using this characteristic, under the drive of the clock edge, delay a combinational logic signal by clocking it through a flip-flop to eliminate competition and hazard.

Delaying by one clock cycle has a certain probability of reducing the occurrence of competition and hazard. Experiments show that the safest delay cycle is 3 cycles, which can effectively reduce the occurrence of competition and hazard.

Of course, the final decision should be based on your design requirements and the reasonable delay of the signal.

To illustrate that delaying the signal can eliminate competition and hazard, we establish the following code model.

Example

module competition_hazard
    (
        input               clk,
        input               rstn,
        input               en,
        input               din_rvs,
        output reg          flag
    );

    wire    condition = din_rvs & en ;  //combination logic
    always @(posedge clk or negedge !rstn) begin
        if (!rstn) begin
            flag   <= 1'b0 ;
        end
        else begin
            flag   <= condition ;
        end
    end 

endmodule

Testbench description is as follows:

Example

`timescale 1ns/1ns

module test ;
    reg         clk, rstn ;
    reg         en ;
    reg         din_rvs ;
    wire        flag_safe, flag_dgs ;

    //clock and rstn generating 
    initial begin
        rstn              = 1'b0 ;
        clk               = 1'b0 ;
        #5 rstn           = 1'b1 ;
        forever begin
            #5 clk = ~clk ;
        end
    end

    initial begin
        en        = 1'b0 ;
        din_rvs   = 1'b1 ;
        #19 ;      en        = 1'b1 ;
        #1 ;       din_rvs   = 1'b0 ;
    end

    competition_hazard         u_dgs
     (
      .clk              (clk           ),
      .rstn             (rstn          ),
      .en               (en            ),
      .din_rvs          (din_rvs       ),
      .flag             (flag_dgs      ));

    initial begin
        forever begin
            #100;
            if ($time >= 1000)  $finish ;
        end
    end

endmodule // test

Simulation results are as follows:

As shown in the figure, signal condition has a spike pulse, which is due to the fact that signals din_rvs and en are asynchronous with respect to the internal clock of the module, so the delays when they reach the internal gate circuit are different, which may cause competition and hazard.

Although the final simulation result flag is always 0, which seems to be the result we want. However, in actual circuits, this spike pulse is very close to the clock edge, and there is a possibility that it will be sampled by the clock and produce an incorrect result.

Below, we improve the model by adding delay logic, as follows:

Example

module clap_delay
    (
        input               clk,
        input               rstn,
        input               en,
        input               din_rvs,
        output reg          flag
    );

    reg                 din_rvs_r ;
    reg                 en_r ;
    always @(posedge clk or !rstn) begin
        if (!rstn) begin
            din_rvs_r      <= 1'b0 ;
            en_r           <= 1'b0 ;
        end
        else begin
            din_rvs_r      <= din_rvs ;
            en_r           <= en ;
        end
    end

    wire                condition = din_rvs_r & en_r ;
    always @(posedge clk or negedge !rstn) begin
        if (!rstn) begin
            flag   <= 1'b0 ;
        end
        else begin

            flag   <= condition ;
        end
    end // always @ (posedge clk or negedge !rstn)

endmodule

Instantiate this module into the above testbench to obtain the following simulation results.

As shown in the figure, signal condition no longer has the interference of spike pulses, and the simulation result flag being 0 is as expected.

In fact, when the input signal is very close to the clock edge, the sampling of the input signal by the clock is also uncertain, but there will be no spike pulse phenomenon. Delaying the input signal by two more cycles is a better approach, with a better inhibitory effect on competition and hazard.

4) Use Gray Code Counter

A multi-bit counter that increments may have multiple bit changes at times.

For example, when the counter variable counter changes from 5 to 6, the corresponding binary numbers are 4'b101 to 4'b110. Due to the delays of each bit data, the transformation process of counter may be: 4'b101 -> 4'b111 -> 4'b110. If there is the following logical description, the signal cout may have a brief spike pulse, which is obviously contrary to the design.

cout = counter[3:0] == 4'd7 ;

The Gray code counter, when counting, only one data bit changes between adjacent numbers, which can effectively avoid competition and hazard.

Fortunately, in Verilog design, counters are mostly synchronous. Even if there is a possibility of multiple bits flipping at the same time during counting, under the action of the clock-driven flip-flop, as long as the signals meet the timing requirements, 100% competition and hazard can be eliminated.

Summary

Generally speaking, adding filter capacitors and logical redundancies to eliminate competition and hazard is not considered in Verilog design.

Using Gray code counters is mostly applied in high-speed clock scenarios to reduce signal transition rates and lower power consumption.

Using flip-flops to delay asynchronous signals in a clock synchronous circuit is a method often used in Verilog design.

In addition, there are some issues to pay attention to when writing Verilog code to eliminate competition and hazard, which are detailed in the next section.


Verilog Writing Standards

By paying attention to the following points during programming, most competition and hazard problems can be avoided.

-

Below, each of the above points is analyzed in detail.

1) Use non-blocking assignment when modeling sequential circuits

This is a Chinese to English translation. Here is the English translation of the text:

In the previous discussion on non-blocking assignments, it was stated that non-blocking assignments in sequential circuits can eliminate race hazards.

For example, the following code describes a situation where the order of blocking assignments to a and b cannot be determined, potentially leading to race hazards.

always @(posedge clk) begin
    a = b;
    b = a;
end

However, when using non-blocking assignments, the assignments are performed simultaneously, thus avoiding race hazards, as described in the following code.

always @(posedge clk) begin
    a <= b;
    b <= a;
end

2) Blocking Assignments in Combinational Logic Modeling

When both assignment statements are executed simultaneously, F <= C & D uses the old value of signal C, leading to incorrect logic where the logical value of F does not equal A&B&D.

Additionally, this requires signal C to have storage capabilities but not be clock-driven, so C may be synthesized into a latch, leading to race hazards.

always @(*) begin
    C <= A & B;
    F <= C & D;
end

By modifying the code as follows, the operation F = C & D is guaranteed to occur after C = A & B, ensuring that the logical value of F equals A&B&D, as intended.

always @(*) begin
    C = A & B;
    F = C & D;
end

3) Non-blocking Assignments in the Same Always Block for Sequential and Combinational Logic Modeling

Although sequential circuits may involve combinational logic, using non-blocking assignments for assignment operations can still lead to similar issues as mentioned in guideline 1.

For example, the following code completes a logical AND function under clock drive.

Example

always @(posedge clk or negedge rst_n)
    if (!rst_n) begin
        q <= 1'b0;
    end
    else begin
        q <= a & b; // Do not write as: q = a & b
    end
end

4) Do Not Mix Blocking and Non-blocking Assignments in the Same Always Block

In combinational logic involving both blocking and non-blocking assignments, unexpected results may occur, as described in the following code.

In this case, signal C is block-assigned first, followed by non-blocking assignment to signal F, which may yield correct simulation results.

However, if signal F has other loads, its latest value cannot be immediately propagated, and the data validity remains until the next trigger moment. This requires F to have storage capabilities, potentially synthesizing into a latch and leading to race hazards.

always @(*) begin
    C = A & B;
    F <= C & D;
end

In the following code, from a simulation perspective, signal C is non-block-assigned and becomes valid at the next trigger moment. Although F = C & D is a blocking assignment, signal C is not block-assigned, so the logic of F still uses the old value of C.

always @(*) begin
    C <= A & B;
    F = C & D;
end

The following analysis examines what happens if both blocking and non-blocking assignments are used in a sequential circuit.

If the reset is synchronized with the clock, the signal q being 0 due to reset becomes effective in the next clock cycle.

However, if signal q being 0 is due to signals a or b, it becomes effective within the current clock cycle.

If q has other loads, this will cause q's timing to be particularly chaotic, clearly not meeting design requirements.

Example

always @(posedge clk or negedge rst_n)
    if (!rst_n) begin // Assuming reset is synchronized with the clock
        q <= 1'b0;
    end
    else begin
        q = a & b;
    end
end

It should be noted that many compilers support this writing style, and the above analysis is based on simulation perspectives. In practice, if blocking and non-blocking assignments are mixed, the timing of the synthesized circuit will be chaotic, making it difficult to analyze and debug.

5) Do Not Assign Values to the Same Variable in Multiple Always Blocks

Unlike C language, Verilog does not allow assigning values to the same variable in multiple always blocks. This results in a signal having multiple driver terminals (Multiple Driver), which is prohibited. Similarly, it is also not allowed to use assign statements to assign values to the same variable multiple times.

From the signal perspective, multiple drivers can cause the same signal variable to be assigned different values multiple times in a short period, potentially leading to race hazards.

From a syntactic perspective, many compilers will report an error when detecting multiple drivers.

6) Avoiding Latch Generation

Specific analysis is provided in the next chapter: Avoiding Latch.

Source Code Download

Download

-1.1 Verilog Tutorial

-1.2 Verilog Introduction

-1.3 Verilog Environment Setup

-1.4 Verilog Design Method

-2.1 Verilog Basic Syntax

-2.2 Verilog Numerical Representation

-2.3 Verilog Data Types

-2.4 Verilog Expressions

-2.5 Verilog Compile Instructions

-3.1 Verilog Continuous Assignment

-3.2 Verilog Time Delay

-4.1 Verilog Process Structure

-4.2 Verilog Process Assignment

-4.3 Verilog Timing Control

-4.4 Verilog Statement Blocks

-4.5 Verilog Conditional Statements

-4.6 Verilog Multi-branch Statements

-4.7 Verilog Loop Statements

-4.8 Verilog Process Continuous Assignment

-5.1 Verilog Modules and Ports

-5.2 Verilog Module Instantiation

-5.3 Verilog Parameterized Instantiation

-6.1 Verilog Functions

-6.2 Verilog Tasks

-6.3 Verilog State Machines

-6.5 Verilog Avoiding Latch

-6.6 Verilog Simulation Stimulus

-6.7 Verilog Pipeline

-7.1 Verilog Divider Design

-7.2 Verilog Parallel FIR Filter Design

-7.3 Verilog Serial FIR Filter Design

-7.4 Verilog CIC Filter Design

-7.5 Verilog FFT Design

-7.6 Verilog DDS Design

-8.1 Verilog Numerical Conversion

-Verilog Advanced Tutorial

WeChat Subscription

English:

❮ Android Tutorial Colorfilterl2 Html5 Canvas Eccharts ❯