Use Explicit Port Declarations

module mux32two (input [31:0] i0,i1, input sel, output [31:0] out);

assign out = sel ? i1 : i0; endmodule

mux32two adder_mux(.i0(b), .i1(32'd1), Sequential Logic .sel(f[0]), .out(addmux_out));

• Digital : the D-Register mux32two adder_mux(b, 32'd1, f[0], addmux_out); • Timing constraints for D-Registers 2 • Specifying registers in Verilog • Blocking and nonblocking assignments Order of the ports matters! • Examples

Reminder: Lab #2 due Thursday

6.111 Fall 2016 Lecture 4 1 6.111 Fall 2015

Verilog Summary Examples

• Verilog – Hardware description language – not software program. parameter MSB = 7; // defines msb as a constant value 7

• A convention: lowercase for variables, UPPERCASE for parameter E = 25, F = 9; // defines two constant numbers parameters module blob #(parameter WIDTH = 64, // default width: 64 pixels parameter BYTE_SIZE = 8, HEIGHT = 64, // default height: 64 pixels BYTE_MASK = BYTE_SIZE - 1; COLOR = 3'b111) // default color: white (input [10:0] x,hcount, input [9:0] y,vcount, output reg [2:0] pixel); endmodule parameter [31:0] DEC_CONST = 1’b1; // value converted to 32 bits

• wires wire a,b,z; // three 1-bit wires wire [31:0] memdata; // a 32-bit bus parameter NEWCONST = 3’h4; // implied range of [2:0] wire [7:0] b1,b2,b3,b4; // four 8-bit buses wire [WIDTH-1:0] input; // parameterized bus parameter NEWCONS = 4; // implied range of at least [31:0]

6.111 Fall 2016 Lecture 4 3 6.111 Fall 2016 Lecture 4 4 Something We Can’t Build (Yet) Digital State One model of what we’d like to build

What if you were given the following design specification: Next State Memory When the button is pushed: 1) Turn on the light if Device Current it is off State Combinational button 2) Turn off the light if light LOAD it is on Logic

The light should change state within a second Input Output of the button press

What makes this circuit so different Plan: Build a Sequential Circuit with stored digital STATE – from those we’ve discussed before? • Memory stores CURRENT state, produced at output

1. “State” – i.e. the circuit has memory • Combinational Logic computes 2. The output was changed by a input • NEXT state (from input, current state) When Output depends on input and current state, circuit is “event” (pushing a button) rather • OUTPUT bit (from input, current state) called a Mealy machine. If than an input “value” Output depends only on the • State changes on LOAD control input current state, circuit is called a Moore machine. 6.111 Fall 2016 Lecture 4 5 6.111 Fall 2016 Lecture 4 6

Ourthe next rising edge building of CLK block: the D register D-Register Timing - I

The edge-triggered D register: on ≤tPD , the value of ≥t D is saved in the register and then CD shortly afterwards appears on Q. Q

CLK

D D  ≥t ≥t CLK tPD: maximum propagation delay, CLK Q SETUP HOLD tCD: minimum contamination delay, CLK Q Q tSETUP: setup time How long D must be stable be

tHOLD: hold time How long D must be stable after the rising edge of CLK fore the rising edge of CLK 6.111 Fall 2016 Lecture 4 7 6.111 Fall 2016 Lecture 4 8 D-Register Internals – 74LS74 D-Register Timing - II

≤tPD DQ logic DQ e1reg2reg1 ≥tCD

Q CLK

tCLK CLK tPD,reg1 D CLK tPD,logic

≥tSETUP ≥tHOLD tCD,reg1 CLK

tSETUP = 20ns tPD-HL = 40ns t The good news: you can CD,logic ≥ tSETUP,reg2 constraint is satisfied! choose tCLK so that this tHOLD = 5ns tPD-LH = 25ns tPD,reg1 + tPD,logic + tSETUP,reg2 ≤ tCLK The bad news: you have to change your design if this constraint isn’t tCD,reg1 + tCD,logic ≥ tHOLD,reg2 6.111 Fall 2016 Lecture 4 9 6.111 Fall 2016 Lecture 4 met. 10

Single-clock Synchronous Circuits Clocks are Not Perfect: Clock Skew

CLout We’ll use Registers in a highly constrained way to build digital systems: In Combinational Does that D Q D Q symbol Logic register? Single-clock Synchronous Discipline • No combinational cycles clk2 domain Wire delay • Single shared among clk1 all clocked devices (one clock ) clk1 • Only care about value of combinational circuits just before clk2 rising edge of clock

• Clock period greater than every δ>0 combinational delay tskew = tclk2 –tclk1 • Change saved state after noise- inducing logic transitions have stopped! 6.111 Fall 2016 Lecture 4 11 6.111 Fall 2016 Lecture 4 12 Positive and Negative Skew D-Register Timing With Skew

In the real world the clock signal arrives TCLK  R1 R2 R3 at different registers at different times. In Combinational Combinational CLK DQ DQ DQ ••• 1 T 3 DQ logic DQ Logic Logic CLK1 The difference in arrival times (pos or  reg2reg1 CLK tCLK1 tCLK2 tCLK3 neg) is called the clock skew tskew. CLK2 2 4 delay delay tskew = tRn,clk2 –tRn,clk1 t   h CLK ±skew (a) Positive skew We can update our two timing constraints to reflect the worst-case skew Launching edge arrives before the receiving edge CLKreg1 Setup time: t = t tPD,reg1+tPD,logic Rn,clk Rn+1,clk tRn,clk1+tPD,reg1+tPD,logic +tSETUP,reg2 ≤ tRn+1,clk2 R1 R2 R3 T +  t +t + t ≤ t + t In Combinational Combinational CLK PD,reg1 PD,logic SETUP,reg2 CLK skew DQ DQ DQ ••• Logic CLK tCD,reg1+tCD,logic Logic 1 3 CLK1 T tCLK1 tCLK2 tCLK3 Hold time: tRn,clk1+tCD,reg1+tCD,logic ≥ tRn,clk2+tHOLD,reg2 delay delay CLK CLK2 2 4 ≥ tSETUP,reg2  (b) Negative skew tCD,reg1+tCD,logic ≥ tHOLD,reg2+ tskew CLKreg2 Receiving edge arrives before the launching edge Thus clock skew increases the minimum ≥ tHOLD,reg2 cycle time of our design and makes it harder to meet register hold times. Adapted from J. Rabaey, A. Chandrakasan, B. Nikolic, CLKanywherereg2 rising in thisedge region. might fall “Digital Integrated Circuits: A Design Perspective” Copyright 2003 Prentice Hall/Pearson. Which skew is tougher to deal with (pos or neg)? 6.111 Fall 2016 Lecture 4 13 6.111 Fall 2016 Lecture 4 14

Delay Estimation : Simple RC Networks RC Equation

VDD Vin

50% Vs = 5 V t V = 5 V Vin Vout s

tpHL tpLH C V Switch is closed t<0 L out R 90% Switch opens t>0 50% V DD V DD V = V + V 10% t + s R C tf tr V dVc (b) High-to-low c Vs = iR R+ Vc iR = C R on (a) Low-to-high dt - dV review R RC c V vout Vs = dt c

V V out t out vin C    V  V 1 e RC  C t c s   L C    L V  51 e RC    R c   on  

tp = ln (2)  = 0.69 RC

6.111 Fall 2016 Lecture 4 15 6.111 Fall 2016 Lecture 4 16 Clocks are Not Perfect: Clock Jitter Sequential Circuit Timing

New tCD,R = 1ns State tPD,R = 3ns t = 2ns S,R Current Combinational tH,R = 2ns State Logic Clock tCD,L = ? t = 5ns InputPD,L Output

Questions:

tpd, tsu, thold • Constraints on tCD for the logic? > 1 ns

• Minimum clock period? > 10 ns (tPD,R+tPD,L+ tSETUP,R) Typical crystal oscillator • Setup, Hold times for Inputs? tSETUP,Input = tPD,L +tSETUP,R tclk –2tjitter > tpd + tsu + tlogic 100mhz (10ns) Jitter: 1ps tHOLD,Input = tHOLD,R -tCD,L This is a simple Finite State Machine … more on next time!

6.111 Fall 2016 Lecture 4 17 6.111 Fall 2016 Lecture 4 18

The Sequential always Block Importance of the Sensitivity List

Edge-triggered circuits are described using a sequential always • The use of posedge and negedge makes an always block block sequential (edge-triggered) • Unlike a combinational always block, the sensitivity list does Combinational Sequential determine behavior for synthesis! D-Register with synchronous clear D-Register with asynchronous clear module comb(input a, b, sel, module seq(input a, b, sel, clk, module dff_sync_clear( module dff_sync_clear( output reg out); output reg out); input d, clearb, clock, input d, clearb, clock, output reg q output reg q always @(*) begin always @(posedge clk) begin ); ); if (sel) out = b; if (sel) out <= b; always @(posedge clock) always @(negedge clearb or posedge clock) else out = a; else out <= a; begin begin end end if (!clearb) q <= 1'b0; if (!clearb) q <= 1'b0; endmodule endmodule else q <= d; else q <= d; end end endmodule endmodule

always always block entered only at block entered immediately when each positive clock edge (active-low) clearb is asserted

Note: The following is incorrect syntax: always @(clear or negedge clock) If one signal in the sensitivity list uses posedge/negedge, then all signals must. . Assign any signal or variable from only one always block. Be wary of race conditions: always blocks with same trigger execute concurrently…

6.111 Fall 2016 Lecture 4 19 6.111 Fall 2016 Lecture 4 20 Blocking vs. Nonblocking Assignments Blocking vs. Nonblocking Assignments

• Verilog supports two types of assignments within always blocks, • Guaranteed question on job interviews with Verilog questions. with subtly different behaviors. • Blocking assignment (=): evaluation and assignment are immediate • Blocking assignment (=): evaluation and assignment are immediate; always @(*) begin subsequent statements affected. x = a | b; // 1. evaluate a|b, assign result to x y = a ^ b ^ c; // 2. evaluate a^b^c, assign result to y z = b & ~c; // 3. evaluate b&(~c), assign result to z • Nonblocking assignment ( <=): all assignments deferred to end of end simulation time step after all right-hand sides have been evaluated (even those in other active always blocks) Nonblocking assignment ( <=): all assignments deferred to end of simulation time step after all right-hand sides have been evaluated (even those in other active always blocks) Sometimes, as above, both produce the same result. Sometimes, not! always @(*) begin x <= a | b; // 1. evaluate a|b, but defer assignment to x y <= a ^ b ^ c; // 2. evaluate a^b^c, but defer assignment to y z <= b & ~c; // 3. evaluate b&(~c), but defer assignment to z // 4. end of time step: assign new values to x, y and z end Sometimes, as above, both produce the same result. Sometimes, not!

6.111 Fall 2016 Lecture 4 21 6.111 Fall 2016 Lecture 4 22

Assignment Styles for Sequential Logic Use Nonblocking for Sequential Logic

always @(posedge clk) begin always @(posedge clk) begin q1 <= in; q1 = in; q2 <= q1; // uses old q1 q2 = q1; // uses new q1 What we want: out <= q2; // uses old q2 out = q2; // uses new q2 Register Based end end Digital Delay Line “At each rising clock edge, q1, q2, “At each rising clock edge, q1 = in. and out simultaneously receive the After that, q2 = q1. old values of in, q1, and q2.” After that, out = q2. Will nonblocking and blocking assignments both produce the Therefore out = in.” desired result? (“old” means value before clock edge, “new” means the value after most recent assignment)

module nonblocking( module blocking( input in, clk, input in, clk, output reg out output reg out ); ); reg q1, q2; reg q1, q2; always @(posedge clk) begin always @(posedge clk) begin • Blocking assignments do not reflect the intrinsic behavior of multi- q1 <= in; q1 = in; stage sequential logic q2 <= q1; // uses old q1 q2 = q1; // uses new q1 out <= q2; // uses old q2 out = q2; // uses new q2 • Guideline: use nonblocking assignments for sequential always blocks end end

endmodule endmodule

6.111 Fall 2016 Lecture 4 23 6.111 Fall 2016 Lecture 4 24 always block Sequential always block style

• // There are two styles for creating this sample divider. The Sequential always block: always @(posedge clock) use <= // first uses sequential always block for state assignment and // a combinational always block for next-state. This style tends // to result in fewer errors. • Combinatorial always block: always @ * use = // // An alternate approach is to use a single always block. An example // of a divide by 5 will illustrate the differences • Results of operators (LHS) inside always block (sequential and combinatorial) must be declared as “reg” ////////////////////////////////// ///////////////////////////////// // Sequential always block with a // Single always block // combinational always block // • Equivalent Verilog reg [3:0] count1, next_count1; reg [3:0] count2;  same as  reg z always @(posedge clk) always @(posedge clk) begin always @ * example of assign z = x && y count1 <= next_count1; if (reset) count2 <= 0; combinatorial // z not a “reg” else count2 <= z = x && y always @* begin (count2 == 4) ? 0 : count2 + 1; always block if (reset) next_count1 = 0; end else next_count1 = (count1 == 4) ? 0 : count1 + 1; assign enable2 = (count2 == 4); • case statements must be used within an always block; include end

default case assign enable1 = (count1 == 4); ////////////////////////////////// //////////////////////////////////

6.111 Fall 2016 Lecture 4 25 6.111 Fall 2016 Lecture 4 26

Coding Guidelines Guideline 4: Sequential and “combinatorial” logic The following helpful guidelines are from the Cummings paper. If in the same always block followed, they ensure your simulation results will match what they synthesized hardware will do: module nbex1 module nbex2 (output reg q, (output q, 1. When modeling sequential logic, use nonblocking assignments. input clk, rst_n, input clk, rst_n, 2. When modeling latches, use nonblocking assignments. Combinatorial input a, b); input a, b); 3. When modeling combinational logic with an always block, use blocking logic assignments. reg y; reg q; 4. When modeling both sequential and “combinational” logic within the always @(a or b) always @(posedge clk or same always block, use nonblocking assignments. y = a ^ b; negedge rst_n) 5. Do not mix blocking and nonblocking assignments in the same always if (!rst_n) q <= 1'b0; block. always @(posedge clk or else q <= a ^ b; 6. Do not make assignments to the same variable from more than one negedge rst_n) always block. if (!rst_n) q <= 1'b0; endmodule 7. Use $strobe to display values that have been assigned using else q <= y; nonblocking assignments. Combinatorial logic 8. Do not make assignments using #0 delays. endmodule For more info see: http://www.sunburst-design.com/papers/CummingsSNUG2002Boston_NBAwithDelays.pdf #1 thing we will be checking in your Verilog submissions! 6.111 Fall 2016 Lecture 4 27 6.111 Fall 2008 Lecture 4 28 = vs. <= inside always Implementation for on/off button

button A always @(posedge clk) begin a = b; // blocking assignment module main; b = a; // execute sequentially reg a,b,clk; end light

B always @(posedge clk) begin a <= b; // non-blocking assignment b <= a; // eval all RHSs first end

always @(posedge clk) a = b; module onoff(input button, output reg light); C always @(posedge clk) b = a; always @(posedge button) light <= ~light; endmodule initial begin clk = 0; a = 0; b = 1; D always @(posedge clk) a <= b; #10 clk = 1; always @(posedge clk) b <= a; #10 $display("a=%d b=%d\n",a,b); $finish; always @(posedge clk) begin end E a <= b; endmodule b = a; // urk! Be consistent! end

Rule: always change state using <= (e.g., inside always @(posedge clk)…)

6.111 Fall 2016 Lecture 4 29 6.111 Fall 2016 Lecture 4 30

Synchronous on/off button Resetting to a known state

When designing a system that accepts many inputs it would be hard Usually one can’t rely on registers powering-on to a particular initial to have input changes serve as the system clock (which input would state*. So most designs have a RESET signal that when asserted we use?). So we’ll use a single clock of some fixed frequency and initializes all the state to known, mutually consistent initial values. have the inputs control what state changes happen on rising clock edges. module onoff_sync(input clk, reset, button, For most of our lab designs we’ll use a 27MHz system clock (37ns output reg light); clock period). always @ (posedge clk) begin if (reset) light <= 0; else if (button) light <= ~light; module onoff_sync(input clk, button, end output reg light); endmodule always @ (posedge clk) begin if (button) light <= ~light; end * Actually, our FPGAs will reset all registers to 0 when the device is endmodule programmed. But it’s nice to be able to press a reset button to return to a known state rather than starting from scratch by reprogramming the device.

6.111 Fall 2016 Lecture 4 31 6.111 Fall 2016 Lecture 4 32 Clocks are fast, we’re slow! Asynchronous Inputs in Sequential Systems The circuit on the last slide toggles the light on every rising clock What about external signals? edge for which button is 1. But clocks are fast (27MHz!) and our fingers are slow, so how do we press the button for just one clock Can’t guarantee edge? Answer: we can’t, but we can add some state that remembers Sequential System setup and hold what button was last clock cycle and then detect the clock cycles times will be met! when button changes from 0 to 1. Clock

module onoff_sync(input clk, reset, button, When an asynchronous signal causes a setup/hold output reg light); violation... reg old_button; // state of button last clk I II III always @ (posedge clk) begin Q ? if (reset) begin light <= 0; old_button <= 0; end D else if (old_button==0 && button==1) Clock // button changed from 0 to 1 Transition is missed Transition is caught Output is metastable light <= ~light; on first clock cycle, on first clock cycle. for an indeterminate old_button <= button; but caught on next amount of time. end clock cycle. endmodule Q: Which cases are problematic?

6.111 Fall 2016 Lecture 4 33 6.111 Fall 2016 Lecture 4 34

Asynchronous Inputs in Sequential Systems Handling Metastability

• Preventing metastability turns out to be an impossible problem All of them can be, if more than one happens simultaneously • High gain of digital devices makes it likely that metastable conditions will within the same circuit. resolve themselves quickly Guideline: ensure that external signals directly feed • Solution to metastability: allow time for signals to stabilize exactly one Can be Very unlikely to Extremely unlikely metastable be metastable for to be metastable for

This imag Clocked e canno t curre ntly be displa yed. Synchronous right after >1 clock cycle >2 clock cycles flip-flop System Async Q0 sampling D Q Sequential System Input DQ Clock Complicated Q1 DQ DQDQ D Q Sequential Logic System Clock Clock Clock

This prevents the possibility of I and II occurring in different places in How many registers are necessary? the circuit, but what about metastability? • Depends on many design parameters (clock speed, device speeds, …) • In 6.111, a pair of synchronization registers is sufficient

6.111 Fall 2016 Lecture 4 35 6.111 Fall 2016 Lecture 4 36 One last little problem… One last little problem…

Mechanical buttons exhibit contact // Switch Debounce Module Mechanical buttons exhibit contact // Switch Debounce Module // use your system clock for the clock input // use your system clock for the clock input “bounce” when they change position, // to produce a synchronous, debounced output “bounce” when they change position, // to produce a synchronous, debounced output leading to multiple output transitions // DELAY = .01 sec with a 27Mhz clock leading to multiple output transitions // DELAY = .01 sec with a 27Mhz clock module debounce #(parameter DELAY=270000-1) module debounce #(parameter DELAY=270000-1) before finally stabilizing in the new (input reset, clock, bouncey, before finally stabilizing in the new (input reset, clock, bouncey, position: output reg steady); position: output reg steady); reg [18:0] count; reg [18:0] count; We need a reg old; We need a reg old;

debouncing always @(posedge clock) debouncing always @(posedge clock) circuit! circuit! if (reset) // return to known state begin count <= 0; old <= bouncey; steady <= bouncey; end else if (bouncey != old) // input changed begin old <= bouncey; count <= 0; end else if (count == DELAY) // stable! steady <= old; else // waiting… count <= count+1; endmodule endmodule

6.111 Fall 2016 Lecture 4 37 6.111 Fall 2016 Lecture 4 38

On/off button: final answer Example: A Simple Counter

module onoff_sync(input clk, reset, button_in, Isn’ t this a lot like output reg light); Exercise 1 in Lab 2? // synchronizer 0 4 4 reg button,btemp; 1 always @(posedge clk) +1 1 count {button,btemp} <= {btemp,button_in}; 0

// debounce push button 0 wire bpressed; clr debounce db1(.clock(clk),.reset(reset), clk .bouncey(button),.steady(bpressed)); enb

reg old_bpressed; // state last clk cycle always @ (posedge clk) begin // 4-bit counter with enable and synchronous clear if (reset) module counter(input clk,enb,clr, begin light <= 0; old_bpressed <= 0; end else if (old_bpressed==0 && bpressed==1) output reg [3:0] count); // button changed from 0 to 1 always @(posedge clk) begin light <= ~light; count <= clr ? 4’b0 : (enb ? count+1 : count); old_bpressed <= bpressed; end end endmodule endmodule

6.111 Fall 2016 Lecture 4 39 6.111 Fall 2016 Lecture 4 40