text
stringlengths 938
1.05M
|
---|
//*****************************************************************************
// (c) Copyright 2008 - 2013 Xilinx, Inc. All rights reserved.
//
// This file contains confidential and proprietary information
// of Xilinx, Inc. and is protected under U.S. and
// international copyright and other intellectual property
// laws.
//
// DISCLAIMER
// This disclaimer is not a license and does not grant any
// rights to the materials distributed herewith. Except as
// otherwise provided in a valid license issued to you by
// Xilinx, and to the maximum extent permitted by applicable
// law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND
// WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES
// AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
// BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-
// INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and
// (2) Xilinx shall not be liable (whether in contract or tort,
// including negligence, or under any other theory of
// liability) for any loss or damage of any kind or nature
// related to, arising under or in connection with these
// materials, including for any direct, or any indirect,
// special, incidental, or consequential loss or damage
// (including loss of data, profits, goodwill, or any type of
// loss or damage suffered as a result of any action brought
// by a third party) even if such damage or loss was
// reasonably foreseeable or Xilinx had been advised of the
// possibility of the same.
//
// CRITICAL APPLICATIONS
// Xilinx products are not designed or intended to be fail-
// safe, or for use in any application requiring fail-safe
// performance, such as life-support or safety devices or
// systems, Class III medical devices, nuclear facilities,
// applications related to the deployment of airbags, or any
// other applications that could lead to death, personal
// injury, or severe property or environmental damage
// (individually and collectively, "Critical
// Applications"). Customer assumes the sole risk and
// liability of any use of Xilinx products in Critical
// Applications, subject only to applicable laws and
// regulations governing limitations on product liability.
//
// THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS
// PART OF THIS FILE AT ALL TIMES.
//
//*****************************************************************************
// ____ ____
// / /\/ /
// /___/ \ / Vendor : Xilinx
// \ \ \/ Version : %version
// \ \ Application : MIG
// / / Filename : ecc_merge_enc.v
// /___/ /\ Date Last Modified : $date$
// \ \ / \ Date Created : Tue Jun 30 2009
// \___\/\___\
//
//Device : 7-Series
//Design Name : DDR3 SDRAM
//Purpose :
//Reference :
//Revision History :
//*****************************************************************************
`timescale 1ps/1ps
module mig_7series_v1_9_ecc_merge_enc
#(
parameter TCQ = 100,
parameter PAYLOAD_WIDTH = 64,
parameter CODE_WIDTH = 72,
parameter DATA_BUF_ADDR_WIDTH = 4,
parameter DATA_BUF_OFFSET_WIDTH = 1,
parameter DATA_WIDTH = 64,
parameter DQ_WIDTH = 72,
parameter ECC_WIDTH = 8,
parameter nCK_PER_CLK = 4
)
(
/*AUTOARG*/
// Outputs
mc_wrdata, mc_wrdata_mask,
// Inputs
clk, rst, wr_data, wr_data_mask, rd_merge_data, h_rows, raw_not_ecc
);
input clk;
input rst;
input [2*nCK_PER_CLK*PAYLOAD_WIDTH-1:0] wr_data;
input [2*nCK_PER_CLK*DATA_WIDTH/8-1:0] wr_data_mask;
input [2*nCK_PER_CLK*DATA_WIDTH-1:0] rd_merge_data;
reg [2*nCK_PER_CLK*PAYLOAD_WIDTH-1:0] wr_data_r;
reg [2*nCK_PER_CLK*DATA_WIDTH/8-1:0] wr_data_mask_r;
reg [2*nCK_PER_CLK*DATA_WIDTH-1:0] rd_merge_data_r;
always @(posedge clk) wr_data_r <= #TCQ wr_data;
always @(posedge clk) wr_data_mask_r <= #TCQ wr_data_mask;
always @(posedge clk) rd_merge_data_r <= #TCQ rd_merge_data;
// Merge new data with memory read data.
wire [2*nCK_PER_CLK*PAYLOAD_WIDTH-1:0] merged_data;
genvar h;
genvar i;
generate
for (h=0; h<2*nCK_PER_CLK; h=h+1) begin : merge_data_outer
for (i=0; i<DATA_WIDTH/8; i=i+1) begin : merge_data_inner
assign merged_data[h*PAYLOAD_WIDTH+i*8+:8] =
wr_data_mask[h*DATA_WIDTH/8+i]
? rd_merge_data[h*DATA_WIDTH+i*8+:8]
: wr_data[h*PAYLOAD_WIDTH+i*8+:8];
end
if (PAYLOAD_WIDTH > DATA_WIDTH)
assign merged_data[(h+1)*PAYLOAD_WIDTH-1-:PAYLOAD_WIDTH-DATA_WIDTH]=
wr_data[(h+1)*PAYLOAD_WIDTH-1-:PAYLOAD_WIDTH-DATA_WIDTH];
end
endgenerate
// Generate ECC and overlay onto mc_wrdata.
input [CODE_WIDTH*ECC_WIDTH-1:0] h_rows;
input [2*nCK_PER_CLK-1:0] raw_not_ecc;
reg [2*nCK_PER_CLK-1:0] raw_not_ecc_r;
always @(posedge clk) raw_not_ecc_r <= #TCQ raw_not_ecc;
output reg [2*nCK_PER_CLK*DQ_WIDTH-1:0] mc_wrdata;
reg [2*nCK_PER_CLK*DQ_WIDTH-1:0] mc_wrdata_c;
genvar j;
integer k;
generate
for (j=0; j<2*nCK_PER_CLK; j=j+1) begin : ecc_word
always @(/*AS*/h_rows or merged_data or raw_not_ecc_r) begin
mc_wrdata_c[j*DQ_WIDTH+:DQ_WIDTH] =
{{DQ_WIDTH-PAYLOAD_WIDTH{1'b0}},
merged_data[j*PAYLOAD_WIDTH+:PAYLOAD_WIDTH]};
for (k=0; k<ECC_WIDTH; k=k+1)
if (~raw_not_ecc_r[j])
mc_wrdata_c[j*DQ_WIDTH+CODE_WIDTH-k-1] =
^(merged_data[j*PAYLOAD_WIDTH+:DATA_WIDTH] &
h_rows[k*CODE_WIDTH+:DATA_WIDTH]);
end
end
endgenerate
always @(posedge clk) mc_wrdata <= mc_wrdata_c;
// Set all DRAM masks to zero.
output wire[2*nCK_PER_CLK*DQ_WIDTH/8-1:0] mc_wrdata_mask;
assign mc_wrdata_mask = {2*nCK_PER_CLK*DQ_WIDTH/8{1'b0}};
endmodule
|
//*****************************************************************************
// (c) Copyright 2008 - 2013 Xilinx, Inc. All rights reserved.
//
// This file contains confidential and proprietary information
// of Xilinx, Inc. and is protected under U.S. and
// international copyright and other intellectual property
// laws.
//
// DISCLAIMER
// This disclaimer is not a license and does not grant any
// rights to the materials distributed herewith. Except as
// otherwise provided in a valid license issued to you by
// Xilinx, and to the maximum extent permitted by applicable
// law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND
// WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES
// AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
// BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-
// INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and
// (2) Xilinx shall not be liable (whether in contract or tort,
// including negligence, or under any other theory of
// liability) for any loss or damage of any kind or nature
// related to, arising under or in connection with these
// materials, including for any direct, or any indirect,
// special, incidental, or consequential loss or damage
// (including loss of data, profits, goodwill, or any type of
// loss or damage suffered as a result of any action brought
// by a third party) even if such damage or loss was
// reasonably foreseeable or Xilinx had been advised of the
// possibility of the same.
//
// CRITICAL APPLICATIONS
// Xilinx products are not designed or intended to be fail-
// safe, or for use in any application requiring fail-safe
// performance, such as life-support or safety devices or
// systems, Class III medical devices, nuclear facilities,
// applications related to the deployment of airbags, or any
// other applications that could lead to death, personal
// injury, or severe property or environmental damage
// (individually and collectively, "Critical
// Applications"). Customer assumes the sole risk and
// liability of any use of Xilinx products in Critical
// Applications, subject only to applicable laws and
// regulations governing limitations on product liability.
//
// THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS
// PART OF THIS FILE AT ALL TIMES.
//
//*****************************************************************************
// ____ ____
// / /\/ /
// /___/ \ / Vendor : Xilinx
// \ \ \/ Version : %version
// \ \ Application : MIG
// / / Filename : ecc_merge_enc.v
// /___/ /\ Date Last Modified : $date$
// \ \ / \ Date Created : Tue Jun 30 2009
// \___\/\___\
//
//Device : 7-Series
//Design Name : DDR3 SDRAM
//Purpose :
//Reference :
//Revision History :
//*****************************************************************************
`timescale 1ps/1ps
module mig_7series_v1_9_ecc_merge_enc
#(
parameter TCQ = 100,
parameter PAYLOAD_WIDTH = 64,
parameter CODE_WIDTH = 72,
parameter DATA_BUF_ADDR_WIDTH = 4,
parameter DATA_BUF_OFFSET_WIDTH = 1,
parameter DATA_WIDTH = 64,
parameter DQ_WIDTH = 72,
parameter ECC_WIDTH = 8,
parameter nCK_PER_CLK = 4
)
(
/*AUTOARG*/
// Outputs
mc_wrdata, mc_wrdata_mask,
// Inputs
clk, rst, wr_data, wr_data_mask, rd_merge_data, h_rows, raw_not_ecc
);
input clk;
input rst;
input [2*nCK_PER_CLK*PAYLOAD_WIDTH-1:0] wr_data;
input [2*nCK_PER_CLK*DATA_WIDTH/8-1:0] wr_data_mask;
input [2*nCK_PER_CLK*DATA_WIDTH-1:0] rd_merge_data;
reg [2*nCK_PER_CLK*PAYLOAD_WIDTH-1:0] wr_data_r;
reg [2*nCK_PER_CLK*DATA_WIDTH/8-1:0] wr_data_mask_r;
reg [2*nCK_PER_CLK*DATA_WIDTH-1:0] rd_merge_data_r;
always @(posedge clk) wr_data_r <= #TCQ wr_data;
always @(posedge clk) wr_data_mask_r <= #TCQ wr_data_mask;
always @(posedge clk) rd_merge_data_r <= #TCQ rd_merge_data;
// Merge new data with memory read data.
wire [2*nCK_PER_CLK*PAYLOAD_WIDTH-1:0] merged_data;
genvar h;
genvar i;
generate
for (h=0; h<2*nCK_PER_CLK; h=h+1) begin : merge_data_outer
for (i=0; i<DATA_WIDTH/8; i=i+1) begin : merge_data_inner
assign merged_data[h*PAYLOAD_WIDTH+i*8+:8] =
wr_data_mask[h*DATA_WIDTH/8+i]
? rd_merge_data[h*DATA_WIDTH+i*8+:8]
: wr_data[h*PAYLOAD_WIDTH+i*8+:8];
end
if (PAYLOAD_WIDTH > DATA_WIDTH)
assign merged_data[(h+1)*PAYLOAD_WIDTH-1-:PAYLOAD_WIDTH-DATA_WIDTH]=
wr_data[(h+1)*PAYLOAD_WIDTH-1-:PAYLOAD_WIDTH-DATA_WIDTH];
end
endgenerate
// Generate ECC and overlay onto mc_wrdata.
input [CODE_WIDTH*ECC_WIDTH-1:0] h_rows;
input [2*nCK_PER_CLK-1:0] raw_not_ecc;
reg [2*nCK_PER_CLK-1:0] raw_not_ecc_r;
always @(posedge clk) raw_not_ecc_r <= #TCQ raw_not_ecc;
output reg [2*nCK_PER_CLK*DQ_WIDTH-1:0] mc_wrdata;
reg [2*nCK_PER_CLK*DQ_WIDTH-1:0] mc_wrdata_c;
genvar j;
integer k;
generate
for (j=0; j<2*nCK_PER_CLK; j=j+1) begin : ecc_word
always @(/*AS*/h_rows or merged_data or raw_not_ecc_r) begin
mc_wrdata_c[j*DQ_WIDTH+:DQ_WIDTH] =
{{DQ_WIDTH-PAYLOAD_WIDTH{1'b0}},
merged_data[j*PAYLOAD_WIDTH+:PAYLOAD_WIDTH]};
for (k=0; k<ECC_WIDTH; k=k+1)
if (~raw_not_ecc_r[j])
mc_wrdata_c[j*DQ_WIDTH+CODE_WIDTH-k-1] =
^(merged_data[j*PAYLOAD_WIDTH+:DATA_WIDTH] &
h_rows[k*CODE_WIDTH+:DATA_WIDTH]);
end
end
endgenerate
always @(posedge clk) mc_wrdata <= mc_wrdata_c;
// Set all DRAM masks to zero.
output wire[2*nCK_PER_CLK*DQ_WIDTH/8-1:0] mc_wrdata_mask;
assign mc_wrdata_mask = {2*nCK_PER_CLK*DQ_WIDTH/8{1'b0}};
endmodule
|
(************************************************************************)
(* v * The Coq Proof Assistant / The Coq Development Team *)
(* <O___,, * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2015 *)
(* \VV/ **************************************************************)
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
Require Export NumPrelude NZAxioms.
Require Import NZBase NZOrder NZAddOrder Plus Minus.
(** In this file, we investigate the shape of domains satisfying
the [NZDomainSig] interface. In particular, we define a
translation from Peano numbers [nat] into NZ.
*)
Local Notation "f ^ n" := (fun x => nat_rect _ x (fun _ => f) n).
Instance nat_rect_wd n {A} (R:relation A) :
Proper (R==>(R==>R)==>R) (fun x f => nat_rect (fun _ => _) x (fun _ => f) n).
Proof.
intros x y eq_xy f g eq_fg; induction n; [assumption | now apply eq_fg].
Qed.
Module NZDomainProp (Import NZ:NZDomainSig').
Include NZBaseProp NZ.
(** * Relationship between points thanks to [succ] and [pred]. *)
(** For any two points, one is an iterated successor of the other. *)
Lemma itersucc_or_itersucc n m : exists k, n == (S^k) m \/ m == (S^k) n.
Proof.
revert n.
apply central_induction with (z:=m).
{ intros x y eq_xy; apply ex_iff_morphism.
intros n; apply or_iff_morphism.
+ split; intros; etransitivity; try eassumption; now symmetry.
+ split; intros; (etransitivity; [eassumption|]); [|symmetry];
(eapply nat_rect_wd; [eassumption|apply succ_wd]).
}
exists 0%nat. now left.
intros n. split; intros [k [L|R]].
exists (Datatypes.S k). left. now apply succ_wd.
destruct k as [|k].
simpl in R. exists 1%nat. left. now apply succ_wd.
rewrite nat_rect_succ_r in R. exists k. now right.
destruct k as [|k]; simpl in L.
exists 1%nat. now right.
apply succ_inj in L. exists k. now left.
exists (Datatypes.S k). right. now rewrite nat_rect_succ_r.
Qed.
(** Generalized version of [pred_succ] when iterating *)
Lemma succ_swap_pred : forall k n m, n == (S^k) m -> m == (P^k) n.
Proof.
induction k.
simpl; auto with *.
simpl; intros. apply pred_wd in H. rewrite pred_succ in H. apply IHk in H; auto.
rewrite <- nat_rect_succ_r in H; auto.
Qed.
(** From a given point, all others are iterated successors
or iterated predecessors. *)
Lemma itersucc_or_iterpred : forall n m, exists k, n == (S^k) m \/ n == (P^k) m.
Proof.
intros n m. destruct (itersucc_or_itersucc n m) as (k,[H|H]).
exists k; left; auto.
exists k; right. apply succ_swap_pred; auto.
Qed.
(** In particular, all points are either iterated successors of [0]
or iterated predecessors of [0] (or both). *)
Lemma itersucc0_or_iterpred0 :
forall n, exists p:nat, n == (S^p) 0 \/ n == (P^p) 0.
Proof.
intros n. exact (itersucc_or_iterpred n 0).
Qed.
(** * Study of initial point w.r.t. [succ] (if any). *)
Definition initial n := forall m, n ~= S m.
Lemma initial_alt : forall n, initial n <-> S (P n) ~= n.
Proof.
split. intros Bn EQ. symmetry in EQ. destruct (Bn _ EQ).
intros NEQ m EQ. apply NEQ. rewrite EQ, pred_succ; auto with *.
Qed.
Lemma initial_alt2 : forall n, initial n <-> ~exists m, n == S m.
Proof. firstorder. Qed.
(** First case: let's assume such an initial point exists
(i.e. [S] isn't surjective)... *)
Section InitialExists.
Hypothesis init : t.
Hypothesis Initial : initial init.
(** ... then we have unicity of this initial point. *)
Lemma initial_unique : forall m, initial m -> m == init.
Proof.
intros m Im. destruct (itersucc_or_itersucc init m) as (p,[H|H]).
destruct p. now simpl in *. destruct (Initial _ H).
destruct p. now simpl in *. destruct (Im _ H).
Qed.
(** ... then all other points are descendant of it. *)
Lemma initial_ancestor : forall m, exists p, m == (S^p) init.
Proof.
intros m. destruct (itersucc_or_itersucc init m) as (p,[H|H]).
destruct p; simpl in *; auto. exists O; auto with *. destruct (Initial _ H).
exists p; auto.
Qed.
(** NB : We would like to have [pred n == n] for the initial element,
but nothing forces that. For instance we can have -3 as initial point,
and P(-3) = 2. A bit odd indeed, but legal according to [NZDomainSig].
We can hence have [n == (P^k) m] without [exists k', m == (S^k') n].
*)
(** We need decidability of [eq] (or classical reasoning) for this: *)
Section SuccPred.
Hypothesis eq_decidable : forall n m, n==m \/ n~=m.
Lemma succ_pred_approx : forall n, ~initial n -> S (P n) == n.
Proof.
intros n NB. rewrite initial_alt in NB.
destruct (eq_decidable (S (P n)) n); auto.
elim NB; auto.
Qed.
End SuccPred.
End InitialExists.
(** Second case : let's suppose now [S] surjective, i.e. no initial point. *)
Section InitialDontExists.
Hypothesis succ_onto : forall n, exists m, n == S m.
Lemma succ_onto_gives_succ_pred : forall n, S (P n) == n.
Proof.
intros n. destruct (succ_onto n) as (m,H). rewrite H, pred_succ; auto with *.
Qed.
Lemma succ_onto_pred_injective : forall n m, P n == P m -> n == m.
Proof.
intros n m. intros H; apply succ_wd in H.
rewrite !succ_onto_gives_succ_pred in H; auto.
Qed.
End InitialDontExists.
(** To summarize:
S is always injective, P is always surjective (thanks to [pred_succ]).
I) If S is not surjective, we have an initial point, which is unique.
This bottom is below zero: we have N shifted (or not) to the left.
P cannot be injective: P init = P (S (P init)).
(P init) can be arbitrary.
II) If S is surjective, we have [forall n, S (P n) = n], S and P are
bijective and reciprocal.
IIa) if [exists k<>O, 0 == S^k 0], then we have a cyclic structure Z/nZ
IIb) otherwise, we have Z
*)
(** * An alternative induction principle using [S] and [P]. *)
(** It is weaker than [bi_induction]. For instance it cannot prove that
we can go from one point by many [S] _or_ many [P], but only by many
[S] mixed with many [P]. Think of a model with two copies of N:
0, 1=S 0, 2=S 1, ...
0', 1'=S 0', 2'=S 1', ...
and P 0 = 0' and P 0' = 0.
*)
Lemma bi_induction_pred :
forall A : t -> Prop, Proper (eq==>iff) A ->
A 0 -> (forall n, A n -> A (S n)) -> (forall n, A n -> A (P n)) ->
forall n, A n.
Proof.
intros. apply bi_induction; auto.
clear n. intros n; split; auto.
intros G; apply H2 in G. rewrite pred_succ in G; auto.
Qed.
Lemma central_induction_pred :
forall A : t -> Prop, Proper (eq==>iff) A -> forall n0,
A n0 -> (forall n, A n -> A (S n)) -> (forall n, A n -> A (P n)) ->
forall n, A n.
Proof.
intros.
assert (A 0).
destruct (itersucc_or_iterpred 0 n0) as (k,[Hk|Hk]); rewrite Hk; clear Hk.
clear H2. induction k; simpl in *; auto.
clear H1. induction k; simpl in *; auto.
apply bi_induction_pred; auto.
Qed.
End NZDomainProp.
(** We now focus on the translation from [nat] into [NZ].
First, relationship with [0], [succ], [pred].
*)
Module NZOfNat (Import NZ:NZDomainSig').
Definition ofnat (n : nat) : t := (S^n) 0.
Notation "[ n ]" := (ofnat n) (at level 7) : ofnat.
Local Open Scope ofnat.
Lemma ofnat_zero : [O] == 0.
Proof.
reflexivity.
Qed.
Lemma ofnat_succ : forall n, [Datatypes.S n] == succ [n].
Proof.
now unfold ofnat.
Qed.
Lemma ofnat_pred : forall n, n<>O -> [Peano.pred n] == P [n].
Proof.
unfold ofnat. destruct n. destruct 1; auto.
intros _. simpl. symmetry. apply pred_succ.
Qed.
(** Since [P 0] can be anything in NZ (either [-1], [0], or even other
numbers, we cannot state previous lemma for [n=O]. *)
End NZOfNat.
(** If we require in addition a strict order on NZ, we can prove that
[ofnat] is injective, and hence that NZ is infinite
(i.e. we ban Z/nZ models) *)
Module NZOfNatOrd (Import NZ:NZOrdSig').
Include NZOfNat NZ.
Include NZBaseProp NZ <+ NZOrderProp NZ.
Local Open Scope ofnat.
Theorem ofnat_S_gt_0 :
forall n : nat, 0 < [Datatypes.S n].
Proof.
unfold ofnat.
intros n; induction n as [| n IH]; simpl in *.
apply lt_succ_diag_r.
apply lt_trans with (S 0). apply lt_succ_diag_r. now rewrite <- succ_lt_mono.
Qed.
Theorem ofnat_S_neq_0 :
forall n : nat, 0 ~= [Datatypes.S n].
Proof.
intros. apply lt_neq, ofnat_S_gt_0.
Qed.
Lemma ofnat_injective : forall n m, [n]==[m] -> n = m.
Proof.
induction n as [|n IH]; destruct m; auto.
intros H; elim (ofnat_S_neq_0 _ H).
intros H; symmetry in H; elim (ofnat_S_neq_0 _ H).
intros. f_equal. apply IH. now rewrite <- succ_inj_wd.
Qed.
Lemma ofnat_eq : forall n m, [n]==[m] <-> n = m.
Proof.
split. apply ofnat_injective. intros; now subst.
Qed.
(* In addition, we can prove that [ofnat] preserves order. *)
Lemma ofnat_lt : forall n m : nat, [n]<[m] <-> (n<m)%nat.
Proof.
induction n as [|n IH]; destruct m; repeat rewrite ofnat_zero; split.
intro H; elim (lt_irrefl _ H).
inversion 1.
auto with arith.
intros; apply ofnat_S_gt_0.
intro H; elim (lt_asymm _ _ H); apply ofnat_S_gt_0.
inversion 1.
rewrite !ofnat_succ, <- succ_lt_mono, IH; auto with arith.
rewrite !ofnat_succ, <- succ_lt_mono, IH; auto with arith.
Qed.
Lemma ofnat_le : forall n m : nat, [n]<=[m] <-> (n<=m)%nat.
Proof.
intros. rewrite lt_eq_cases, ofnat_lt, ofnat_eq.
split.
destruct 1; subst; auto with arith.
apply Lt.le_lt_or_eq.
Qed.
End NZOfNatOrd.
(** For basic operations, we can prove correspondance with
their counterpart in [nat]. *)
Module NZOfNatOps (Import NZ:NZAxiomsSig').
Include NZOfNat NZ.
Local Open Scope ofnat.
Lemma ofnat_add_l : forall n m, [n]+m == (S^n) m.
Proof.
induction n; intros.
apply add_0_l.
rewrite ofnat_succ, add_succ_l. simpl. now f_equiv.
Qed.
Lemma ofnat_add : forall n m, [n+m] == [n]+[m].
Proof.
intros. rewrite ofnat_add_l.
induction n; simpl. reflexivity.
now f_equiv.
Qed.
Lemma ofnat_mul : forall n m, [n*m] == [n]*[m].
Proof.
induction n; simpl; intros.
symmetry. apply mul_0_l.
rewrite plus_comm.
rewrite ofnat_add, mul_succ_l.
now f_equiv.
Qed.
Lemma ofnat_sub_r : forall n m, n-[m] == (P^m) n.
Proof.
induction m; simpl; intros.
apply sub_0_r.
rewrite sub_succ_r. now f_equiv.
Qed.
Lemma ofnat_sub : forall n m, m<=n -> [n-m] == [n]-[m].
Proof.
intros n m H. rewrite ofnat_sub_r.
revert n H. induction m. intros.
rewrite <- minus_n_O. now simpl.
intros.
destruct n.
inversion H.
rewrite nat_rect_succ_r.
simpl.
etransitivity. apply IHm. auto with arith.
eapply nat_rect_wd; [symmetry;apply pred_succ|apply pred_wd].
Qed.
End NZOfNatOps.
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2009 by Iztok Jeras.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
`define checkh(gotv,expv) do if ((gotv) !== (expv)) begin $write("%%Error: %s:%0d: got='h%x exp='h%x\n", `__FILE__,`__LINE__, (gotv), (expv)); $stop; end while(0);
// parameters for array sizes
localparam WA = 4;
localparam WB = 6;
localparam WC = 8;
// 2D packed arrays
logic [WA+1:2] [WB+1:2] [WC+1:2] array_bg; // big endian array
/* verilator lint_off LITENDIAN */
logic [2:WA+1] [2:WB+1] [2:WC+1] array_lt; // little endian array
/* verilator lint_on LITENDIAN */
logic [1:0] array_unpk [3:2][1:0];
integer cnt = 0;
integer slc = 0; // slice type
integer dim = 0; // dimension
integer wdt = 0; // width
initial begin
`checkh($dimensions (array_unpk), 3);
`ifndef VCS
`checkh($unpacked_dimensions (array_unpk), 2); // IEEE 2009
`endif
`checkh($bits (array_unpk), 2*2*2);
`checkh($low (array_unpk), 2);
`checkh($high (array_unpk), 3);
`checkh($left (array_unpk), 3);
`checkh($right(array_unpk), 2);
`checkh($increment(array_unpk), 1);
`checkh($size (array_unpk), 2);
end
// event counter
always @ (posedge clk) begin
cnt <= cnt + 1;
end
// finish report
always @ (posedge clk)
if ( (cnt[30:4]==3) && (cnt[3:2]==2'd3) && (cnt[1:0]==2'd3) ) begin
$write("*-* All Finished *-*\n");
$finish;
end
integer slc_next;
// calculation of dimention sizes
always @ (posedge clk) begin
// slicing type counter
case (cnt[3:2])
2'd0 : begin slc_next = 0; end // full array
2'd1 : begin slc_next = 1; end // single array element
2'd2 : begin slc_next = 2; end // half array
default: begin slc_next = 0; end
endcase
slc <= slc_next;
// dimension counter
case (cnt[1:0])
2'd0 : begin dim <= 1; wdt <= (slc_next==1) ? WA/2 : (slc_next==2) ? WA/2 : WA; end
2'd1 : begin dim <= 2; wdt <= WB; end
2'd2 : begin dim <= 3; wdt <= WC; end
default: begin dim <= 0; wdt <= 0; end
endcase
end
always @ (posedge clk) begin
`ifdef TEST_VERBOSE
$write("cnt[30:4]=%0d slc=%0d dim=%0d wdt=%0d\n", cnt[30:4], slc, dim, wdt);
`endif
if (cnt[30:4]==1) begin
// big endian
if (slc==0) begin
// full array
`checkh($dimensions (array_bg), 3);
`checkh($bits (array_bg), WA*WB*WC);
if ((dim>=1)&&(dim<=3)) begin
`checkh($left (array_bg, dim), wdt+1);
`checkh($right (array_bg, dim), 2 );
`checkh($low (array_bg, dim), 2 );
`checkh($high (array_bg, dim), wdt+1);
`checkh($increment (array_bg, dim), 1 );
`checkh($size (array_bg, dim), wdt );
end
end else if (slc==1) begin
// single array element
`checkh($dimensions (array_bg[2]), 2);
`checkh($bits (array_bg[2]), WB*WC);
if ((dim>=2)&&(dim<=3)) begin
`checkh($left (array_bg[2], dim-1), wdt+1);
`checkh($right (array_bg[2], dim-1), 2 );
`checkh($low (array_bg[2], dim-1), 2 );
`checkh($high (array_bg[2], dim-1), wdt+1);
`checkh($increment (array_bg[2], dim-1), 1 );
`checkh($size (array_bg[2], dim-1), wdt );
end
`ifndef VERILATOR // Unsupported slices don't maintain size correctly
end else if (slc==2) begin
// half array
`checkh($dimensions (array_bg[WA/2+1:2]), 3);
`checkh($bits (array_bg[WA/2+1:2]), WA/2*WB*WC);
if ((dim>=1)&&(dim<=3)) begin
`checkh($left (array_bg[WA/2+1:2], dim), wdt+1);
`checkh($right (array_bg[WA/2+1:2], dim), 2 );
`checkh($low (array_bg[WA/2+1:2], dim), 2 );
`checkh($high (array_bg[WA/2+1:2], dim), wdt+1);
`checkh($increment (array_bg[WA/2+1:2], dim), 1 );
`checkh($size (array_bg[WA/2+1:2], dim), wdt);
end
`endif
end
end else if (cnt[30:4]==2) begin
// little endian
if (slc==0) begin
// full array
`checkh($dimensions (array_lt), 3);
`checkh($bits (array_lt), WA*WB*WC);
if ((dim>=1)&&(dim<=3)) begin
`checkh($left (array_lt, dim), 2 );
`checkh($right (array_lt, dim), wdt+1);
`checkh($low (array_lt, dim), 2 );
`checkh($high (array_lt, dim), wdt+1);
`checkh($increment (array_lt, dim), -1 );
`checkh($size (array_lt, dim), wdt );
end
end else if (slc==1) begin
// single array element
`checkh($dimensions (array_lt[2]), 2);
`checkh($bits (array_lt[2]), WB*WC);
if ((dim>=2)&&(dim<=3)) begin
`checkh($left (array_lt[2], dim-1), 2 );
`checkh($right (array_lt[2], dim-1), wdt+1);
`checkh($low (array_lt[2], dim-1), 2 );
`checkh($high (array_lt[2], dim-1), wdt+1);
`checkh($increment (array_lt[2], dim-1), -1 );
`checkh($size (array_lt[2], dim-1), wdt );
end
`ifndef VERILATOR // Unsupported slices don't maintain size correctly
end else if (slc==2) begin
// half array
`checkh($dimensions (array_lt[2:WA/2+1]), 3);
`checkh($bits (array_lt[2:WA/2+1]), WA/2*WB*WC);
if ((dim>=1)&&(dim<=3)) begin
`checkh($left (array_lt[2:WA/2+1], dim), 2 );
`checkh($right (array_lt[2:WA/2+1], dim), wdt+1);
`checkh($low (array_lt[2:WA/2+1], dim), 2 );
`checkh($high (array_lt[2:WA/2+1], dim), wdt+1);
`checkh($increment (array_lt[2:WA/2+1], dim), -1 );
`checkh($size (array_lt[2:WA/2+1], dim), wdt );
end
`endif
end
end
end
endmodule
|
// ----------------------------------------------------------------------
// Copyright (c) 2016, The Regents of the University of California All
// rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// * Neither the name of The Regents of the University of California
// nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL REGENTS OF THE
// UNIVERSITY OF CALIFORNIA BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
// OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
// TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
// ----------------------------------------------------------------------
//----------------------------------------------------------------------------
// Filename: fifo_packer_64.v
// Version: 1.00.a
// Verilog Standard: Verilog-2001
// Description: Packs 32 or 64 bit received data into a 64 bit wide FIFO.
// Assumes the FIFO always has room to accommodate the data.
// Author: Matt Jacobsen
// History: @mattj: Version 2.0
// Additional Comments:
//-----------------------------------------------------------------------------
`timescale 1ns/1ns
module fifo_packer_64 (
input CLK,
input RST,
input [63:0] DATA_IN, // Incoming data
input [1:0] DATA_IN_EN, // Incoming data enable
input DATA_IN_DONE, // Incoming data packet end
input DATA_IN_ERR, // Incoming data error
input DATA_IN_FLUSH, // End of incoming data
output [63:0] PACKED_DATA, // Outgoing data
output PACKED_WEN, // Outgoing data write enable
output PACKED_DATA_DONE, // End of outgoing data packet
output PACKED_DATA_ERR, // Error in outgoing data
output PACKED_DATA_FLUSHED // End of outgoing data
);
reg [1:0] rPackedCount=0, _rPackedCount=0;
reg rPackedDone=0, _rPackedDone=0;
reg rPackedErr=0, _rPackedErr=0;
reg rPackedFlush=0, _rPackedFlush=0;
reg rPackedFlushed=0, _rPackedFlushed=0;
reg [95:0] rPackedData=96'd0, _rPackedData=96'd0;
reg [63:0] rDataIn=64'd0, _rDataIn=64'd0;
reg [1:0] rDataInEn=0, _rDataInEn=0;
reg [63:0] rDataMasked=64'd0, _rDataMasked=64'd0;
reg [1:0] rDataMaskedEn=0, _rDataMaskedEn=0;
assign PACKED_DATA = rPackedData[63:0];
assign PACKED_WEN = rPackedCount[1];
assign PACKED_DATA_DONE = rPackedDone;
assign PACKED_DATA_ERR = rPackedErr;
assign PACKED_DATA_FLUSHED = rPackedFlushed;
// Buffers input data until 2 words are available, then writes 2 words out.
wire [63:0] wMask = {64{1'b1}}<<(32*rDataInEn);
wire [63:0] wDataMasked = ~wMask & rDataIn;
always @ (posedge CLK) begin
rPackedCount <= #1 (RST ? 2'd0 : _rPackedCount);
rPackedDone <= #1 (RST ? 1'd0 : _rPackedDone);
rPackedErr <= #1 (RST ? 1'd0 : _rPackedErr);
rPackedFlush <= #1 (RST ? 1'd0 : _rPackedFlush);
rPackedFlushed <= #1 (RST ? 1'd0 : _rPackedFlushed);
rPackedData <= #1 (RST ? 96'd0 : _rPackedData);
rDataIn <= #1 _rDataIn;
rDataInEn <= #1 (RST ? 2'd0 : _rDataInEn);
rDataMasked <= #1 _rDataMasked;
rDataMaskedEn <= #1 (RST ? 2'd0 : _rDataMaskedEn);
end
always @ (*) begin
// Buffer and mask the input data.
_rDataIn = DATA_IN;
_rDataInEn = DATA_IN_EN;
_rDataMasked = wDataMasked;
_rDataMaskedEn = rDataInEn;
// Count what's in our buffer. When we reach 2 words, 2 words will be written
// out. If flush is requested, write out whatever remains.
if (rPackedFlush && rPackedCount[0])
_rPackedCount = 2;
else
_rPackedCount = rPackedCount + rDataMaskedEn - {rPackedCount[1], 1'd0};
// Shift data into and out of our buffer as we receive and write out data.
if (rDataMaskedEn != 2'd0)
_rPackedData = ((rPackedData>>(32*{rPackedCount[1], 1'd0})) | (rDataMasked<<(32*rPackedCount[0])));
else
_rPackedData = (rPackedData>>(32*{rPackedCount[1], 1'd0}));
// Track done/error/flush signals.
_rPackedDone = DATA_IN_DONE;
_rPackedErr = DATA_IN_ERR;
_rPackedFlush = DATA_IN_FLUSH;
_rPackedFlushed = rPackedFlush;
end
endmodule
|
// ----------------------------------------------------------------------
// Copyright (c) 2016, The Regents of the University of California All
// rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// * Neither the name of The Regents of the University of California
// nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL REGENTS OF THE
// UNIVERSITY OF CALIFORNIA BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
// OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
// TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
// ----------------------------------------------------------------------
//----------------------------------------------------------------------------
// Filename: rx_port_32.v
// Version: 1.00.a
// Verilog Standard: Verilog-2001
// Description: Receives data from the rx_engine and buffers the output
// for the RIFFA channel.
// Author: Matt Jacobsen
// History: @mattj: Version 2.0
//-----------------------------------------------------------------------------
`timescale 1ns/1ns
module rx_port_32 #(
parameter C_DATA_WIDTH = 9'd32,
parameter C_MAIN_FIFO_DEPTH = 1024,
parameter C_SG_FIFO_DEPTH = 512,
parameter C_MAX_READ_REQ = 2, // Max read: 000=128B, 001=256B, 010=512B, 011=1024B, 100=2048B, 101=4096B
// Local parameters
parameter C_DATA_WORD_WIDTH = clog2((C_DATA_WIDTH/32)+1),
parameter C_MAIN_FIFO_DEPTH_WIDTH = clog2((2**clog2(C_MAIN_FIFO_DEPTH))+1),
parameter C_SG_FIFO_DEPTH_WIDTH = clog2((2**clog2(C_SG_FIFO_DEPTH))+1)
)
(
input CLK,
input RST,
input [2:0] CONFIG_MAX_READ_REQUEST_SIZE, // Maximum read payload: 000=128B, 001=256B, 010=512B, 011=1024B, 100=2048B, 101=4096B
output SG_RX_BUF_RECVD, // Scatter gather RX buffer completely read (ready for next if applicable)
input [31:0] SG_RX_BUF_DATA, // Scatter gather RX buffer data
input SG_RX_BUF_LEN_VALID, // Scatter gather RX buffer length valid
input SG_RX_BUF_ADDR_HI_VALID, // Scatter gather RX buffer high address valid
input SG_RX_BUF_ADDR_LO_VALID, // Scatter gather RX buffer low address valid
output SG_TX_BUF_RECVD, // Scatter gather TX buffer completely read (ready for next if applicable)
input [31:0] SG_TX_BUF_DATA, // Scatter gather TX buffer data
input SG_TX_BUF_LEN_VALID, // Scatter gather TX buffer length valid
input SG_TX_BUF_ADDR_HI_VALID, // Scatter gather TX buffer high address valid
input SG_TX_BUF_ADDR_LO_VALID, // Scatter gather TX buffer low address valid
output [C_DATA_WIDTH-1:0] SG_DATA, // Scatter gather TX buffer data
output SG_DATA_EMPTY, // Scatter gather TX buffer data empty
input SG_DATA_REN, // Scatter gather TX buffer data read enable
input SG_RST, // Scatter gather TX buffer data reset
output SG_ERR, // Scatter gather TX encountered an error
input [31:0] TXN_DATA, // Read transaction data
input TXN_LEN_VALID, // Read transaction length valid
input TXN_OFF_LAST_VALID, // Read transaction offset/last valid
output [31:0] TXN_DONE_LEN, // Read transaction actual transfer length
output TXN_DONE, // Read transaction done
input TXN_DONE_ACK, // Read transaction actual transfer length read
output RX_REQ, // Read request
input RX_REQ_ACK, // Read request accepted
output [1:0] RX_REQ_TAG, // Read request data tag
output [63:0] RX_REQ_ADDR, // Read request address
output [9:0] RX_REQ_LEN, // Read request length
input [C_DATA_WIDTH-1:0] MAIN_DATA, // Main incoming data
input [C_DATA_WORD_WIDTH-1:0] MAIN_DATA_EN, // Main incoming data enable
input MAIN_DONE, // Main incoming data complete
input MAIN_ERR, // Main incoming data completed with error
input [C_DATA_WIDTH-1:0] SG_RX_DATA, // Scatter gather for RX incoming data
input [C_DATA_WORD_WIDTH-1:0] SG_RX_DATA_EN, // Scatter gather for RX incoming data enable
input SG_RX_DONE, // Scatter gather for RX incoming data complete
input SG_RX_ERR, // Scatter gather for RX incoming data completed with error
input [C_DATA_WIDTH-1:0] SG_TX_DATA, // Scatter gather for TX incoming data
input [C_DATA_WORD_WIDTH-1:0] SG_TX_DATA_EN, // Scatter gather for TX incoming data enable
input SG_TX_DONE, // Scatter gather for TX incoming data complete
input SG_TX_ERR, // Scatter gather for TX incoming data completed with error
input CHNL_CLK, // Channel read clock
output CHNL_RX, // Channel read receive signal
input CHNL_RX_ACK, // Channle read received signal
output CHNL_RX_LAST, // Channel last read
output [31:0] CHNL_RX_LEN, // Channel read length
output [30:0] CHNL_RX_OFF, // Channel read offset
output [C_DATA_WIDTH-1:0] CHNL_RX_DATA, // Channel read data
output CHNL_RX_DATA_VALID, // Channel read data valid
input CHNL_RX_DATA_REN // Channel read data has been recieved
);
`include "functions.vh"
wire [C_DATA_WIDTH-1:0] wPackedMainData;
wire wPackedMainWen;
wire wPackedMainDone;
wire wPackedMainErr;
wire wMainFlush;
wire wMainFlushed;
wire [C_DATA_WIDTH-1:0] wPackedSgRxData;
wire wPackedSgRxWen;
wire wPackedSgRxDone;
wire wPackedSgRxErr;
wire wSgRxFlush;
wire wSgRxFlushed;
wire [C_DATA_WIDTH-1:0] wPackedSgTxData;
wire wPackedSgTxWen;
wire wPackedSgTxDone;
wire wPackedSgTxErr;
wire wSgTxFlush;
wire wSgTxFlushed;
wire wMainDataRen;
wire wMainDataEmpty;
wire [C_DATA_WIDTH-1:0] wMainData;
wire wSgRxRst;
wire wSgRxDataRen;
wire wSgRxDataEmpty;
wire [C_DATA_WIDTH-1:0] wSgRxData;
wire [C_SG_FIFO_DEPTH_WIDTH-1:0] wSgRxFifoCount;
wire wSgTxRst;
wire [C_SG_FIFO_DEPTH_WIDTH-1:0] wSgTxFifoCount;
wire wSgRxReq;
wire [63:0] wSgRxReqAddr;
wire [9:0] wSgRxReqLen;
wire wSgTxReq;
wire [63:0] wSgTxReqAddr;
wire [9:0] wSgTxReqLen;
wire wSgRxReqProc;
wire wSgTxReqProc;
wire wMainReqProc;
wire wReqAck;
wire wSgElemRdy;
wire wSgElemRen;
wire [63:0] wSgElemAddr;
wire [31:0] wSgElemLen;
wire wSgRst;
wire wMainReq;
wire [63:0] wMainReqAddr;
wire [9:0] wMainReqLen;
wire wTxnErr;
wire wChnlRx;
wire wChnlRxRecvd;
wire wChnlRxAckRecvd;
wire wChnlRxLast;
wire [31:0] wChnlRxLen;
wire [30:0] wChnlRxOff;
wire [31:0] wChnlRxConsumed;
reg [4:0] rWideRst=0;
reg rRst=0;
assign SG_ERR = (wPackedSgTxDone & wPackedSgTxErr);
// Generate a wide reset from the input reset.
always @ (posedge CLK) begin
rRst <= #1 rWideRst[4];
if (RST)
rWideRst <= #1 5'b11111;
else
rWideRst <= (rWideRst<<1);
end
// Pack received data tightly into our FIFOs
fifo_packer_32 mainFifoPacker (
.CLK(CLK),
.RST(rRst),
.DATA_IN(MAIN_DATA),
.DATA_IN_EN(MAIN_DATA_EN),
.DATA_IN_DONE(MAIN_DONE),
.DATA_IN_ERR(MAIN_ERR),
.DATA_IN_FLUSH(wMainFlush),
.PACKED_DATA(wPackedMainData),
.PACKED_WEN(wPackedMainWen),
.PACKED_DATA_DONE(wPackedMainDone),
.PACKED_DATA_ERR(wPackedMainErr),
.PACKED_DATA_FLUSHED(wMainFlushed)
);
fifo_packer_32 sgRxFifoPacker (
.CLK(CLK),
.RST(rRst),
.DATA_IN(SG_RX_DATA),
.DATA_IN_EN(SG_RX_DATA_EN),
.DATA_IN_DONE(SG_RX_DONE),
.DATA_IN_ERR(SG_RX_ERR),
.DATA_IN_FLUSH(wSgRxFlush),
.PACKED_DATA(wPackedSgRxData),
.PACKED_WEN(wPackedSgRxWen),
.PACKED_DATA_DONE(wPackedSgRxDone),
.PACKED_DATA_ERR(wPackedSgRxErr),
.PACKED_DATA_FLUSHED(wSgRxFlushed)
);
fifo_packer_32 sgTxFifoPacker (
.CLK(CLK),
.RST(rRst),
.DATA_IN(SG_TX_DATA),
.DATA_IN_EN(SG_TX_DATA_EN),
.DATA_IN_DONE(SG_TX_DONE),
.DATA_IN_ERR(SG_TX_ERR),
.DATA_IN_FLUSH(wSgTxFlush),
.PACKED_DATA(wPackedSgTxData),
.PACKED_WEN(wPackedSgTxWen),
.PACKED_DATA_DONE(wPackedSgTxDone),
.PACKED_DATA_ERR(wPackedSgTxErr),
.PACKED_DATA_FLUSHED(wSgTxFlushed)
);
// FIFOs for storing received data for the channel.
(* RAM_STYLE="BLOCK" *)
async_fifo_fwft #(.C_WIDTH(C_DATA_WIDTH), .C_DEPTH(C_MAIN_FIFO_DEPTH)) mainFifo (
.WR_CLK(CLK),
.WR_RST(rRst | (wTxnErr & TXN_DONE) | wSgRst),
.WR_EN(wPackedMainWen),
.WR_DATA(wPackedMainData),
.WR_FULL(),
.RD_CLK(CHNL_CLK),
.RD_RST(rRst | (wTxnErr & TXN_DONE) | wSgRst),
.RD_EN(wMainDataRen),
.RD_DATA(wMainData),
.RD_EMPTY(wMainDataEmpty)
);
(* RAM_STYLE="BLOCK" *)
sync_fifo #(.C_WIDTH(C_DATA_WIDTH), .C_DEPTH(C_SG_FIFO_DEPTH), .C_PROVIDE_COUNT(1)) sgRxFifo (
.RST(rRst | wSgRxRst),
.CLK(CLK),
.WR_EN(wPackedSgRxWen),
.WR_DATA(wPackedSgRxData),
.FULL(),
.RD_EN(wSgRxDataRen),
.RD_DATA(wSgRxData),
.EMPTY(wSgRxDataEmpty),
.COUNT(wSgRxFifoCount)
);
(* RAM_STYLE="BLOCK" *)
sync_fifo #(.C_WIDTH(C_DATA_WIDTH), .C_DEPTH(C_SG_FIFO_DEPTH), .C_PROVIDE_COUNT(1)) sgTxFifo (
.RST(rRst | wSgTxRst),
.CLK(CLK),
.WR_EN(wPackedSgTxWen),
.WR_DATA(wPackedSgTxData),
.FULL(),
.RD_EN(SG_DATA_REN),
.RD_DATA(SG_DATA),
.EMPTY(SG_DATA_EMPTY),
.COUNT(wSgTxFifoCount)
);
// Manage requesting and acknowledging scatter gather data. Note that
// these modules will share the main requestor's RX channel. They will
// take priority over the main logic's use of the RX channel.
sg_list_requester #(.C_FIFO_DATA_WIDTH(C_DATA_WIDTH), .C_FIFO_DEPTH(C_SG_FIFO_DEPTH), .C_MAX_READ_REQ(C_MAX_READ_REQ)) sgRxReq (
.CLK(CLK),
.RST(rRst),
.CONFIG_MAX_READ_REQUEST_SIZE(CONFIG_MAX_READ_REQUEST_SIZE),
.USER_RST(wSgRst),
.BUF_RECVD(SG_RX_BUF_RECVD),
.BUF_DATA(SG_RX_BUF_DATA),
.BUF_LEN_VALID(SG_RX_BUF_LEN_VALID),
.BUF_ADDR_HI_VALID(SG_RX_BUF_ADDR_HI_VALID),
.BUF_ADDR_LO_VALID(SG_RX_BUF_ADDR_LO_VALID),
.FIFO_COUNT(wSgRxFifoCount),
.FIFO_FLUSH(wSgRxFlush),
.FIFO_FLUSHED(wSgRxFlushed),
.FIFO_RST(wSgRxRst),
.RX_REQ(wSgRxReq),
.RX_ADDR(wSgRxReqAddr),
.RX_LEN(wSgRxReqLen),
.RX_REQ_ACK(wReqAck & wSgRxReqProc),
.RX_DONE(wPackedSgRxDone)
);
sg_list_requester #(.C_FIFO_DATA_WIDTH(C_DATA_WIDTH), .C_FIFO_DEPTH(C_SG_FIFO_DEPTH), .C_MAX_READ_REQ(C_MAX_READ_REQ)) sgTxReq (
.CLK(CLK),
.RST(rRst),
.CONFIG_MAX_READ_REQUEST_SIZE(CONFIG_MAX_READ_REQUEST_SIZE),
.USER_RST(SG_RST),
.BUF_RECVD(SG_TX_BUF_RECVD),
.BUF_DATA(SG_TX_BUF_DATA),
.BUF_LEN_VALID(SG_TX_BUF_LEN_VALID),
.BUF_ADDR_HI_VALID(SG_TX_BUF_ADDR_HI_VALID),
.BUF_ADDR_LO_VALID(SG_TX_BUF_ADDR_LO_VALID),
.FIFO_COUNT(wSgTxFifoCount),
.FIFO_FLUSH(wSgTxFlush),
.FIFO_FLUSHED(wSgTxFlushed),
.FIFO_RST(wSgTxRst),
.RX_REQ(wSgTxReq),
.RX_ADDR(wSgTxReqAddr),
.RX_LEN(wSgTxReqLen),
.RX_REQ_ACK(wReqAck & wSgTxReqProc),
.RX_DONE(wPackedSgTxDone)
);
// A read requester for the channel and scatter gather requesters.
rx_port_requester_mux requesterMux (
.RST(rRst),
.CLK(CLK),
.SG_RX_REQ(wSgRxReq),
.SG_RX_LEN(wSgRxReqLen),
.SG_RX_ADDR(wSgRxReqAddr),
.SG_RX_REQ_PROC(wSgRxReqProc),
.SG_TX_REQ(wSgTxReq),
.SG_TX_LEN(wSgTxReqLen),
.SG_TX_ADDR(wSgTxReqAddr),
.SG_TX_REQ_PROC(wSgTxReqProc),
.MAIN_REQ(wMainReq),
.MAIN_LEN(wMainReqLen),
.MAIN_ADDR(wMainReqAddr),
.MAIN_REQ_PROC(wMainReqProc),
.RX_REQ(RX_REQ),
.RX_REQ_ACK(RX_REQ_ACK),
.RX_REQ_TAG(RX_REQ_TAG),
.RX_REQ_ADDR(RX_REQ_ADDR),
.RX_REQ_LEN(RX_REQ_LEN),
.REQ_ACK(wReqAck)
);
// Read the scatter gather buffer address and length, continuously so that
// we have it ready whenever the next buffer is needed.
sg_list_reader_32 #(.C_DATA_WIDTH(C_DATA_WIDTH)) sgListReader (
.CLK(CLK),
.RST(rRst | wSgRst),
.BUF_DATA(wSgRxData),
.BUF_DATA_EMPTY(wSgRxDataEmpty),
.BUF_DATA_REN(wSgRxDataRen),
.VALID(wSgElemRdy),
.EMPTY(),
.REN(wSgElemRen),
.ADDR(wSgElemAddr),
.LEN(wSgElemLen)
);
// Main port reader logic
rx_port_reader #(.C_DATA_WIDTH(C_DATA_WIDTH), .C_FIFO_DEPTH(C_MAIN_FIFO_DEPTH), .C_MAX_READ_REQ(C_MAX_READ_REQ)) reader (
.CLK(CLK),
.RST(rRst),
.CONFIG_MAX_READ_REQUEST_SIZE(CONFIG_MAX_READ_REQUEST_SIZE),
.TXN_DATA(TXN_DATA),
.TXN_LEN_VALID(TXN_LEN_VALID),
.TXN_OFF_LAST_VALID(TXN_OFF_LAST_VALID),
.TXN_DONE_LEN(TXN_DONE_LEN),
.TXN_DONE(TXN_DONE),
.TXN_ERR(wTxnErr),
.TXN_DONE_ACK(TXN_DONE_ACK),
.TXN_DATA_FLUSH(wMainFlush),
.TXN_DATA_FLUSHED(wMainFlushed),
.RX_REQ(wMainReq),
.RX_ADDR(wMainReqAddr),
.RX_LEN(wMainReqLen),
.RX_REQ_ACK(wReqAck & wMainReqProc),
.RX_DATA_EN(MAIN_DATA_EN),
.RX_DONE(wPackedMainDone),
.RX_ERR(wPackedMainErr),
.SG_DONE(wPackedSgRxDone),
.SG_ERR(wPackedSgRxErr),
.SG_ELEM_ADDR(wSgElemAddr),
.SG_ELEM_LEN(wSgElemLen),
.SG_ELEM_RDY(wSgElemRdy),
.SG_ELEM_REN(wSgElemRen),
.SG_RST(wSgRst),
.CHNL_RX(wChnlRx),
.CHNL_RX_LEN(wChnlRxLen),
.CHNL_RX_LAST(wChnlRxLast),
.CHNL_RX_OFF(wChnlRxOff),
.CHNL_RX_RECVD(wChnlRxRecvd),
.CHNL_RX_ACK_RECVD(wChnlRxAckRecvd),
.CHNL_RX_CONSUMED(wChnlRxConsumed)
);
// Manage the CHNL_RX* signals in the CHNL_CLK domain.
rx_port_channel_gate #(.C_DATA_WIDTH(C_DATA_WIDTH)) gate (
.RST(rRst),
.CLK(CLK),
.RX(wChnlRx),
.RX_RECVD(wChnlRxRecvd),
.RX_ACK_RECVD(wChnlRxAckRecvd),
.RX_LAST(wChnlRxLast),
.RX_LEN(wChnlRxLen),
.RX_OFF(wChnlRxOff),
.RX_CONSUMED(wChnlRxConsumed),
.RD_DATA(wMainData),
.RD_EMPTY(wMainDataEmpty),
.RD_EN(wMainDataRen),
.CHNL_CLK(CHNL_CLK),
.CHNL_RX(CHNL_RX),
.CHNL_RX_ACK(CHNL_RX_ACK),
.CHNL_RX_LAST(CHNL_RX_LAST),
.CHNL_RX_LEN(CHNL_RX_LEN),
.CHNL_RX_OFF(CHNL_RX_OFF),
.CHNL_RX_DATA(CHNL_RX_DATA),
.CHNL_RX_DATA_VALID(CHNL_RX_DATA_VALID),
.CHNL_RX_DATA_REN(CHNL_RX_DATA_REN)
);
/*
wire [35:0] wControl0;
chipscope_icon_1 cs_icon(
.CONTROL0(wControl0)
);
chipscope_ila_t8_512 a0(
.CLK(CLK),
.CONTROL(wControl0),
.TRIG0({SG_RX_DATA_EN != 0, wSgElemRen, wMainReq | wSgRxReq | wSgTxReq,
RX_REQ, SG_RX_BUF_ADDR_LO_VALID | SG_RX_BUF_ADDR_HI_VALID | SG_RX_BUF_LEN_VALID,
wSgRst, wTxnErr | wPackedSgRxDone | wSgRxFlush | wSgRxFlushed, TXN_OFF_LAST_VALID | TXN_LEN_VALID}),
.DATA({
wPackedSgRxErr, // 1
wPackedSgRxDone, // 1
wPackedSgRxWen, // 1
wPackedSgRxData, // 64
SG_RX_ERR, // 1
SG_RX_DONE, // 1
SG_RX_DATA_EN, // 2
SG_RX_DATA, // 64
wSgRxDataRen, // 1
wSgRxDataEmpty, // 1
wSgRxData, // 64
wSgRst, // 1
SG_RST, // 1
wPackedSgRxDone, // 1
wSgRxRst, // 1
wSgRxFlushed, // 1
wSgRxFlush, // 1
SG_RX_BUF_ADDR_LO_VALID, // 1
SG_RX_BUF_ADDR_HI_VALID, // 1
SG_RX_BUF_LEN_VALID, // 1
SG_RX_BUF_DATA, // 32
RX_REQ_ADDR, // 64
RX_REQ_TAG, // 2
RX_REQ_ACK, // 1
RX_REQ, // 1
wSgTxReqProc, // 1
wSgTxReqAddr, // 64
wSgTxReq, // 1
wSgRxReqProc, // 1
wSgRxReqAddr, // 64
wSgRxReq, // 1
wMainReqProc, // 1
wMainReqAddr, // 64
wMainReq, // 1
wReqAck, // 1
wTxnErr, // 1
TXN_OFF_LAST_VALID, // 1
TXN_LEN_VALID}) // 1
);
*/
endmodule
|
//*****************************************************************************
// (c) Copyright 2008 - 2013 Xilinx, Inc. All rights reserved.
//
// This file contains confidential and proprietary information
// of Xilinx, Inc. and is protected under U.S. and
// international copyright and other intellectual property
// laws.
//
// DISCLAIMER
// This disclaimer is not a license and does not grant any
// rights to the materials distributed herewith. Except as
// otherwise provided in a valid license issued to you by
// Xilinx, and to the maximum extent permitted by applicable
// law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND
// WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES
// AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
// BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-
// INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and
// (2) Xilinx shall not be liable (whether in contract or tort,
// including negligence, or under any other theory of
// liability) for any loss or damage of any kind or nature
// related to, arising under or in connection with these
// materials, including for any direct, or any indirect,
// special, incidental, or consequential loss or damage
// (including loss of data, profits, goodwill, or any type of
// loss or damage suffered as a result of any action brought
// by a third party) even if such damage or loss was
// reasonably foreseeable or Xilinx had been advised of the
// possibility of the same.
//
// CRITICAL APPLICATIONS
// Xilinx products are not designed or intended to be fail-
// safe, or for use in any application requiring fail-safe
// performance, such as life-support or safety devices or
// systems, Class III medical devices, nuclear facilities,
// applications related to the deployment of airbags, or any
// other applications that could lead to death, personal
// injury, or severe property or environmental damage
// (individually and collectively, "Critical
// Applications"). Customer assumes the sole risk and
// liability of any use of Xilinx products in Critical
// Applications, subject only to applicable laws and
// regulations governing limitations on product liability.
//
// THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS
// PART OF THIS FILE AT ALL TIMES.
//
//*****************************************************************************
// ____ ____
// / /\/ /
// /___/ \ / Vendor : Xilinx
// \ \ \/ Version : %version
// \ \ Application : MIG
// / / Filename : ecc_gen.v
// /___/ /\ Date Last Modified : $date$
// \ \ / \ Date Created : Tue Jun 30 2009
// \___\/\___\
//
//Device : 7-Series
//Design Name : DDR3 SDRAM
//Purpose :
//Reference :
//Revision History :
//*****************************************************************************
`timescale 1ps/1ps
// Generate the ecc code. Note that the synthesizer should
// generate this as a static logic. Code in this block should
// never run during simulation phase, or directly impact timing.
//
// The code generated is a single correct, double detect code.
// It is the classic Hamming code. Instead, the code is
// optimized for minimal/balanced tree depth and size. See
// Hsiao IBM Technial Journal 1970.
//
// The code is returned as a single bit vector, h_rows. This was
// the only way to "subroutinize" this with the restrictions of
// disallowed include files and that matrices cannot be passed
// in ports.
//
// Factorial and the combos functions are defined. Combos
// simply computes the number of combinations from the set
// size and elements at a time.
//
// The function next_combo computes the next combination in
// lexicographical order given the "current" combination. Its
// output is undefined if given the last combination in the
// lexicographical order.
//
// next_combo is insensitive to the number of elements in the
// combinations.
//
// An H transpose matrix is generated because that's the easiest
// way to do it. The H transpose matrix is generated by taking
// the one at a time combinations, then the 3 at a time, then
// the 5 at a time. The number combinations used is equal to
// the width of the code (CODE_WIDTH). The boundaries between
// the 1, 3 and 5 groups are hardcoded in the for loop.
//
// At the same time the h_rows vector is generated from the
// H transpose matrix.
module mig_7series_v1_9_ecc_gen
#(
parameter CODE_WIDTH = 72,
parameter ECC_WIDTH = 8,
parameter DATA_WIDTH = 64
)
(
/*AUTOARG*/
// Outputs
h_rows
);
function integer factorial (input integer i);
integer index;
if (i == 1) factorial = 1;
else begin
factorial = 1;
for (index=2; index<=i; index=index+1)
factorial = factorial * index;
end
endfunction // factorial
function integer combos (input integer n, k);
combos = factorial(n)/(factorial(k)*factorial(n-k));
endfunction // combinations
// function next_combo
// Given a combination, return the next combo in lexicographical
// order. Scans from right to left. Assumes the first combination
// is k ones all of the way to the left.
//
// Upon entry, initialize seen0, trig1, and ones. "seen0" means
// that a zero has been observed while scanning from right to left.
// "trig1" means that a one have been observed _after_ seen0 is set.
// "ones" counts the number of ones observed while scanning the input.
//
// If trig1 is one, just copy the input bit to the output and increment
// to the next bit. Otherwise set the the output bit to zero, if the
// input is a one, increment ones. If the input bit is a one and seen0
// is true, dump out the accumulated ones. Set seen0 to the complement
// of the input bit. Note that seen0 is not used subsequent to trig1
// getting set.
function [ECC_WIDTH-1:0] next_combo (input [ECC_WIDTH-1:0] i);
integer index;
integer dump_index;
reg seen0;
reg trig1;
// integer ones;
reg [ECC_WIDTH-1:0] ones;
begin
seen0 = 1'b0;
trig1 = 1'b0;
ones = 0;
for (index=0; index<ECC_WIDTH; index=index+1)
begin
// The "== 1'bx" is so this will converge at time zero.
// XST assumes false, which should be OK.
if ((&i == 1'bx) || trig1) next_combo[index] = i[index];
else begin
next_combo[index] = 1'b0;
ones = ones + i[index];
if (i[index] && seen0) begin
trig1 = 1'b1;
for (dump_index=index-1; dump_index>=0;dump_index=dump_index-1)
if (dump_index>=index-ones) next_combo[dump_index] = 1'b1;
end
seen0 = ~i[index];
end // else: !if(trig1)
end
end // function
endfunction // next_combo
wire [ECC_WIDTH-1:0] ht_matrix [CODE_WIDTH-1:0];
output wire [CODE_WIDTH*ECC_WIDTH-1:0] h_rows;
localparam COMBOS_3 = combos(ECC_WIDTH, 3);
localparam COMBOS_5 = combos(ECC_WIDTH, 5);
genvar n;
genvar s;
generate
for (n=0; n<CODE_WIDTH; n=n+1) begin : ht
if (n == 0)
assign ht_matrix[n] = {{3{1'b1}}, {ECC_WIDTH-3{1'b0}}};
else if (n == COMBOS_3 && n < DATA_WIDTH)
assign ht_matrix[n] = {{5{1'b1}}, {ECC_WIDTH-5{1'b0}}};
else if ((n == COMBOS_3+COMBOS_5) && n < DATA_WIDTH)
assign ht_matrix[n] = {{7{1'b1}}, {ECC_WIDTH-7{1'b0}}};
else if (n == DATA_WIDTH)
assign ht_matrix[n] = {{1{1'b1}}, {ECC_WIDTH-1{1'b0}}};
else assign ht_matrix[n] = next_combo(ht_matrix[n-1]);
for (s=0; s<ECC_WIDTH; s=s+1) begin : h_row
assign h_rows[s*CODE_WIDTH+n] = ht_matrix[n][s];
end
end
endgenerate
endmodule // ecc_gen
|
//*****************************************************************************
// (c) Copyright 2008 - 2013 Xilinx, Inc. All rights reserved.
//
// This file contains confidential and proprietary information
// of Xilinx, Inc. and is protected under U.S. and
// international copyright and other intellectual property
// laws.
//
// DISCLAIMER
// This disclaimer is not a license and does not grant any
// rights to the materials distributed herewith. Except as
// otherwise provided in a valid license issued to you by
// Xilinx, and to the maximum extent permitted by applicable
// law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND
// WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES
// AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
// BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-
// INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and
// (2) Xilinx shall not be liable (whether in contract or tort,
// including negligence, or under any other theory of
// liability) for any loss or damage of any kind or nature
// related to, arising under or in connection with these
// materials, including for any direct, or any indirect,
// special, incidental, or consequential loss or damage
// (including loss of data, profits, goodwill, or any type of
// loss or damage suffered as a result of any action brought
// by a third party) even if such damage or loss was
// reasonably foreseeable or Xilinx had been advised of the
// possibility of the same.
//
// CRITICAL APPLICATIONS
// Xilinx products are not designed or intended to be fail-
// safe, or for use in any application requiring fail-safe
// performance, such as life-support or safety devices or
// systems, Class III medical devices, nuclear facilities,
// applications related to the deployment of airbags, or any
// other applications that could lead to death, personal
// injury, or severe property or environmental damage
// (individually and collectively, "Critical
// Applications"). Customer assumes the sole risk and
// liability of any use of Xilinx products in Critical
// Applications, subject only to applicable laws and
// regulations governing limitations on product liability.
//
// THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS
// PART OF THIS FILE AT ALL TIMES.
//
//*****************************************************************************
// ____ ____
// / /\/ /
// /___/ \ / Vendor : Xilinx
// \ \ \/ Version : %version
// \ \ Application : MIG
// / / Filename : ecc_gen.v
// /___/ /\ Date Last Modified : $date$
// \ \ / \ Date Created : Tue Jun 30 2009
// \___\/\___\
//
//Device : 7-Series
//Design Name : DDR3 SDRAM
//Purpose :
//Reference :
//Revision History :
//*****************************************************************************
`timescale 1ps/1ps
// Generate the ecc code. Note that the synthesizer should
// generate this as a static logic. Code in this block should
// never run during simulation phase, or directly impact timing.
//
// The code generated is a single correct, double detect code.
// It is the classic Hamming code. Instead, the code is
// optimized for minimal/balanced tree depth and size. See
// Hsiao IBM Technial Journal 1970.
//
// The code is returned as a single bit vector, h_rows. This was
// the only way to "subroutinize" this with the restrictions of
// disallowed include files and that matrices cannot be passed
// in ports.
//
// Factorial and the combos functions are defined. Combos
// simply computes the number of combinations from the set
// size and elements at a time.
//
// The function next_combo computes the next combination in
// lexicographical order given the "current" combination. Its
// output is undefined if given the last combination in the
// lexicographical order.
//
// next_combo is insensitive to the number of elements in the
// combinations.
//
// An H transpose matrix is generated because that's the easiest
// way to do it. The H transpose matrix is generated by taking
// the one at a time combinations, then the 3 at a time, then
// the 5 at a time. The number combinations used is equal to
// the width of the code (CODE_WIDTH). The boundaries between
// the 1, 3 and 5 groups are hardcoded in the for loop.
//
// At the same time the h_rows vector is generated from the
// H transpose matrix.
module mig_7series_v1_9_ecc_gen
#(
parameter CODE_WIDTH = 72,
parameter ECC_WIDTH = 8,
parameter DATA_WIDTH = 64
)
(
/*AUTOARG*/
// Outputs
h_rows
);
function integer factorial (input integer i);
integer index;
if (i == 1) factorial = 1;
else begin
factorial = 1;
for (index=2; index<=i; index=index+1)
factorial = factorial * index;
end
endfunction // factorial
function integer combos (input integer n, k);
combos = factorial(n)/(factorial(k)*factorial(n-k));
endfunction // combinations
// function next_combo
// Given a combination, return the next combo in lexicographical
// order. Scans from right to left. Assumes the first combination
// is k ones all of the way to the left.
//
// Upon entry, initialize seen0, trig1, and ones. "seen0" means
// that a zero has been observed while scanning from right to left.
// "trig1" means that a one have been observed _after_ seen0 is set.
// "ones" counts the number of ones observed while scanning the input.
//
// If trig1 is one, just copy the input bit to the output and increment
// to the next bit. Otherwise set the the output bit to zero, if the
// input is a one, increment ones. If the input bit is a one and seen0
// is true, dump out the accumulated ones. Set seen0 to the complement
// of the input bit. Note that seen0 is not used subsequent to trig1
// getting set.
function [ECC_WIDTH-1:0] next_combo (input [ECC_WIDTH-1:0] i);
integer index;
integer dump_index;
reg seen0;
reg trig1;
// integer ones;
reg [ECC_WIDTH-1:0] ones;
begin
seen0 = 1'b0;
trig1 = 1'b0;
ones = 0;
for (index=0; index<ECC_WIDTH; index=index+1)
begin
// The "== 1'bx" is so this will converge at time zero.
// XST assumes false, which should be OK.
if ((&i == 1'bx) || trig1) next_combo[index] = i[index];
else begin
next_combo[index] = 1'b0;
ones = ones + i[index];
if (i[index] && seen0) begin
trig1 = 1'b1;
for (dump_index=index-1; dump_index>=0;dump_index=dump_index-1)
if (dump_index>=index-ones) next_combo[dump_index] = 1'b1;
end
seen0 = ~i[index];
end // else: !if(trig1)
end
end // function
endfunction // next_combo
wire [ECC_WIDTH-1:0] ht_matrix [CODE_WIDTH-1:0];
output wire [CODE_WIDTH*ECC_WIDTH-1:0] h_rows;
localparam COMBOS_3 = combos(ECC_WIDTH, 3);
localparam COMBOS_5 = combos(ECC_WIDTH, 5);
genvar n;
genvar s;
generate
for (n=0; n<CODE_WIDTH; n=n+1) begin : ht
if (n == 0)
assign ht_matrix[n] = {{3{1'b1}}, {ECC_WIDTH-3{1'b0}}};
else if (n == COMBOS_3 && n < DATA_WIDTH)
assign ht_matrix[n] = {{5{1'b1}}, {ECC_WIDTH-5{1'b0}}};
else if ((n == COMBOS_3+COMBOS_5) && n < DATA_WIDTH)
assign ht_matrix[n] = {{7{1'b1}}, {ECC_WIDTH-7{1'b0}}};
else if (n == DATA_WIDTH)
assign ht_matrix[n] = {{1{1'b1}}, {ECC_WIDTH-1{1'b0}}};
else assign ht_matrix[n] = next_combo(ht_matrix[n-1]);
for (s=0; s<ECC_WIDTH; s=s+1) begin : h_row
assign h_rows[s*CODE_WIDTH+n] = ht_matrix[n][s];
end
end
endgenerate
endmodule // ecc_gen
|
//*****************************************************************************
// (c) Copyright 2008 - 2013 Xilinx, Inc. All rights reserved.
//
// This file contains confidential and proprietary information
// of Xilinx, Inc. and is protected under U.S. and
// international copyright and other intellectual property
// laws.
//
// DISCLAIMER
// This disclaimer is not a license and does not grant any
// rights to the materials distributed herewith. Except as
// otherwise provided in a valid license issued to you by
// Xilinx, and to the maximum extent permitted by applicable
// law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND
// WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES
// AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
// BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-
// INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and
// (2) Xilinx shall not be liable (whether in contract or tort,
// including negligence, or under any other theory of
// liability) for any loss or damage of any kind or nature
// related to, arising under or in connection with these
// materials, including for any direct, or any indirect,
// special, incidental, or consequential loss or damage
// (including loss of data, profits, goodwill, or any type of
// loss or damage suffered as a result of any action brought
// by a third party) even if such damage or loss was
// reasonably foreseeable or Xilinx had been advised of the
// possibility of the same.
//
// CRITICAL APPLICATIONS
// Xilinx products are not designed or intended to be fail-
// safe, or for use in any application requiring fail-safe
// performance, such as life-support or safety devices or
// systems, Class III medical devices, nuclear facilities,
// applications related to the deployment of airbags, or any
// other applications that could lead to death, personal
// injury, or severe property or environmental damage
// (individually and collectively, "Critical
// Applications"). Customer assumes the sole risk and
// liability of any use of Xilinx products in Critical
// Applications, subject only to applicable laws and
// regulations governing limitations on product liability.
//
// THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS
// PART OF THIS FILE AT ALL TIMES.
//
//*****************************************************************************
// ____ ____
// / /\/ /
// /___/ \ / Vendor : Xilinx
// \ \ \/ Version : %version
// \ \ Application : MIG
// / / Filename : ecc_gen.v
// /___/ /\ Date Last Modified : $date$
// \ \ / \ Date Created : Tue Jun 30 2009
// \___\/\___\
//
//Device : 7-Series
//Design Name : DDR3 SDRAM
//Purpose :
//Reference :
//Revision History :
//*****************************************************************************
`timescale 1ps/1ps
// Generate the ecc code. Note that the synthesizer should
// generate this as a static logic. Code in this block should
// never run during simulation phase, or directly impact timing.
//
// The code generated is a single correct, double detect code.
// It is the classic Hamming code. Instead, the code is
// optimized for minimal/balanced tree depth and size. See
// Hsiao IBM Technial Journal 1970.
//
// The code is returned as a single bit vector, h_rows. This was
// the only way to "subroutinize" this with the restrictions of
// disallowed include files and that matrices cannot be passed
// in ports.
//
// Factorial and the combos functions are defined. Combos
// simply computes the number of combinations from the set
// size and elements at a time.
//
// The function next_combo computes the next combination in
// lexicographical order given the "current" combination. Its
// output is undefined if given the last combination in the
// lexicographical order.
//
// next_combo is insensitive to the number of elements in the
// combinations.
//
// An H transpose matrix is generated because that's the easiest
// way to do it. The H transpose matrix is generated by taking
// the one at a time combinations, then the 3 at a time, then
// the 5 at a time. The number combinations used is equal to
// the width of the code (CODE_WIDTH). The boundaries between
// the 1, 3 and 5 groups are hardcoded in the for loop.
//
// At the same time the h_rows vector is generated from the
// H transpose matrix.
module mig_7series_v1_9_ecc_gen
#(
parameter CODE_WIDTH = 72,
parameter ECC_WIDTH = 8,
parameter DATA_WIDTH = 64
)
(
/*AUTOARG*/
// Outputs
h_rows
);
function integer factorial (input integer i);
integer index;
if (i == 1) factorial = 1;
else begin
factorial = 1;
for (index=2; index<=i; index=index+1)
factorial = factorial * index;
end
endfunction // factorial
function integer combos (input integer n, k);
combos = factorial(n)/(factorial(k)*factorial(n-k));
endfunction // combinations
// function next_combo
// Given a combination, return the next combo in lexicographical
// order. Scans from right to left. Assumes the first combination
// is k ones all of the way to the left.
//
// Upon entry, initialize seen0, trig1, and ones. "seen0" means
// that a zero has been observed while scanning from right to left.
// "trig1" means that a one have been observed _after_ seen0 is set.
// "ones" counts the number of ones observed while scanning the input.
//
// If trig1 is one, just copy the input bit to the output and increment
// to the next bit. Otherwise set the the output bit to zero, if the
// input is a one, increment ones. If the input bit is a one and seen0
// is true, dump out the accumulated ones. Set seen0 to the complement
// of the input bit. Note that seen0 is not used subsequent to trig1
// getting set.
function [ECC_WIDTH-1:0] next_combo (input [ECC_WIDTH-1:0] i);
integer index;
integer dump_index;
reg seen0;
reg trig1;
// integer ones;
reg [ECC_WIDTH-1:0] ones;
begin
seen0 = 1'b0;
trig1 = 1'b0;
ones = 0;
for (index=0; index<ECC_WIDTH; index=index+1)
begin
// The "== 1'bx" is so this will converge at time zero.
// XST assumes false, which should be OK.
if ((&i == 1'bx) || trig1) next_combo[index] = i[index];
else begin
next_combo[index] = 1'b0;
ones = ones + i[index];
if (i[index] && seen0) begin
trig1 = 1'b1;
for (dump_index=index-1; dump_index>=0;dump_index=dump_index-1)
if (dump_index>=index-ones) next_combo[dump_index] = 1'b1;
end
seen0 = ~i[index];
end // else: !if(trig1)
end
end // function
endfunction // next_combo
wire [ECC_WIDTH-1:0] ht_matrix [CODE_WIDTH-1:0];
output wire [CODE_WIDTH*ECC_WIDTH-1:0] h_rows;
localparam COMBOS_3 = combos(ECC_WIDTH, 3);
localparam COMBOS_5 = combos(ECC_WIDTH, 5);
genvar n;
genvar s;
generate
for (n=0; n<CODE_WIDTH; n=n+1) begin : ht
if (n == 0)
assign ht_matrix[n] = {{3{1'b1}}, {ECC_WIDTH-3{1'b0}}};
else if (n == COMBOS_3 && n < DATA_WIDTH)
assign ht_matrix[n] = {{5{1'b1}}, {ECC_WIDTH-5{1'b0}}};
else if ((n == COMBOS_3+COMBOS_5) && n < DATA_WIDTH)
assign ht_matrix[n] = {{7{1'b1}}, {ECC_WIDTH-7{1'b0}}};
else if (n == DATA_WIDTH)
assign ht_matrix[n] = {{1{1'b1}}, {ECC_WIDTH-1{1'b0}}};
else assign ht_matrix[n] = next_combo(ht_matrix[n-1]);
for (s=0; s<ECC_WIDTH; s=s+1) begin : h_row
assign h_rows[s*CODE_WIDTH+n] = ht_matrix[n][s];
end
end
endgenerate
endmodule // ecc_gen
|
/***********************************************************
-- (c) Copyright 2010 - 2013 Xilinx, Inc. All rights reserved.
--
-- This file contains confidential and proprietary information
-- of Xilinx, Inc. and is protected under U.S. and
-- international copyright and other intellectual property
-- laws.
--
-- DISCLAIMER
-- This disclaimer is not a license and does not grant any
-- rights to the materials distributed herewith. Except as
-- otherwise provided in a valid license issued to you by
-- Xilinx, and to the maximum extent permitted by applicable
-- law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND
-- WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES
-- AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
-- BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-
-- INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and
-- (2) Xilinx shall not be liable (whether in contract or tort,
-- including negligence, or under any other theory of
-- liability) for any loss or damage of any kind or nature
-- related to, arising under or in connection with these
-- materials, including for any direct, or any indirect,
-- special, incidental, or consequential loss or damage
-- (including loss of data, profits, goodwill, or any type of
-- loss or damage suffered as a result of any action brought
-- by a third party) even if such damage or loss was
-- reasonably foreseeable or Xilinx had been advised of the
-- possibility of the same.
--
-- CRITICAL APPLICATIONS
-- Xilinx products are not designed or intended to be fail-
-- safe, or for use in any application requiring fail-safe
-- performance, such as life-support or safety devices or
-- systems, Class III medical devices, nuclear facilities,
-- applications related to the deployment of airbags, or any
-- other applications that could lead to death, personal
-- injury, or severe property or environmental damage
-- (individually and collectively, "Critical
-- Applications"). A Customer assumes the sole risk and
-- liability of any use of Xilinx products in Critical
-- Applications, subject only to applicable laws and
-- regulations governing limitations on product liability.
--
-- THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS
-- PART OF THIS FILE AT ALL TIMES.
//
//
// Owner: Gary Martin
// Revision: $Id: //depot/icm/proj/common/head/rtl/v32_cmt/rtl/phy/byte_lane.v#4 $
// $Author: gary $
// $DateTime: 2010/05/11 18:05:17 $
// $Change: 490882 $
// Description:
// This verilog file is a parameterizable single 10 or 12 bit byte lane.
//
// History:
// Date Engineer Description
// 04/01/2010 G. Martin Initial Checkin.
//
////////////////////////////////////////////////////////////
***********************************************************/
`timescale 1ps/1ps
//`include "phy.vh"
module mig_7series_v1_9_ddr_byte_lane #(
// these are used to scale the index into phaser,calib,scan,mc vectors
// to access fields used in this instance
parameter ABCD = "A", // A,B,C, or D
parameter PO_DATA_CTL = "FALSE",
parameter BITLANES = 12'b1111_1111_1111,
parameter BITLANES_OUTONLY = 12'b1111_1111_1111,
parameter BYTELANES_DDR_CK = 24'b0010_0010_0010_0010_0010_0010,
parameter RCLK_SELECT_LANE = "B",
parameter PC_CLK_RATIO = 4,
parameter USE_PRE_POST_FIFO = "FALSE",
//OUT_FIFO
parameter OF_ALMOST_EMPTY_VALUE = 1,
parameter OF_ALMOST_FULL_VALUE = 1,
parameter OF_ARRAY_MODE = "UNDECLARED",
parameter OF_OUTPUT_DISABLE = "FALSE",
parameter OF_SYNCHRONOUS_MODE = "TRUE",
//IN_FIFO
parameter IF_ALMOST_EMPTY_VALUE = 1,
parameter IF_ALMOST_FULL_VALUE = 1,
parameter IF_ARRAY_MODE = "UNDECLARED",
parameter IF_SYNCHRONOUS_MODE = "TRUE",
//PHASER_IN
parameter PI_BURST_MODE = "TRUE",
parameter PI_CLKOUT_DIV = 2,
parameter PI_FREQ_REF_DIV = "NONE",
parameter PI_FINE_DELAY = 1,
parameter PI_OUTPUT_CLK_SRC = "DELAYED_REF" , //"DELAYED_REF",
parameter PI_SEL_CLK_OFFSET = 0,
parameter PI_SYNC_IN_DIV_RST = "FALSE",
//PHASER_OUT
parameter PO_CLKOUT_DIV = (PO_DATA_CTL == "FALSE") ? 4 : 2,
parameter PO_FINE_DELAY = 0,
parameter PO_COARSE_BYPASS = "FALSE",
parameter PO_COARSE_DELAY = 0,
parameter PO_OCLK_DELAY = 0,
parameter PO_OCLKDELAY_INV = "TRUE",
parameter PO_OUTPUT_CLK_SRC = "DELAYED_REF",
parameter PO_SYNC_IN_DIV_RST = "FALSE",
// OSERDES
parameter OSERDES_DATA_RATE = "DDR",
parameter OSERDES_DATA_WIDTH = 4,
//IDELAY
parameter IDELAYE2_IDELAY_TYPE = "VARIABLE",
parameter IDELAYE2_IDELAY_VALUE = 00,
parameter IODELAY_GRP = "IODELAY_MIG",
parameter BANK_TYPE = "HP_IO", // # = "HP_IO", "HPL_IO", "HR_IO", "HRL_IO"
parameter real TCK = 0.00,
parameter SYNTHESIS = "FALSE",
// local constants, do not pass in from above
parameter BUS_WIDTH = 12,
parameter MSB_BURST_PEND_PO = 3,
parameter MSB_BURST_PEND_PI = 7,
parameter MSB_RANK_SEL_I = MSB_BURST_PEND_PI + 8,
parameter PHASER_CTL_BUS_WIDTH = MSB_RANK_SEL_I + 1
,parameter CKE_ODT_AUX = "FALSE"
)(
input rst,
input phy_clk,
input freq_refclk,
input mem_refclk,
input idelayctrl_refclk,
input sync_pulse,
output [BUS_WIDTH-1:0] mem_dq_out,
output [BUS_WIDTH-1:0] mem_dq_ts,
input [9:0] mem_dq_in,
output mem_dqs_out,
output mem_dqs_ts,
input mem_dqs_in,
output [11:0] ddr_ck_out,
output rclk,
input if_empty_def,
output if_a_empty,
output if_empty,
output if_a_full,
output if_full,
output of_a_empty,
output of_empty,
output of_a_full,
output of_full,
output pre_fifo_a_full,
output [79:0] phy_din,
input [79:0] phy_dout,
input phy_cmd_wr_en,
input phy_data_wr_en,
input phy_rd_en,
input [PHASER_CTL_BUS_WIDTH-1:0] phaser_ctl_bus,
input idelay_inc,
input idelay_ce,
input idelay_ld,
input if_rst,
input [2:0] byte_rd_en_oth_lanes,
input [1:0] byte_rd_en_oth_banks,
output byte_rd_en,
output po_coarse_overflow,
output po_fine_overflow,
output [8:0] po_counter_read_val,
input po_fine_enable,
input po_coarse_enable,
input [1:0] po_en_calib,
input po_fine_inc,
input po_coarse_inc,
input po_counter_load_en,
input po_counter_read_en,
input po_sel_fine_oclk_delay,
input [8:0] po_counter_load_val,
input [1:0] pi_en_calib,
input pi_rst_dqs_find,
input pi_fine_enable,
input pi_fine_inc,
input pi_counter_load_en,
input pi_counter_read_en,
input [5:0] pi_counter_load_val,
output wire pi_iserdes_rst,
output pi_phase_locked,
output pi_fine_overflow,
output [5:0] pi_counter_read_val,
output wire pi_dqs_found,
output dqs_out_of_range
);
localparam PHASER_INDEX =
(ABCD=="B" ? 1 : (ABCD == "C") ? 2 : (ABCD == "D" ? 3 : 0));
localparam L_OF_ARRAY_MODE =
(OF_ARRAY_MODE != "UNDECLARED") ? OF_ARRAY_MODE :
(PO_DATA_CTL == "FALSE" || PC_CLK_RATIO == 2) ? "ARRAY_MODE_4_X_4" : "ARRAY_MODE_8_X_4";
localparam L_IF_ARRAY_MODE = (IF_ARRAY_MODE != "UNDECLARED") ? IF_ARRAY_MODE :
(PC_CLK_RATIO == 2) ? "ARRAY_MODE_4_X_4" : "ARRAY_MODE_4_X_8";
localparam L_OSERDES_DATA_RATE = (OSERDES_DATA_RATE != "UNDECLARED") ? OSERDES_DATA_RATE : ((PO_DATA_CTL == "FALSE" && PC_CLK_RATIO == 4) ? "SDR" : "DDR") ;
localparam L_OSERDES_DATA_WIDTH = (OSERDES_DATA_WIDTH != "UNDECLARED") ? OSERDES_DATA_WIDTH : 4;
localparam real L_FREQ_REF_PERIOD_NS = TCK > 2500.0 ? (TCK/(PI_FREQ_REF_DIV == "DIV2" ? 2 : 1)/1000.0) : TCK/1000.0;
localparam real L_MEM_REF_PERIOD_NS = TCK/1000.0;
localparam real L_PHASE_REF_PERIOD_NS = TCK/1000.0;
localparam ODDR_CLK_EDGE = "SAME_EDGE";
localparam PO_DCD_CORRECTION = "ON";
localparam [2:0] PO_DCD_SETTING = (PO_DCD_CORRECTION == "ON") ? 3'b111 : 3'b000;
localparam DQS_AUTO_RECAL = (BANK_TYPE == "HR_IO" || BANK_TYPE == "HRL_IO" || (BANK_TYPE == "HPL_IO" && TCK > 2500)) ? 1 : 0;
localparam DQS_FIND_PATTERN = (BANK_TYPE == "HR_IO" || BANK_TYPE == "HRL_IO" || (BANK_TYPE == "HPL_IO" && TCK > 2500)) ? "001" : "000";
wire [1:0] oserdes_dqs;
wire [1:0] oserdes_dqs_ts;
wire [1:0] oserdes_dq_ts;
wire [3:0] of_q9;
wire [3:0] of_q8;
wire [3:0] of_q7;
wire [7:0] of_q6;
wire [7:0] of_q5;
wire [3:0] of_q4;
wire [3:0] of_q3;
wire [3:0] of_q2;
wire [3:0] of_q1;
wire [3:0] of_q0;
wire [7:0] of_d9;
wire [7:0] of_d8;
wire [7:0] of_d7;
wire [7:0] of_d6;
wire [7:0] of_d5;
wire [7:0] of_d4;
wire [7:0] of_d3;
wire [7:0] of_d2;
wire [7:0] of_d1;
wire [7:0] of_d0;
wire [7:0] if_q9;
wire [7:0] if_q8;
wire [7:0] if_q7;
wire [7:0] if_q6;
wire [7:0] if_q5;
wire [7:0] if_q4;
wire [7:0] if_q3;
wire [7:0] if_q2;
wire [7:0] if_q1;
wire [7:0] if_q0;
wire [3:0] if_d9;
wire [3:0] if_d8;
wire [3:0] if_d7;
wire [3:0] if_d6;
wire [3:0] if_d5;
wire [3:0] if_d4;
wire [3:0] if_d3;
wire [3:0] if_d2;
wire [3:0] if_d1;
wire [3:0] if_d0;
wire [3:0] dummy_i5;
wire [3:0] dummy_i6;
wire [48-1:0] of_dqbus;
wire [10*4-1:0] iserdes_dout;
wire iserdes_clk;
wire iserdes_clkdiv;
wire ififo_wr_enable;
wire phy_rd_en_;
wire dqs_to_phaser;
wire phy_wr_en = ( PO_DATA_CTL == "FALSE" ) ? phy_cmd_wr_en : phy_data_wr_en;
wire if_empty_;
wire if_a_empty_;
wire if_full_;
wire if_a_full_;
wire po_oserdes_rst;
wire empty_post_fifo;
(* keep = "true", max_fanout = 3 *) reg [3:0] if_empty_r /* synthesis syn_maxfan = 3 */;
wire [79:0] rd_data;
reg [79:0] rd_data_r;
/////////////////////////////////////////////////////////////////////////
///This is a temporary fix until we get a proper fix for CR#638064///////
/////////////////////////////////////////////////////////////////////////
reg ififo_rst = 1'b1;
reg ofifo_rst = 1'b1;
/////////////////////////////////////////////////////////////////////////
wire of_wren_pre;
wire [79:0] pre_fifo_dout;
wire pre_fifo_full;
wire pre_fifo_rden;
wire [5:0] ddr_ck_out_q;
(* keep = "true", max_fanout = 10 *) wire ififo_rd_en_in /* synthesis syn_maxfan = 10 */;
always @(posedge phy_clk) begin
ififo_rst <= #1 pi_rst_dqs_find | if_rst ;
// reset only data o-fifos on reset of dqs_found
ofifo_rst <= #1 (pi_rst_dqs_find & PO_DATA_CTL == "TRUE") | rst;
end
// IN_FIFO EMPTY->RDEN TIMING FIX:
// Always read from IN_FIFO - it doesn't hurt to read from an empty FIFO
// since the IN_FIFO read pointers are not incr'ed when the FIFO is empty
assign #(25) phy_rd_en_ = 1'b1;
//assign #(25) phy_rd_en_ = phy_rd_en;
generate
if ( PO_DATA_CTL == "FALSE" ) begin : if_empty_null
assign if_empty = 0;
assign if_a_empty = 0;
assign if_full = 0;
assign if_a_full = 0;
end
else begin : if_empty_gen
assign if_empty = empty_post_fifo;
assign if_a_empty = if_a_empty_;
assign if_full = if_full_;
assign if_a_full = if_a_full_;
end
endgenerate
generate
if ( PO_DATA_CTL == "FALSE" ) begin : dq_gen_48
assign of_dqbus[48-1:0] = {of_q6[7:4], of_q5[7:4], of_q9, of_q8, of_q7, of_q6[3:0], of_q5[3:0], of_q4, of_q3, of_q2, of_q1, of_q0};
assign phy_din = 80'h0;
assign byte_rd_en = 1'b1;
end
else begin : dq_gen_40
assign of_dqbus[40-1:0] = {of_q9, of_q8, of_q7, of_q6[3:0], of_q5[3:0], of_q4, of_q3, of_q2, of_q1, of_q0};
assign ififo_rd_en_in = !if_empty_def ? ((&byte_rd_en_oth_banks) && (&byte_rd_en_oth_lanes) && byte_rd_en) :
((|byte_rd_en_oth_banks) || (|byte_rd_en_oth_lanes) || byte_rd_en);
if (USE_PRE_POST_FIFO == "TRUE") begin : if_post_fifo_gen
// IN_FIFO EMPTY->RDEN TIMING FIX:
assign rd_data = {if_q9, if_q8, if_q7, if_q6, if_q5, if_q4, if_q3, if_q2, if_q1, if_q0};
always @(posedge phy_clk) begin
rd_data_r <= #(025) rd_data;
if_empty_r[0] <= #(025) if_empty_;
if_empty_r[1] <= #(025) if_empty_;
if_empty_r[2] <= #(025) if_empty_;
if_empty_r[3] <= #(025) if_empty_;
end
mig_7series_v1_9_ddr_if_post_fifo #
(
.TCQ (25), // simulation CK->Q delay
.DEPTH (4), //2 // depth - account for up to 2 cycles of skew
.WIDTH (80) // width
)
u_ddr_if_post_fifo
(
.clk (phy_clk),
.rst (ififo_rst),
.empty_in (if_empty_r),
.rd_en_in (ififo_rd_en_in),
.d_in (rd_data_r),
.empty_out (empty_post_fifo),
.byte_rd_en (byte_rd_en),
.d_out (phy_din)
);
end
else begin : phy_din_gen
assign phy_din = {if_q9, if_q8, if_q7, if_q6, if_q5, if_q4, if_q3, if_q2, if_q1, if_q0};
assign empty_post_fifo = if_empty_;
end
end
endgenerate
assign { if_d9, if_d8, if_d7, if_d6, if_d5, if_d4, if_d3, if_d2, if_d1, if_d0} = iserdes_dout;
wire [1:0] rank_sel_i = ((phaser_ctl_bus[MSB_RANK_SEL_I :MSB_RANK_SEL_I -7] >> (PHASER_INDEX << 1)) & 2'b11);
generate
if ( USE_PRE_POST_FIFO == "TRUE" ) begin : of_pre_fifo_gen
assign {of_d9, of_d8, of_d7, of_d6, of_d5, of_d4, of_d3, of_d2, of_d1, of_d0} = pre_fifo_dout;
mig_7series_v1_9_ddr_of_pre_fifo #
(
.TCQ (25), // simulation CK->Q delay
.DEPTH (9), // depth - set to 9 to accommodate flow control
.WIDTH (80) // width
)
u_ddr_of_pre_fifo
(
.clk (phy_clk),
/////////////////////////////////////////////////////////////////////////
///This is a temporary fix until we get a proper fix for CR#638064///////
/////////////////////////////////////////////////////////////////////////
.rst (ofifo_rst),
/////////////////////////////////////////////////////////////////////////
.full_in (of_full),
.wr_en_in (phy_wr_en),
.d_in (phy_dout),
.wr_en_out (of_wren_pre),
.d_out (pre_fifo_dout),
.afull (pre_fifo_a_full)
);
end
else begin
// wire direct to ofifo
assign {of_d9, of_d8, of_d7, of_d6, of_d5, of_d4, of_d3, of_d2, of_d1, of_d0} = phy_dout;
assign of_wren_pre = phy_wr_en;
end
endgenerate
generate
if ( PO_DATA_CTL == "TRUE" || ((RCLK_SELECT_LANE==ABCD) && (CKE_ODT_AUX =="TRUE"))) begin : phaser_in_gen
PHASER_IN_PHY #(
.BURST_MODE ( PI_BURST_MODE),
.CLKOUT_DIV ( PI_CLKOUT_DIV),
.DQS_AUTO_RECAL ( DQS_AUTO_RECAL),
.DQS_FIND_PATTERN ( DQS_FIND_PATTERN),
.SEL_CLK_OFFSET ( PI_SEL_CLK_OFFSET),
.FINE_DELAY ( PI_FINE_DELAY),
.FREQ_REF_DIV ( PI_FREQ_REF_DIV),
.OUTPUT_CLK_SRC ( PI_OUTPUT_CLK_SRC),
.SYNC_IN_DIV_RST ( PI_SYNC_IN_DIV_RST),
.REFCLK_PERIOD ( L_FREQ_REF_PERIOD_NS),
.MEMREFCLK_PERIOD ( L_MEM_REF_PERIOD_NS),
.PHASEREFCLK_PERIOD ( L_PHASE_REF_PERIOD_NS)
) phaser_in (
.DQSFOUND (pi_dqs_found),
.DQSOUTOFRANGE (dqs_out_of_range),
.FINEOVERFLOW (pi_fine_overflow),
.PHASELOCKED (pi_phase_locked),
.ISERDESRST (pi_iserdes_rst),
.ICLKDIV (iserdes_clkdiv),
.ICLK (iserdes_clk),
.COUNTERREADVAL (pi_counter_read_val),
.RCLK (rclk),
.WRENABLE (ififo_wr_enable),
.BURSTPENDINGPHY (phaser_ctl_bus[MSB_BURST_PEND_PI - 3 + PHASER_INDEX]),
.ENCALIBPHY (pi_en_calib),
.FINEENABLE (pi_fine_enable),
.FREQREFCLK (freq_refclk),
.MEMREFCLK (mem_refclk),
.RANKSELPHY (rank_sel_i),
.PHASEREFCLK (dqs_to_phaser),
.RSTDQSFIND (pi_rst_dqs_find),
.RST (rst),
.FINEINC (pi_fine_inc),
.COUNTERLOADEN (pi_counter_load_en),
.COUNTERREADEN (pi_counter_read_en),
.COUNTERLOADVAL (pi_counter_load_val),
.SYNCIN (sync_pulse),
.SYSCLK (phy_clk)
);
end
else begin
assign pi_dqs_found = 1'b1;
assign pi_dqs_out_of_range = 1'b0;
assign pi_phase_locked = 1'b1;
end
endgenerate
wire #0 phase_ref = freq_refclk;
wire oserdes_clk;
PHASER_OUT_PHY #(
.CLKOUT_DIV ( PO_CLKOUT_DIV),
.DATA_CTL_N ( PO_DATA_CTL ),
.FINE_DELAY ( PO_FINE_DELAY),
.COARSE_BYPASS ( PO_COARSE_BYPASS ),
.COARSE_DELAY ( PO_COARSE_DELAY),
.OCLK_DELAY ( PO_OCLK_DELAY),
.OCLKDELAY_INV ( PO_OCLKDELAY_INV),
.OUTPUT_CLK_SRC ( PO_OUTPUT_CLK_SRC),
.SYNC_IN_DIV_RST ( PO_SYNC_IN_DIV_RST),
.REFCLK_PERIOD ( L_FREQ_REF_PERIOD_NS),
.PHASEREFCLK_PERIOD ( 1), // dummy, not used
.PO ( PO_DCD_SETTING ),
.MEMREFCLK_PERIOD ( L_MEM_REF_PERIOD_NS)
) phaser_out (
.COARSEOVERFLOW (po_coarse_overflow),
.CTSBUS (oserdes_dqs_ts),
.DQSBUS (oserdes_dqs),
.DTSBUS (oserdes_dq_ts),
.FINEOVERFLOW (po_fine_overflow),
.OCLKDIV (oserdes_clkdiv),
.OCLK (oserdes_clk),
.OCLKDELAYED (oserdes_clk_delayed),
.COUNTERREADVAL (po_counter_read_val),
.BURSTPENDINGPHY (phaser_ctl_bus[MSB_BURST_PEND_PO -3 + PHASER_INDEX]),
.ENCALIBPHY (po_en_calib),
.RDENABLE (po_rd_enable),
.FREQREFCLK (freq_refclk),
.MEMREFCLK (mem_refclk),
.PHASEREFCLK (/*phase_ref*/),
.RST (rst),
.OSERDESRST (po_oserdes_rst),
.COARSEENABLE (po_coarse_enable),
.FINEENABLE (po_fine_enable),
.COARSEINC (po_coarse_inc),
.FINEINC (po_fine_inc),
.SELFINEOCLKDELAY (po_sel_fine_oclk_delay),
.COUNTERLOADEN (po_counter_load_en),
.COUNTERREADEN (po_counter_read_en),
.COUNTERLOADVAL (po_counter_load_val),
.SYNCIN (sync_pulse),
.SYSCLK (phy_clk)
);
generate
if (PO_DATA_CTL == "TRUE") begin : in_fifo_gen
IN_FIFO #(
.ALMOST_EMPTY_VALUE ( IF_ALMOST_EMPTY_VALUE ),
.ALMOST_FULL_VALUE ( IF_ALMOST_FULL_VALUE ),
.ARRAY_MODE ( L_IF_ARRAY_MODE),
.SYNCHRONOUS_MODE ( IF_SYNCHRONOUS_MODE)
) in_fifo (
.ALMOSTEMPTY (if_a_empty_),
.ALMOSTFULL (if_a_full_),
.EMPTY (if_empty_),
.FULL (if_full_),
.Q0 (if_q0),
.Q1 (if_q1),
.Q2 (if_q2),
.Q3 (if_q3),
.Q4 (if_q4),
.Q5 (if_q5),
.Q6 (if_q6),
.Q7 (if_q7),
.Q8 (if_q8),
.Q9 (if_q9),
//===
.D0 (if_d0),
.D1 (if_d1),
.D2 (if_d2),
.D3 (if_d3),
.D4 (if_d4),
.D5 ({dummy_i5,if_d5}),
.D6 ({dummy_i6,if_d6}),
.D7 (if_d7),
.D8 (if_d8),
.D9 (if_d9),
.RDCLK (phy_clk),
.RDEN (phy_rd_en_),
.RESET (ififo_rst),
.WRCLK (iserdes_clkdiv),
.WREN (ififo_wr_enable)
);
end
endgenerate
OUT_FIFO #(
.ALMOST_EMPTY_VALUE (OF_ALMOST_EMPTY_VALUE),
.ALMOST_FULL_VALUE (OF_ALMOST_FULL_VALUE),
.ARRAY_MODE (L_OF_ARRAY_MODE),
.OUTPUT_DISABLE (OF_OUTPUT_DISABLE),
.SYNCHRONOUS_MODE (OF_SYNCHRONOUS_MODE)
) out_fifo (
.ALMOSTEMPTY (of_a_empty),
.ALMOSTFULL (of_a_full),
.EMPTY (of_empty),
.FULL (of_full),
.Q0 (of_q0),
.Q1 (of_q1),
.Q2 (of_q2),
.Q3 (of_q3),
.Q4 (of_q4),
.Q5 (of_q5),
.Q6 (of_q6),
.Q7 (of_q7),
.Q8 (of_q8),
.Q9 (of_q9),
.D0 (of_d0),
.D1 (of_d1),
.D2 (of_d2),
.D3 (of_d3),
.D4 (of_d4),
.D5 (of_d5),
.D6 (of_d6),
.D7 (of_d7),
.D8 (of_d8),
.D9 (of_d9),
.RDCLK (oserdes_clkdiv),
.RDEN (po_rd_enable),
.RESET (ofifo_rst),
.WRCLK (phy_clk),
.WREN (of_wren_pre)
);
mig_7series_v1_9_ddr_byte_group_io #
(
.PO_DATA_CTL (PO_DATA_CTL),
.BITLANES (BITLANES),
.BITLANES_OUTONLY (BITLANES_OUTONLY),
.OSERDES_DATA_RATE (L_OSERDES_DATA_RATE),
.OSERDES_DATA_WIDTH (L_OSERDES_DATA_WIDTH),
.IODELAY_GRP (IODELAY_GRP),
.IDELAYE2_IDELAY_TYPE (IDELAYE2_IDELAY_TYPE),
.IDELAYE2_IDELAY_VALUE (IDELAYE2_IDELAY_VALUE),
.SYNTHESIS (SYNTHESIS)
)
ddr_byte_group_io
(
.mem_dq_out (mem_dq_out),
.mem_dq_ts (mem_dq_ts),
.mem_dq_in (mem_dq_in),
.mem_dqs_in (mem_dqs_in),
.mem_dqs_out (mem_dqs_out),
.mem_dqs_ts (mem_dqs_ts),
.rst (rst),
.oserdes_rst (po_oserdes_rst),
.iserdes_rst (pi_iserdes_rst ),
.iserdes_dout (iserdes_dout),
.dqs_to_phaser (dqs_to_phaser),
.phy_clk (phy_clk),
.iserdes_clk (iserdes_clk),
.iserdes_clkb (!iserdes_clk),
.iserdes_clkdiv (iserdes_clkdiv),
.idelay_inc (idelay_inc),
.idelay_ce (idelay_ce),
.idelay_ld (idelay_ld),
.idelayctrl_refclk (idelayctrl_refclk),
.oserdes_clk (oserdes_clk),
.oserdes_clk_delayed (oserdes_clk_delayed),
.oserdes_clkdiv (oserdes_clkdiv),
.oserdes_dqs ({oserdes_dqs[1], oserdes_dqs[0]}),
.oserdes_dqsts ({oserdes_dqs_ts[1], oserdes_dqs_ts[0]}),
.oserdes_dq (of_dqbus),
.oserdes_dqts ({oserdes_dq_ts[1], oserdes_dq_ts[0]})
);
genvar i;
generate
for (i = 0; i <= 5; i = i+1) begin : ddr_ck_gen_loop
if (PO_DATA_CTL== "FALSE" && (BYTELANES_DDR_CK[i*4+PHASER_INDEX])) begin : ddr_ck_gen
ODDR #(.DDR_CLK_EDGE (ODDR_CLK_EDGE))
ddr_ck (
.C (oserdes_clk),
.R (1'b0),
.S (),
.D1 (1'b0),
.D2 (1'b1),
.CE (1'b1),
.Q (ddr_ck_out_q[i])
);
OBUFDS ddr_ck_obuf (.I(ddr_ck_out_q[i]), .O(ddr_ck_out[i*2]), .OB(ddr_ck_out[i*2+1]));
end // ddr_ck_gen
else begin : ddr_ck_null
assign ddr_ck_out[i*2+1:i*2] = 2'b0;
end
end // ddr_ck_gen_loop
endgenerate
endmodule // byte_lane
|
(************************************************************************)
(* v * The Coq Proof Assistant / The Coq Development Team *)
(* <O___,, * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2015 *)
(* \VV/ **************************************************************)
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
Require Import ZAxioms ZMulOrder ZSgnAbs ZGcd ZDivTrunc ZDivFloor.
(** * Least Common Multiple *)
(** Unlike other functions around, we will define lcm below instead of
axiomatizing it. Indeed, there is no "prior art" about lcm in the
standard library to be compliant with, and the generic definition
of lcm via gcd is quite reasonable.
By the way, we also state here some combined properties of div/mod
and quot/rem and gcd.
*)
Module Type ZLcmProp
(Import A : ZAxiomsSig')
(Import B : ZMulOrderProp A)
(Import C : ZSgnAbsProp A B)
(Import D : ZDivProp A B C)
(Import E : ZQuotProp A B C)
(Import F : ZGcdProp A B C).
(** The two notions of division are equal on non-negative numbers *)
Lemma quot_div_nonneg : forall a b, 0<=a -> 0<b -> a÷b == a/b.
Proof.
intros. apply div_unique_pos with (a rem b).
now apply rem_bound_pos.
apply quot_rem. order.
Qed.
Lemma rem_mod_nonneg : forall a b, 0<=a -> 0<b -> a rem b == a mod b.
Proof.
intros. apply mod_unique_pos with (a÷b).
now apply rem_bound_pos.
apply quot_rem. order.
Qed.
(** We can use the sign rule to have an relation between divisions. *)
Lemma quot_div : forall a b, b~=0 ->
a÷b == (sgn a)*(sgn b)*(abs a / abs b).
Proof.
assert (AUX : forall a b, 0<b -> a÷b == (sgn a)*(sgn b)*(abs a / abs b)).
intros a b Hb. rewrite (sgn_pos b), (abs_eq b), mul_1_r by order.
destruct (lt_trichotomy 0 a) as [Ha|[Ha|Ha]].
rewrite sgn_pos, abs_eq, mul_1_l, quot_div_nonneg; order.
rewrite <- Ha, abs_0, sgn_0, quot_0_l, div_0_l, mul_0_l; order.
rewrite sgn_neg, abs_neq, mul_opp_l, mul_1_l, eq_opp_r, <-quot_opp_l
by order.
apply quot_div_nonneg; trivial. apply opp_nonneg_nonpos; order.
(* main *)
intros a b Hb.
apply neg_pos_cases in Hb. destruct Hb as [Hb|Hb]; [|now apply AUX].
rewrite <- (opp_involutive b) at 1. rewrite quot_opp_r.
rewrite AUX, abs_opp, sgn_opp, mul_opp_r, mul_opp_l, opp_involutive.
reflexivity.
now apply opp_pos_neg.
rewrite eq_opp_l, opp_0; order.
Qed.
Lemma rem_mod : forall a b, b~=0 ->
a rem b == (sgn a) * ((abs a) mod (abs b)).
Proof.
intros a b Hb.
rewrite <- rem_abs_r by trivial.
assert (Hb' := proj2 (abs_pos b) Hb).
destruct (lt_trichotomy 0 a) as [Ha|[Ha|Ha]].
rewrite (abs_eq a), sgn_pos, mul_1_l, rem_mod_nonneg; order.
rewrite <- Ha, abs_0, sgn_0, mod_0_l, rem_0_l, mul_0_l; order.
rewrite sgn_neg, (abs_neq a), mul_opp_l, mul_1_l, eq_opp_r, <-rem_opp_l
by order.
apply rem_mod_nonneg; trivial. apply opp_nonneg_nonpos; order.
Qed.
(** Modulo and remainder are null at the same place,
and this correspond to the divisibility relation. *)
Lemma mod_divide : forall a b, b~=0 -> (a mod b == 0 <-> (b|a)).
Proof.
intros a b Hb. split.
intros Hab. exists (a/b). rewrite mul_comm.
rewrite (div_mod a b Hb) at 1. rewrite Hab; now nzsimpl.
intros (c,Hc). rewrite Hc. now apply mod_mul.
Qed.
Lemma rem_divide : forall a b, b~=0 -> (a rem b == 0 <-> (b|a)).
Proof.
intros a b Hb. split.
intros Hab. exists (a÷b). rewrite mul_comm.
rewrite (quot_rem a b Hb) at 1. rewrite Hab; now nzsimpl.
intros (c,Hc). rewrite Hc. now apply rem_mul.
Qed.
Lemma rem_mod_eq_0 : forall a b, b~=0 -> (a rem b == 0 <-> a mod b == 0).
Proof.
intros a b Hb. now rewrite mod_divide, rem_divide.
Qed.
(** When division is exact, div and quot agree *)
Lemma quot_div_exact : forall a b, b~=0 -> (b|a) -> a÷b == a/b.
Proof.
intros a b Hb H.
apply mul_cancel_l with b; trivial.
assert (H':=H).
apply rem_divide, quot_exact in H; trivial.
apply mod_divide, div_exact in H'; trivial.
now rewrite <-H,<-H'.
Qed.
Lemma divide_div_mul_exact : forall a b c, b~=0 -> (b|a) ->
(c*a)/b == c*(a/b).
Proof.
intros a b c Hb H.
apply mul_cancel_l with b; trivial.
rewrite mul_assoc, mul_shuffle0.
assert (H':=H). apply mod_divide, div_exact in H'; trivial.
rewrite <- H', (mul_comm a c).
symmetry. apply div_exact; trivial.
apply mod_divide; trivial.
now apply divide_mul_r.
Qed.
Lemma divide_quot_mul_exact : forall a b c, b~=0 -> (b|a) ->
(c*a)÷b == c*(a÷b).
Proof.
intros a b c Hb H.
rewrite 2 quot_div_exact; trivial.
apply divide_div_mul_exact; trivial.
now apply divide_mul_r.
Qed.
(** Gcd of divided elements, for exact divisions *)
Lemma gcd_div_factor : forall a b c, 0<c -> (c|a) -> (c|b) ->
gcd (a/c) (b/c) == (gcd a b)/c.
Proof.
intros a b c Hc Ha Hb.
apply mul_cancel_l with c; try order.
assert (H:=gcd_greatest _ _ _ Ha Hb).
apply mod_divide, div_exact in H; try order.
rewrite <- H.
rewrite <- gcd_mul_mono_l_nonneg; try order.
f_equiv; symmetry; apply div_exact; try order;
apply mod_divide; trivial; try order.
Qed.
Lemma gcd_quot_factor : forall a b c, 0<c -> (c|a) -> (c|b) ->
gcd (a÷c) (b÷c) == (gcd a b)÷c.
Proof.
intros a b c Hc Ha Hb. rewrite !quot_div_exact; trivial; try order.
now apply gcd_div_factor. now apply gcd_greatest.
Qed.
Lemma gcd_div_gcd : forall a b g, g~=0 -> g == gcd a b ->
gcd (a/g) (b/g) == 1.
Proof.
intros a b g NZ EQ. rewrite gcd_div_factor.
now rewrite <- EQ, div_same.
generalize (gcd_nonneg a b); order.
rewrite EQ; apply gcd_divide_l.
rewrite EQ; apply gcd_divide_r.
Qed.
Lemma gcd_quot_gcd : forall a b g, g~=0 -> g == gcd a b ->
gcd (a÷g) (b÷g) == 1.
Proof.
intros a b g NZ EQ. rewrite !quot_div_exact; trivial.
now apply gcd_div_gcd.
rewrite EQ; apply gcd_divide_r.
rewrite EQ; apply gcd_divide_l.
Qed.
(** The following equality is crucial for Euclid algorithm *)
Lemma gcd_mod : forall a b, b~=0 -> gcd (a mod b) b == gcd b a.
Proof.
intros a b Hb. rewrite mod_eq; trivial.
rewrite <- add_opp_r, mul_comm, <- mul_opp_l.
rewrite (gcd_comm _ b).
apply gcd_add_mult_diag_r.
Qed.
Lemma gcd_rem : forall a b, b~=0 -> gcd (a rem b) b == gcd b a.
Proof.
intros a b Hb. rewrite rem_eq; trivial.
rewrite <- add_opp_r, mul_comm, <- mul_opp_l.
rewrite (gcd_comm _ b).
apply gcd_add_mult_diag_r.
Qed.
(** We now define lcm thanks to gcd:
lcm a b = a * (b / gcd a b)
= (a / gcd a b) * b
= (a*b) / gcd a b
We had an abs in order to have an always-nonnegative lcm,
in the spirit of gcd. Nota: [lcm 0 0] should be 0, which
isn't garantee with the third equation above.
*)
Definition lcm a b := abs (a*(b/gcd a b)).
Instance lcm_wd : Proper (eq==>eq==>eq) lcm.
Proof. unfold lcm. solve_proper. Qed.
Lemma lcm_equiv1 : forall a b, gcd a b ~= 0 ->
a * (b / gcd a b) == (a*b)/gcd a b.
Proof.
intros a b H. rewrite divide_div_mul_exact; try easy. apply gcd_divide_r.
Qed.
Lemma lcm_equiv2 : forall a b, gcd a b ~= 0 ->
(a / gcd a b) * b == (a*b)/gcd a b.
Proof.
intros a b H. rewrite 2 (mul_comm _ b).
rewrite divide_div_mul_exact; try easy. apply gcd_divide_l.
Qed.
Lemma gcd_div_swap : forall a b,
(a / gcd a b) * b == a * (b / gcd a b).
Proof.
intros a b. destruct (eq_decidable (gcd a b) 0) as [EQ|NEQ].
apply gcd_eq_0 in EQ. destruct EQ as (EQ,EQ'). rewrite EQ, EQ'. now nzsimpl.
now rewrite lcm_equiv1, <-lcm_equiv2.
Qed.
Lemma divide_lcm_l : forall a b, (a | lcm a b).
Proof.
unfold lcm. intros a b. apply divide_abs_r, divide_factor_l.
Qed.
Lemma divide_lcm_r : forall a b, (b | lcm a b).
Proof.
unfold lcm. intros a b. apply divide_abs_r. rewrite <- gcd_div_swap.
apply divide_factor_r.
Qed.
Lemma divide_div : forall a b c, a~=0 -> (a|b) -> (b|c) -> (b/a|c/a).
Proof.
intros a b c Ha Hb (c',Hc). exists c'.
now rewrite <- divide_div_mul_exact, <- Hc.
Qed.
Lemma lcm_least : forall a b c,
(a | c) -> (b | c) -> (lcm a b | c).
Proof.
intros a b c Ha Hb. unfold lcm. apply divide_abs_l.
destruct (eq_decidable (gcd a b) 0) as [EQ|NEQ].
apply gcd_eq_0 in EQ. destruct EQ as (EQ,EQ'). rewrite EQ in *. now nzsimpl.
assert (Ga := gcd_divide_l a b).
assert (Gb := gcd_divide_r a b).
set (g:=gcd a b) in *.
assert (Ha' := divide_div g a c NEQ Ga Ha).
assert (Hb' := divide_div g b c NEQ Gb Hb).
destruct Ha' as (a',Ha'). rewrite Ha', mul_comm in Hb'.
apply gauss in Hb'; [|apply gcd_div_gcd; unfold g; trivial using gcd_comm].
destruct Hb' as (b',Hb').
exists b'.
rewrite mul_shuffle3, <- Hb'.
rewrite (proj2 (div_exact c g NEQ)).
rewrite Ha', mul_shuffle3, (mul_comm a a'). f_equiv.
symmetry. apply div_exact; trivial.
apply mod_divide; trivial.
apply mod_divide; trivial. transitivity a; trivial.
Qed.
Lemma lcm_nonneg : forall a b, 0 <= lcm a b.
Proof.
intros a b. unfold lcm. apply abs_nonneg.
Qed.
Lemma lcm_comm : forall a b, lcm a b == lcm b a.
Proof.
intros a b. unfold lcm. rewrite (gcd_comm b), (mul_comm b).
now rewrite <- gcd_div_swap.
Qed.
Lemma lcm_divide_iff : forall n m p,
(lcm n m | p) <-> (n | p) /\ (m | p).
Proof.
intros. split. split.
transitivity (lcm n m); trivial using divide_lcm_l.
transitivity (lcm n m); trivial using divide_lcm_r.
intros (H,H'). now apply lcm_least.
Qed.
Lemma lcm_unique : forall n m p,
0<=p -> (n|p) -> (m|p) ->
(forall q, (n|q) -> (m|q) -> (p|q)) ->
lcm n m == p.
Proof.
intros n m p Hp Hn Hm H.
apply divide_antisym_nonneg; trivial. apply lcm_nonneg.
now apply lcm_least.
apply H. apply divide_lcm_l. apply divide_lcm_r.
Qed.
Lemma lcm_unique_alt : forall n m p, 0<=p ->
(forall q, (p|q) <-> (n|q) /\ (m|q)) ->
lcm n m == p.
Proof.
intros n m p Hp H.
apply lcm_unique; trivial.
apply H, divide_refl.
apply H, divide_refl.
intros. apply H. now split.
Qed.
Lemma lcm_assoc : forall n m p, lcm n (lcm m p) == lcm (lcm n m) p.
Proof.
intros. apply lcm_unique_alt; try apply lcm_nonneg.
intros. now rewrite !lcm_divide_iff, and_assoc.
Qed.
Lemma lcm_0_l : forall n, lcm 0 n == 0.
Proof.
intros. apply lcm_unique; trivial. order.
apply divide_refl.
apply divide_0_r.
Qed.
Lemma lcm_0_r : forall n, lcm n 0 == 0.
Proof.
intros. now rewrite lcm_comm, lcm_0_l.
Qed.
Lemma lcm_1_l_nonneg : forall n, 0<=n -> lcm 1 n == n.
Proof.
intros. apply lcm_unique; trivial using divide_1_l, le_0_1, divide_refl.
Qed.
Lemma lcm_1_r_nonneg : forall n, 0<=n -> lcm n 1 == n.
Proof.
intros. now rewrite lcm_comm, lcm_1_l_nonneg.
Qed.
Lemma lcm_diag_nonneg : forall n, 0<=n -> lcm n n == n.
Proof.
intros. apply lcm_unique; trivial using divide_refl.
Qed.
Lemma lcm_eq_0 : forall n m, lcm n m == 0 <-> n == 0 \/ m == 0.
Proof.
intros. split.
intros EQ.
apply eq_mul_0.
apply divide_0_l. rewrite <- EQ. apply lcm_least.
apply divide_factor_l. apply divide_factor_r.
destruct 1 as [EQ|EQ]; rewrite EQ. apply lcm_0_l. apply lcm_0_r.
Qed.
Lemma divide_lcm_eq_r : forall n m, 0<=m -> (n|m) -> lcm n m == m.
Proof.
intros n m Hm H. apply lcm_unique_alt; trivial.
intros q. split. split; trivial. now transitivity m.
now destruct 1.
Qed.
Lemma divide_lcm_iff : forall n m, 0<=m -> ((n|m) <-> lcm n m == m).
Proof.
intros n m Hn. split. now apply divide_lcm_eq_r.
intros EQ. rewrite <- EQ. apply divide_lcm_l.
Qed.
Lemma lcm_opp_l : forall n m, lcm (-n) m == lcm n m.
Proof.
intros. apply lcm_unique_alt; try apply lcm_nonneg.
intros. rewrite divide_opp_l. apply lcm_divide_iff.
Qed.
Lemma lcm_opp_r : forall n m, lcm n (-m) == lcm n m.
Proof.
intros. now rewrite lcm_comm, lcm_opp_l, lcm_comm.
Qed.
Lemma lcm_abs_l : forall n m, lcm (abs n) m == lcm n m.
Proof.
intros. destruct (abs_eq_or_opp n) as [H|H]; rewrite H.
easy. apply lcm_opp_l.
Qed.
Lemma lcm_abs_r : forall n m, lcm n (abs m) == lcm n m.
Proof.
intros. now rewrite lcm_comm, lcm_abs_l, lcm_comm.
Qed.
Lemma lcm_1_l : forall n, lcm 1 n == abs n.
Proof.
intros. rewrite <- lcm_abs_r. apply lcm_1_l_nonneg, abs_nonneg.
Qed.
Lemma lcm_1_r : forall n, lcm n 1 == abs n.
Proof.
intros. now rewrite lcm_comm, lcm_1_l.
Qed.
Lemma lcm_diag : forall n, lcm n n == abs n.
Proof.
intros. rewrite <- lcm_abs_l, <- lcm_abs_r.
apply lcm_diag_nonneg, abs_nonneg.
Qed.
Lemma lcm_mul_mono_l :
forall n m p, lcm (p * n) (p * m) == abs p * lcm n m.
Proof.
intros n m p.
destruct (eq_decidable p 0) as [Hp|Hp].
rewrite Hp. nzsimpl. rewrite lcm_0_l, abs_0. now nzsimpl.
destruct (eq_decidable (gcd n m) 0) as [Hg|Hg].
apply gcd_eq_0 in Hg. destruct Hg as (Hn,Hm); rewrite Hn, Hm.
nzsimpl. rewrite lcm_0_l. now nzsimpl.
unfold lcm.
rewrite gcd_mul_mono_l.
rewrite !abs_mul, mul_assoc. f_equiv.
rewrite <- (abs_sgn p) at 1. rewrite <- mul_assoc.
rewrite div_mul_cancel_l; trivial.
rewrite divide_div_mul_exact; trivial. rewrite abs_mul.
rewrite <- (sgn_abs (sgn p)), sgn_sgn.
destruct (sgn_spec p) as [(_,EQ)|[(EQ,_)|(_,EQ)]].
rewrite EQ. now nzsimpl. order.
rewrite EQ. rewrite mul_opp_l, mul_opp_r, opp_involutive. now nzsimpl.
apply gcd_divide_r.
contradict Hp. now apply abs_0_iff.
Qed.
Lemma lcm_mul_mono_l_nonneg :
forall n m p, 0<=p -> lcm (p*n) (p*m) == p * lcm n m.
Proof.
intros. rewrite <- (abs_eq p) at 3; trivial. apply lcm_mul_mono_l.
Qed.
Lemma lcm_mul_mono_r :
forall n m p, lcm (n * p) (m * p) == lcm n m * abs p.
Proof.
intros n m p. now rewrite !(mul_comm _ p), lcm_mul_mono_l, mul_comm.
Qed.
Lemma lcm_mul_mono_r_nonneg :
forall n m p, 0<=p -> lcm (n*p) (m*p) == lcm n m * p.
Proof.
intros. rewrite <- (abs_eq p) at 3; trivial. apply lcm_mul_mono_r.
Qed.
Lemma gcd_1_lcm_mul : forall n m, n~=0 -> m~=0 ->
(gcd n m == 1 <-> lcm n m == abs (n*m)).
Proof.
intros n m Hn Hm. split; intros H.
unfold lcm. rewrite H. now rewrite div_1_r.
unfold lcm in *.
rewrite !abs_mul in H. apply mul_cancel_l in H; [|now rewrite abs_0_iff].
assert (H' := gcd_divide_r n m).
assert (Hg : gcd n m ~= 0) by (red; rewrite gcd_eq_0; destruct 1; order).
apply mod_divide in H'; trivial. apply div_exact in H'; trivial.
assert (m / gcd n m ~=0) by (contradict Hm; rewrite H', Hm; now nzsimpl).
rewrite <- (mul_1_l (abs (_/_))) in H.
rewrite H' in H at 3. rewrite abs_mul in H.
apply mul_cancel_r in H; [|now rewrite abs_0_iff].
rewrite abs_eq in H. order. apply gcd_nonneg.
Qed.
End ZLcmProp.
|
//*****************************************************************************
// (c) Copyright 2008 - 2013 Xilinx, Inc. All rights reserved.
//
// This file contains confidential and proprietary information
// of Xilinx, Inc. and is protected under U.S. and
// international copyright and other intellectual property
// laws.
//
// DISCLAIMER
// This disclaimer is not a license and does not grant any
// rights to the materials distributed herewith. Except as
// otherwise provided in a valid license issued to you by
// Xilinx, and to the maximum extent permitted by applicable
// law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND
// WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES
// AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
// BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-
// INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and
// (2) Xilinx shall not be liable (whether in contract or tort,
// including negligence, or under any other theory of
// liability) for any loss or damage of any kind or nature
// related to, arising under or in connection with these
// materials, including for any direct, or any indirect,
// special, incidental, or consequential loss or damage
// (including loss of data, profits, goodwill, or any type of
// loss or damage suffered as a result of any action brought
// by a third party) even if such damage or loss was
// reasonably foreseeable or Xilinx had been advised of the
// possibility of the same.
//
// CRITICAL APPLICATIONS
// Xilinx products are not designed or intended to be fail-
// safe, or for use in any application requiring fail-safe
// performance, such as life-support or safety devices or
// systems, Class III medical devices, nuclear facilities,
// applications related to the deployment of airbags, or any
// other applications that could lead to death, personal
// injury, or severe property or environmental damage
// (individually and collectively, "Critical
// Applications"). Customer assumes the sole risk and
// liability of any use of Xilinx products in Critical
// Applications, subject only to applicable laws and
// regulations governing limitations on product liability.
//
// THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS
// PART OF THIS FILE AT ALL TIMES.
//
//*****************************************************************************
// ____ ____
// / /\/ /
// /___/ \ / Vendor : Xilinx
// \ \ \/ Version : %version
// \ \ Application : MIG
// / / Filename : ui_cmd.v
// /___/ /\ Date Last Modified : $date$
// \ \ / \ Date Created : Tue Jun 30 2009
// \___\/\___\
//
//Device : 7-Series
//Design Name : DDR3 SDRAM
//Purpose :
//Reference :
//Revision History :
//*****************************************************************************
`timescale 1 ps / 1 ps
// User interface command port.
module mig_7series_v1_9_ui_cmd #
(
parameter TCQ = 100,
parameter ADDR_WIDTH = 33,
parameter BANK_WIDTH = 3,
parameter COL_WIDTH = 12,
parameter DATA_BUF_ADDR_WIDTH = 5,
parameter RANK_WIDTH = 2,
parameter ROW_WIDTH = 16,
parameter RANKS = 4,
parameter MEM_ADDR_ORDER = "BANK_ROW_COLUMN"
)
(/*AUTOARG*/
// Outputs
app_rdy, use_addr, rank, bank, row, col, size, cmd, hi_priority,
rd_accepted, wr_accepted, data_buf_addr,
// Inputs
rst, clk, accept_ns, rd_buf_full, wr_req_16, app_addr, app_cmd,
app_sz, app_hi_pri, app_en, wr_data_buf_addr, rd_data_buf_addr_r
);
input rst;
input clk;
input accept_ns;
input rd_buf_full;
input wr_req_16;
wire app_rdy_ns = accept_ns && ~rd_buf_full && ~wr_req_16;
(* keep = "true", max_fanout = 10 *) reg app_rdy_r = 1'b0 /* synthesis syn_maxfan = 10 */;
always @(posedge clk) app_rdy_r <= #TCQ app_rdy_ns;
output wire app_rdy;
assign app_rdy = app_rdy_r;
input [ADDR_WIDTH-1:0] app_addr;
input [2:0] app_cmd;
input app_sz;
input app_hi_pri;
input app_en;
reg [ADDR_WIDTH-1:0] app_addr_r1 = {ADDR_WIDTH{1'b0}};
reg [ADDR_WIDTH-1:0] app_addr_r2 = {ADDR_WIDTH{1'b0}};
reg [2:0] app_cmd_r1;
reg [2:0] app_cmd_r2;
reg app_sz_r1;
reg app_sz_r2;
reg app_hi_pri_r1;
reg app_hi_pri_r2;
reg app_en_r1;
reg app_en_r2;
wire [ADDR_WIDTH-1:0] app_addr_ns1 = app_rdy_r && app_en ? app_addr : app_addr_r1;
wire [ADDR_WIDTH-1:0] app_addr_ns2 = app_rdy_r ? app_addr_r1 : app_addr_r2;
wire [2:0] app_cmd_ns1 = app_rdy_r ? app_cmd : app_cmd_r1;
wire [2:0] app_cmd_ns2 = app_rdy_r ? app_cmd_r1 : app_cmd_r2;
wire app_sz_ns1 = app_rdy_r ? app_sz : app_sz_r1;
wire app_sz_ns2 = app_rdy_r ? app_sz_r1 : app_sz_r2;
wire app_hi_pri_ns1 = app_rdy_r ? app_hi_pri : app_hi_pri_r1;
wire app_hi_pri_ns2 = app_rdy_r ? app_hi_pri_r1 : app_hi_pri_r2;
wire app_en_ns1 = ~rst && (app_rdy_r ? app_en : app_en_r1);
wire app_en_ns2 = ~rst && (app_rdy_r ? app_en_r1 : app_en_r2);
always @(posedge clk) begin
if (rst) begin
app_addr_r1 <= #TCQ {ADDR_WIDTH{1'b0}};
app_addr_r2 <= #TCQ {ADDR_WIDTH{1'b0}};
end else begin
app_addr_r1 <= #TCQ app_addr_ns1;
app_addr_r2 <= #TCQ app_addr_ns2;
end
app_cmd_r1 <= #TCQ app_cmd_ns1;
app_cmd_r2 <= #TCQ app_cmd_ns2;
app_sz_r1 <= #TCQ app_sz_ns1;
app_sz_r2 <= #TCQ app_sz_ns2;
app_hi_pri_r1 <= #TCQ app_hi_pri_ns1;
app_hi_pri_r2 <= #TCQ app_hi_pri_ns2;
app_en_r1 <= #TCQ app_en_ns1;
app_en_r2 <= #TCQ app_en_ns2;
end // always @ (posedge clk)
wire use_addr_lcl = app_en_r2 && app_rdy_r;
output wire use_addr;
assign use_addr = use_addr_lcl;
output wire [RANK_WIDTH-1:0] rank;
output wire [BANK_WIDTH-1:0] bank;
output wire [ROW_WIDTH-1:0] row;
output wire [COL_WIDTH-1:0] col;
output wire size;
output wire [2:0] cmd;
output wire hi_priority;
/* assign col = app_rdy_r
? app_addr_r1[0+:COL_WIDTH]
: app_addr_r2[0+:COL_WIDTH];*/
generate
begin
if (MEM_ADDR_ORDER == "TG_TEST")
begin
assign col[4:0] = app_rdy_r
? app_addr_r1[0+:5]
: app_addr_r2[0+:5];
if (RANKS==1)
begin
assign col[COL_WIDTH-1:COL_WIDTH-2] = app_rdy_r
? app_addr_r1[5+3+BANK_WIDTH+:2]
: app_addr_r2[5+3+BANK_WIDTH+:2];
assign col[COL_WIDTH-3:5] = app_rdy_r
? app_addr_r1[5+3+BANK_WIDTH+2+2+:COL_WIDTH-7]
: app_addr_r2[5+3+BANK_WIDTH+2+2+:COL_WIDTH-7];
end
else
begin
assign col[COL_WIDTH-1:COL_WIDTH-2] = app_rdy_r
? app_addr_r1[5+3+BANK_WIDTH+RANK_WIDTH+:2]
: app_addr_r2[5+3+BANK_WIDTH+RANK_WIDTH+:2];
assign col[COL_WIDTH-3:5] = app_rdy_r
? app_addr_r1[5+3+BANK_WIDTH+RANK_WIDTH+2+2+:COL_WIDTH-7]
: app_addr_r2[5+3+BANK_WIDTH+RANK_WIDTH+2+2+:COL_WIDTH-7];
end
assign row[2:0] = app_rdy_r
? app_addr_r1[5+:3]
: app_addr_r2[5+:3];
if (RANKS==1)
begin
assign row[ROW_WIDTH-1:ROW_WIDTH-2] = app_rdy_r
? app_addr_r1[5+3+BANK_WIDTH+2+:2]
: app_addr_r2[5+3+BANK_WIDTH+2+:2];
assign row[ROW_WIDTH-3:3] = app_rdy_r
? app_addr_r1[5+3+BANK_WIDTH+2+2+COL_WIDTH-7+:ROW_WIDTH-5]
: app_addr_r2[5+3+BANK_WIDTH+2+2+COL_WIDTH-7+:ROW_WIDTH-5];
end
else
begin
assign row[ROW_WIDTH-1:ROW_WIDTH-2] = app_rdy_r
? app_addr_r1[5+3+BANK_WIDTH+RANK_WIDTH+2+:2]
: app_addr_r2[5+3+BANK_WIDTH+RANK_WIDTH+2+:2];
assign row[ROW_WIDTH-3:3] = app_rdy_r
? app_addr_r1[5+3+BANK_WIDTH+RANK_WIDTH+2+2+COL_WIDTH-7+:ROW_WIDTH-5]
: app_addr_r2[5+3+BANK_WIDTH+RANK_WIDTH+2+2+COL_WIDTH-7+:ROW_WIDTH-5];
end
assign bank = app_rdy_r
? app_addr_r1[5+3+:BANK_WIDTH]
: app_addr_r2[5+3+:BANK_WIDTH];
assign rank = (RANKS == 1)
? 1'b0
: app_rdy_r
? app_addr_r1[5+3+BANK_WIDTH+:RANK_WIDTH]
: app_addr_r2[5+3+BANK_WIDTH+:RANK_WIDTH];
end
else if (MEM_ADDR_ORDER == "ROW_BANK_COLUMN")
begin
assign col = app_rdy_r
? app_addr_r1[0+:COL_WIDTH]
: app_addr_r2[0+:COL_WIDTH];
assign row = app_rdy_r
? app_addr_r1[COL_WIDTH+BANK_WIDTH+:ROW_WIDTH]
: app_addr_r2[COL_WIDTH+BANK_WIDTH+:ROW_WIDTH];
assign bank = app_rdy_r
? app_addr_r1[COL_WIDTH+:BANK_WIDTH]
: app_addr_r2[COL_WIDTH+:BANK_WIDTH];
assign rank = (RANKS == 1)
? 1'b0
: app_rdy_r
? app_addr_r1[COL_WIDTH+ROW_WIDTH+BANK_WIDTH+:RANK_WIDTH]
: app_addr_r2[COL_WIDTH+ROW_WIDTH+BANK_WIDTH+:RANK_WIDTH];
end
else
begin
assign col = app_rdy_r
? app_addr_r1[0+:COL_WIDTH]
: app_addr_r2[0+:COL_WIDTH];
assign row = app_rdy_r
? app_addr_r1[COL_WIDTH+:ROW_WIDTH]
: app_addr_r2[COL_WIDTH+:ROW_WIDTH];
assign bank = app_rdy_r
? app_addr_r1[COL_WIDTH+ROW_WIDTH+:BANK_WIDTH]
: app_addr_r2[COL_WIDTH+ROW_WIDTH+:BANK_WIDTH];
assign rank = (RANKS == 1)
? 1'b0
: app_rdy_r
? app_addr_r1[COL_WIDTH+ROW_WIDTH+BANK_WIDTH+:RANK_WIDTH]
: app_addr_r2[COL_WIDTH+ROW_WIDTH+BANK_WIDTH+:RANK_WIDTH];
end
end
endgenerate
/* assign rank = (RANKS == 1)
? 1'b0
: app_rdy_r
? app_addr_r1[COL_WIDTH+ROW_WIDTH+BANK_WIDTH+:RANK_WIDTH]
: app_addr_r2[COL_WIDTH+ROW_WIDTH+BANK_WIDTH+:RANK_WIDTH];*/
assign size = app_rdy_r
? app_sz_r1
: app_sz_r2;
assign cmd = app_rdy_r
? app_cmd_r1
: app_cmd_r2;
assign hi_priority = app_rdy_r
? app_hi_pri_r1
: app_hi_pri_r2;
wire request_accepted = use_addr_lcl && app_rdy_r;
wire rd = app_cmd_r2[1:0] == 2'b01;
wire wr = app_cmd_r2[1:0] == 2'b00;
wire wr_bytes = app_cmd_r2[1:0] == 2'b11;
wire write = wr || wr_bytes;
output wire rd_accepted;
assign rd_accepted = request_accepted && rd;
output wire wr_accepted;
assign wr_accepted = request_accepted && write;
input [DATA_BUF_ADDR_WIDTH-1:0] wr_data_buf_addr;
input [DATA_BUF_ADDR_WIDTH-1:0] rd_data_buf_addr_r;
output wire [DATA_BUF_ADDR_WIDTH-1:0] data_buf_addr;
assign data_buf_addr = ~write ? rd_data_buf_addr_r : wr_data_buf_addr;
endmodule // ui_cmd
// Local Variables:
// verilog-library-directories:(".")
// End:
|
//*****************************************************************************
// (c) Copyright 2008 - 2013 Xilinx, Inc. All rights reserved.
//
// This file contains confidential and proprietary information
// of Xilinx, Inc. and is protected under U.S. and
// international copyright and other intellectual property
// laws.
//
// DISCLAIMER
// This disclaimer is not a license and does not grant any
// rights to the materials distributed herewith. Except as
// otherwise provided in a valid license issued to you by
// Xilinx, and to the maximum extent permitted by applicable
// law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND
// WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES
// AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
// BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-
// INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and
// (2) Xilinx shall not be liable (whether in contract or tort,
// including negligence, or under any other theory of
// liability) for any loss or damage of any kind or nature
// related to, arising under or in connection with these
// materials, including for any direct, or any indirect,
// special, incidental, or consequential loss or damage
// (including loss of data, profits, goodwill, or any type of
// loss or damage suffered as a result of any action brought
// by a third party) even if such damage or loss was
// reasonably foreseeable or Xilinx had been advised of the
// possibility of the same.
//
// CRITICAL APPLICATIONS
// Xilinx products are not designed or intended to be fail-
// safe, or for use in any application requiring fail-safe
// performance, such as life-support or safety devices or
// systems, Class III medical devices, nuclear facilities,
// applications related to the deployment of airbags, or any
// other applications that could lead to death, personal
// injury, or severe property or environmental damage
// (individually and collectively, "Critical
// Applications"). Customer assumes the sole risk and
// liability of any use of Xilinx products in Critical
// Applications, subject only to applicable laws and
// regulations governing limitations on product liability.
//
// THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS
// PART OF THIS FILE AT ALL TIMES.
//
//*****************************************************************************
// ____ ____
// / /\/ /
// /___/ \ / Vendor : Xilinx
// \ \ \/ Version : %version
// \ \ Application : MIG
// / / Filename : mc.v
// /___/ /\ Date Last Modified : $date$
// \ \ / \ Date Created : Tue Jun 30 2009
// \___\/\___\
//
//Device : 7-Series
//Design Name : DDR3 SDRAM
//Purpose :
//Reference :
//Revision History :
//*****************************************************************************
//*****************************************************************************
// Top level memory sequencer structural block. This block
// instantiates the rank, bank, and column machines.
//*****************************************************************************
`timescale 1ps/1ps
module mig_7series_v1_9_mc #
(
parameter TCQ = 100, // clk->out delay(sim only)
parameter ADDR_CMD_MODE = "1T", // registered or
// 1Tfered mem?
parameter BANK_WIDTH = 3, // bank address width
parameter BM_CNT_WIDTH = 2, // # BM counter width
// i.e., log2(nBANK_MACHS)
parameter BURST_MODE = "8", // Burst length
parameter CL = 5, // Read CAS latency
// (in clk cyc)
parameter CMD_PIPE_PLUS1 = "ON", // add register stage
// between MC and PHY
parameter COL_WIDTH = 12, // column address width
parameter CS_WIDTH = 4, // # of unique CS outputs
parameter CWL = 5, // Write CAS latency
// (in clk cyc)
parameter DATA_BUF_ADDR_WIDTH = 8, // User request tag (e.g.
// user src/dest buf addr)
parameter DATA_BUF_OFFSET_WIDTH = 1, // User buffer offset width
parameter DATA_WIDTH = 64, // Data bus width
parameter DQ_WIDTH = 64, // # of DQ (data)
parameter DQS_WIDTH = 8, // # of DQS (strobe)
parameter DRAM_TYPE = "DDR3", // Memory I/F type:
// "DDR3", "DDR2"
parameter ECC = "OFF", // ECC ON/OFF?
parameter ECC_WIDTH = 8, // # of ECC bits
parameter MAINT_PRESCALER_PERIOD= 200000, // maintenance period (ps)
parameter MC_ERR_ADDR_WIDTH = 31, // # of error address bits
parameter nBANK_MACHS = 4, // # of bank machines (BM)
parameter nCK_PER_CLK = 4, // DRAM clock : MC clock
// frequency ratio
parameter nCS_PER_RANK = 1, // # of unique CS outputs
// per rank
parameter nREFRESH_BANK = 1, // # of REF cmds to pull-in
parameter nSLOTS = 1, // # DIMM slots in system
parameter ORDERING = "NORM", // request ordering mode
parameter PAYLOAD_WIDTH = 64, // Width of data payload
// from PHY
parameter RANK_WIDTH = 2, // # of bits to count ranks
parameter RANKS = 4, // # of ranks of DRAM
parameter REG_CTRL = "ON", // "ON" for registered DIMM
parameter ROW_WIDTH = 16, // row address width
parameter RTT_NOM = "40", // Nominal ODT value
parameter RTT_WR = "120", // Write ODT value
parameter SLOT_0_CONFIG = 8'b0000_0101, // ranks allowed in slot 0
parameter SLOT_1_CONFIG = 8'b0000_1010, // ranks allowed in slot 1
parameter STARVE_LIMIT = 2, // max # of times a user
// request is allowed to
// lose arbitration when
// reordering is enabled
parameter tCK = 2500, // memory clk period(ps)
parameter tCKE = 10000, // CKE minimum pulse (ps)
parameter tFAW = 40000, // four activate window(ps)
parameter tRAS = 37500, // ACT->PRE cmd period (ps)
parameter tRCD = 12500, // ACT->R/W delay (ps)
parameter tREFI = 7800000, // average periodic
// refresh interval(ps)
parameter CKE_ODT_AUX = "FALSE", //Parameter to turn on/off the aux_out signal
parameter tRFC = 110000, // REF->ACT/REF delay (ps)
parameter tRP = 12500, // PRE cmd period (ps)
parameter tRRD = 10000, // ACT->ACT period (ps)
parameter tRTP = 7500, // Read->PRE cmd delay (ps)
parameter tWTR = 7500, // Internal write->read
// delay (ps)
// requiring DLL lock (CKs)
parameter tZQCS = 64, // ZQCS cmd period (CKs)
parameter tZQI = 128_000_000, // ZQCS interval (ps)
parameter tPRDI = 1_000_000, // pS
parameter USER_REFRESH = "OFF" // Whether user manages REF
)
(
// System inputs
input clk,
input rst,
// Physical memory slot presence
input [7:0] slot_0_present,
input [7:0] slot_1_present,
// Native Interface
input [2:0] cmd,
input [DATA_BUF_ADDR_WIDTH-1:0] data_buf_addr,
input hi_priority,
input size,
input [BANK_WIDTH-1:0] bank,
input [COL_WIDTH-1:0] col,
input [RANK_WIDTH-1:0] rank,
input [ROW_WIDTH-1:0] row,
input use_addr,
input [2*nCK_PER_CLK*PAYLOAD_WIDTH-1:0] wr_data,
input [2*nCK_PER_CLK*DATA_WIDTH/8-1:0] wr_data_mask,
output accept,
output accept_ns,
output [BM_CNT_WIDTH-1:0] bank_mach_next,
output wire [2*nCK_PER_CLK*PAYLOAD_WIDTH-1:0] rd_data,
output [DATA_BUF_ADDR_WIDTH-1:0] rd_data_addr,
output rd_data_en,
output rd_data_end,
output [DATA_BUF_OFFSET_WIDTH-1:0] rd_data_offset,
(* keep = "true", max_fanout = 30 *) output reg [DATA_BUF_ADDR_WIDTH-1:0] wr_data_addr /* synthesis syn_maxfan = 30 */,
output reg wr_data_en,
(* keep = "true", max_fanout = 30 *) output reg [DATA_BUF_OFFSET_WIDTH-1:0] wr_data_offset /* synthesis syn_maxfan = 30 */,
output mc_read_idle,
output mc_ref_zq_wip,
// ECC interface
input correct_en,
input [2*nCK_PER_CLK-1:0] raw_not_ecc,
output [MC_ERR_ADDR_WIDTH-1:0] ecc_err_addr,
output [2*nCK_PER_CLK-1:0] ecc_single,
output [2*nCK_PER_CLK-1:0] ecc_multiple,
// User maintenance requests
input app_periodic_rd_req,
input app_ref_req,
input app_zq_req,
input app_sr_req,
output app_sr_active,
output app_ref_ack,
output app_zq_ack,
// MC <==> PHY Interface
output reg [nCK_PER_CLK-1:0] mc_ras_n,
output reg [nCK_PER_CLK-1:0] mc_cas_n,
output reg [nCK_PER_CLK-1:0] mc_we_n,
output reg [nCK_PER_CLK*ROW_WIDTH-1:0] mc_address,
output reg [nCK_PER_CLK*BANK_WIDTH-1:0] mc_bank,
output reg [CS_WIDTH*nCS_PER_RANK*nCK_PER_CLK-1:0] mc_cs_n,
output reg [1:0] mc_odt,
output reg [nCK_PER_CLK-1:0] mc_cke,
output wire mc_reset_n,
output wire [2*nCK_PER_CLK*DQ_WIDTH-1:0] mc_wrdata,
output wire [2*nCK_PER_CLK*DQ_WIDTH/8-1:0]mc_wrdata_mask,
output reg mc_wrdata_en,
output wire mc_cmd_wren,
output wire mc_ctl_wren,
output reg [2:0] mc_cmd,
output reg [5:0] mc_data_offset,
output reg [5:0] mc_data_offset_1,
output reg [5:0] mc_data_offset_2,
output reg [1:0] mc_cas_slot,
output reg [3:0] mc_aux_out0,
output reg [3:0] mc_aux_out1,
output reg [1:0] mc_rank_cnt,
input phy_mc_ctl_full,
input phy_mc_cmd_full,
input phy_mc_data_full,
input [2*nCK_PER_CLK*DQ_WIDTH-1:0] phy_rd_data,
input phy_rddata_valid,
input init_calib_complete,
input [6*RANKS-1:0] calib_rd_data_offset,
input [6*RANKS-1:0] calib_rd_data_offset_1,
input [6*RANKS-1:0] calib_rd_data_offset_2
);
assign mc_reset_n = 1'b1; // never reset memory
assign mc_cmd_wren = 1'b1; // always write CMD FIFO(issue DSEL when idle)
assign mc_ctl_wren = 1'b1; // always write CTL FIFO(issue nondata when idle)
// Ensure there is always at least one rank present during operation
`ifdef MC_SVA
ranks_present: assert property
(@(posedge clk) (rst || (|(slot_0_present | slot_1_present))));
`endif
// Reserved. Do not change.
localparam nPHY_WRLAT = 2;
// always delay write data control unless ECC mode is enabled
localparam DELAY_WR_DATA_CNTRL = ECC == "ON" ? 0 : 1;
// Ensure that write control is delayed for appropriate CWL
/*`ifdef MC_SVA
delay_wr_data_zero_CWL_le_6: assert property
(@(posedge clk) ((CWL > 6) || (DELAY_WR_DATA_CNTRL == 0)));
`endif*/
// Never retrieve WR_DATA_ADDR early
localparam EARLY_WR_DATA_ADDR = "OFF";
//***************************************************************************
// Convert timing parameters from time to clock cycles
//***************************************************************************
localparam nCKE = cdiv(tCKE, tCK);
localparam nRP = cdiv(tRP, tCK);
localparam nRCD = cdiv(tRCD, tCK);
localparam nRAS = cdiv(tRAS, tCK);
localparam nFAW = cdiv(tFAW, tCK);
localparam nRFC = cdiv(tRFC, tCK);
// Convert tWR. As per specification, write recover for autoprecharge
// cycles doesn't support values of 9 and 11. Round up 9 to 10 and 11 to 12
localparam nWR_CK = cdiv(15000, tCK) ;
localparam nWR = (nWR_CK == 9) ? 10 : (nWR_CK == 11) ? 12 : nWR_CK;
// tRRD, tWTR at tRTP have a 4 cycle floor in DDR3 and 2 cycle floor in DDR2
localparam nRRD_CK = cdiv(tRRD, tCK);
localparam nRRD = (DRAM_TYPE == "DDR3") ? (nRRD_CK < 4) ? 4 : nRRD_CK
: (nRRD_CK < 2) ? 2 : nRRD_CK;
localparam nWTR_CK = cdiv(tWTR, tCK);
localparam nWTR = (DRAM_TYPE == "DDR3") ? (nWTR_CK < 4) ? 4 : nWTR_CK
: (nWTR_CK < 2) ? 2 : nWTR_CK;
localparam nRTP_CK = cdiv(tRTP, tCK);
localparam nRTP = (DRAM_TYPE == "DDR3") ? (nRTP_CK < 4) ? 4 : nRTP_CK
: (nRTP_CK < 2) ? 2 : nRTP_CK;
// Add a cycle to CL/CWL for the register in RDIMM devices
localparam CWL_M = (REG_CTRL == "ON") ? CWL + 1 : CWL;
localparam CL_M = (REG_CTRL == "ON") ? CL + 1 : CL;
// Tuneable delay between read and write data on the DQ bus
localparam DQRD2DQWR_DLY = 4;
// CKE minimum pulse width for self-refresh (SRE->SRX minimum time)
localparam nCKESR = nCKE + 1;
// Delay from SRE to command requiring locked DLL. Currently fixed at 512 for
// all devices per JEDEC spec.
localparam tXSDLL = 512;
//***************************************************************************
// Set up maintenance counter dividers
//***************************************************************************
// CK clock divisor to generate maintenance prescaler period (round down)
localparam MAINT_PRESCALER_DIV = MAINT_PRESCALER_PERIOD / (tCK*nCK_PER_CLK);
// Maintenance prescaler divisor for refresh timer. Essentially, this is
// just (tREFI / MAINT_PRESCALER_PERIOD), but we must account for the worst
// case delay from the time we get a tick from the refresh counter to the
// time that we can actually issue the REF command. Thus, subtract tRCD, CL,
// data burst time and tRP for each implemented bank machine to ensure that
// all transactions can complete before tREFI expires
localparam REFRESH_TIMER_DIV =
USER_REFRESH == "ON" ? 0 :
(tREFI-((tRCD+((CL+4)*tCK)+tRP)*nBANK_MACHS)) / MAINT_PRESCALER_PERIOD;
// Periodic read (RESERVED - not currently required or supported in 7 series)
// tPRDI should only be set to 0
// localparam tPRDI = 0; // Do NOT change.
localparam PERIODIC_RD_TIMER_DIV = tPRDI / MAINT_PRESCALER_PERIOD;
// Convert maintenance prescaler from ps to ns
localparam MAINT_PRESCALER_PERIOD_NS = MAINT_PRESCALER_PERIOD / 1000;
// Maintenance prescaler divisor for ZQ calibration (ZQCS) timer
localparam ZQ_TIMER_DIV = tZQI / MAINT_PRESCALER_PERIOD_NS;
// Bus width required to broadcast a single bit rank signal among all the
// bank machines - 1 bit per rank, per bank
localparam RANK_BM_BV_WIDTH = nBANK_MACHS * RANKS;
//***************************************************************************
// Define 2T, CWL-even mode to enable multi-fabric-cycle 2T commands
//***************************************************************************
localparam EVEN_CWL_2T_MODE =
((ADDR_CMD_MODE == "2T") && (!(CWL % 2))) ? "ON" : "OFF";
//***************************************************************************
// Reserved feature control.
//***************************************************************************
// Open page wait mode is reserved.
// nOP_WAIT is the number of states a bank machine will park itself
// on an otherwise inactive open page before closing the page. If
// nOP_WAIT == 0, open page wait mode is disabled. If nOP_WAIT == -1,
// the bank machine will remain parked until the pool of idle bank machines
// are less than LOW_IDLE_CNT. At which point parked bank machines
// are selected to exit until the number of idle bank machines exceeds the
// LOW_IDLE_CNT.
localparam nOP_WAIT = 0; // Open page mode
localparam LOW_IDLE_CNT = 0; // Low idle bank machine threshold
//***************************************************************************
// Internal wires
//***************************************************************************
wire [RANK_BM_BV_WIDTH-1:0] act_this_rank_r;
wire [ROW_WIDTH-1:0] col_a;
wire [BANK_WIDTH-1:0] col_ba;
wire [DATA_BUF_ADDR_WIDTH-1:0] col_data_buf_addr;
wire col_periodic_rd;
wire [RANK_WIDTH-1:0] col_ra;
wire col_rmw;
wire col_rd_wr;
wire [ROW_WIDTH-1:0] col_row;
wire col_size;
wire [DATA_BUF_ADDR_WIDTH-1:0] col_wr_data_buf_addr;
wire dq_busy_data;
wire ecc_status_valid;
wire [RANKS-1:0] inhbt_act_faw_r;
wire [RANKS-1:0] inhbt_rd;
wire [RANKS-1:0] inhbt_wr;
wire insert_maint_r1;
wire [RANK_WIDTH-1:0] maint_rank_r;
wire maint_req_r;
wire maint_wip_r;
wire maint_zq_r;
wire maint_sre_r;
wire maint_srx_r;
wire periodic_rd_ack_r;
wire periodic_rd_r;
wire [RANK_WIDTH-1:0] periodic_rd_rank_r;
wire [(RANKS*nBANK_MACHS)-1:0] rank_busy_r;
wire rd_rmw;
wire [RANK_BM_BV_WIDTH-1:0] rd_this_rank_r;
wire [nBANK_MACHS-1:0] sending_col;
wire [nBANK_MACHS-1:0] sending_row;
wire sent_col;
wire sent_col_r;
wire wr_ecc_buf;
wire [RANK_BM_BV_WIDTH-1:0] wr_this_rank_r;
// MC/PHY optional pipeline stage support
wire [nCK_PER_CLK-1:0] mc_ras_n_ns;
wire [nCK_PER_CLK-1:0] mc_cas_n_ns;
wire [nCK_PER_CLK-1:0] mc_we_n_ns;
wire [nCK_PER_CLK*ROW_WIDTH-1:0] mc_address_ns;
wire [nCK_PER_CLK*BANK_WIDTH-1:0] mc_bank_ns;
wire [CS_WIDTH*nCS_PER_RANK*nCK_PER_CLK-1:0] mc_cs_n_ns;
wire [1:0] mc_odt_ns;
wire [nCK_PER_CLK-1:0] mc_cke_ns;
wire [3:0] mc_aux_out0_ns;
wire [3:0] mc_aux_out1_ns;
wire [1:0] mc_rank_cnt_ns = col_ra;
wire [2:0] mc_cmd_ns;
wire [5:0] mc_data_offset_ns;
wire [5:0] mc_data_offset_1_ns;
wire [5:0] mc_data_offset_2_ns;
wire [1:0] mc_cas_slot_ns;
wire mc_wrdata_en_ns;
wire [DATA_BUF_ADDR_WIDTH-1:0] wr_data_addr_ns;
wire wr_data_en_ns;
wire [DATA_BUF_OFFSET_WIDTH-1:0] wr_data_offset_ns;
integer i;
// MC Read idle support
wire col_read_fifo_empty;
wire mc_read_idle_ns;
reg mc_read_idle_r;
// MC Maintenance in progress with bus idle indication
wire maint_ref_zq_wip;
wire mc_ref_zq_wip_ns;
reg mc_ref_zq_wip_r;
//***************************************************************************
// Function cdiv
// Description:
// This function performs ceiling division (divide and round-up)
// Inputs:
// num: integer to be divided
// div: divisor
// Outputs:
// cdiv: result of ceiling division (num/div, rounded up)
//***************************************************************************
function integer cdiv (input integer num, input integer div);
begin
// perform division, then add 1 if and only if remainder is non-zero
cdiv = (num/div) + (((num%div)>0) ? 1 : 0);
end
endfunction // cdiv
//***************************************************************************
// Optional pipeline register stage on MC/PHY interface
//***************************************************************************
generate
if (CMD_PIPE_PLUS1 == "ON") begin : cmd_pipe_plus // register interface
always @(posedge clk) begin
mc_address <= #TCQ mc_address_ns;
mc_bank <= #TCQ mc_bank_ns;
mc_cas_n <= #TCQ mc_cas_n_ns;
mc_cs_n <= #TCQ mc_cs_n_ns;
mc_odt <= #TCQ mc_odt_ns;
mc_cke <= #TCQ mc_cke_ns;
mc_aux_out0 <= #TCQ mc_aux_out0_ns;
mc_aux_out1 <= #TCQ mc_aux_out1_ns;
mc_cmd <= #TCQ mc_cmd_ns;
mc_ras_n <= #TCQ mc_ras_n_ns;
mc_we_n <= #TCQ mc_we_n_ns;
mc_data_offset <= #TCQ mc_data_offset_ns;
mc_data_offset_1 <= #TCQ mc_data_offset_1_ns;
mc_data_offset_2 <= #TCQ mc_data_offset_2_ns;
mc_cas_slot <= #TCQ mc_cas_slot_ns;
mc_wrdata_en <= #TCQ mc_wrdata_en_ns;
mc_rank_cnt <= #TCQ mc_rank_cnt_ns;
wr_data_addr <= #TCQ wr_data_addr_ns;
wr_data_en <= #TCQ wr_data_en_ns;
wr_data_offset <= #TCQ wr_data_offset_ns;
end // always @ (posedge clk)
end // block: cmd_pipe_plus
else begin : cmd_pipe_plus0 // don't register interface
always @( mc_address_ns or mc_aux_out0_ns or mc_aux_out1_ns or
mc_bank_ns or mc_cas_n_ns or mc_cmd_ns or mc_cs_n_ns or
mc_odt_ns or mc_cke_ns or mc_data_offset_ns or
mc_data_offset_1_ns or mc_data_offset_2_ns or mc_rank_cnt_ns or
mc_ras_n_ns or mc_we_n_ns or mc_wrdata_en_ns or
wr_data_addr_ns or wr_data_en_ns or wr_data_offset_ns or
mc_cas_slot_ns)
begin
mc_address = #TCQ mc_address_ns;
mc_bank = #TCQ mc_bank_ns;
mc_cas_n = #TCQ mc_cas_n_ns;
mc_cs_n = #TCQ mc_cs_n_ns;
mc_odt = #TCQ mc_odt_ns;
mc_cke = #TCQ mc_cke_ns;
mc_aux_out0 = #TCQ mc_aux_out0_ns;
mc_aux_out1 = #TCQ mc_aux_out1_ns;
mc_cmd = #TCQ mc_cmd_ns;
mc_ras_n = #TCQ mc_ras_n_ns;
mc_we_n = #TCQ mc_we_n_ns;
mc_data_offset = #TCQ mc_data_offset_ns;
mc_data_offset_1 = #TCQ mc_data_offset_1_ns;
mc_data_offset_2 = #TCQ mc_data_offset_2_ns;
mc_cas_slot = #TCQ mc_cas_slot_ns;
mc_wrdata_en = #TCQ mc_wrdata_en_ns;
mc_rank_cnt = #TCQ mc_rank_cnt_ns;
wr_data_addr = #TCQ wr_data_addr_ns;
wr_data_en = #TCQ wr_data_en_ns;
wr_data_offset = #TCQ wr_data_offset_ns;
end // always @ (...
end // block: cmd_pipe_plus0
endgenerate
//***************************************************************************
// Indicate when there are no pending reads so that input features can be
// powered down
//***************************************************************************
assign mc_read_idle_ns = col_read_fifo_empty & init_calib_complete;
always @(posedge clk) mc_read_idle_r <= #TCQ mc_read_idle_ns;
assign mc_read_idle = mc_read_idle_r;
//***************************************************************************
// Indicate when there is a refresh in progress and the bus is idle so that
// tap adjustments can be made
//***************************************************************************
assign mc_ref_zq_wip_ns = maint_ref_zq_wip && col_read_fifo_empty;
always @(posedge clk) mc_ref_zq_wip_r <= mc_ref_zq_wip_ns;
assign mc_ref_zq_wip = mc_ref_zq_wip_r;
//***************************************************************************
// Manage rank-level timing and maintanence
//***************************************************************************
mig_7series_v1_9_rank_mach #
(
// Parameters
.BURST_MODE (BURST_MODE),
.CL (CL),
.CWL (CWL),
.CS_WIDTH (CS_WIDTH),
.DQRD2DQWR_DLY (DQRD2DQWR_DLY),
.DRAM_TYPE (DRAM_TYPE),
.MAINT_PRESCALER_DIV (MAINT_PRESCALER_DIV),
.nBANK_MACHS (nBANK_MACHS),
.nCKESR (nCKESR),
.nCK_PER_CLK (nCK_PER_CLK),
.nFAW (nFAW),
.nREFRESH_BANK (nREFRESH_BANK),
.nRRD (nRRD),
.nWTR (nWTR),
.PERIODIC_RD_TIMER_DIV (PERIODIC_RD_TIMER_DIV),
.RANK_BM_BV_WIDTH (RANK_BM_BV_WIDTH),
.RANK_WIDTH (RANK_WIDTH),
.RANKS (RANKS),
.REFRESH_TIMER_DIV (REFRESH_TIMER_DIV),
.ZQ_TIMER_DIV (ZQ_TIMER_DIV)
)
rank_mach0
(
// Outputs
.inhbt_act_faw_r (inhbt_act_faw_r[RANKS-1:0]),
.inhbt_rd (inhbt_rd[RANKS-1:0]),
.inhbt_wr (inhbt_wr[RANKS-1:0]),
.maint_rank_r (maint_rank_r[RANK_WIDTH-1:0]),
.maint_req_r (maint_req_r),
.maint_zq_r (maint_zq_r),
.maint_sre_r (maint_sre_r),
.maint_srx_r (maint_srx_r),
.maint_ref_zq_wip (maint_ref_zq_wip),
.periodic_rd_r (periodic_rd_r),
.periodic_rd_rank_r (periodic_rd_rank_r[RANK_WIDTH-1:0]),
// Inputs
.act_this_rank_r (act_this_rank_r[RANK_BM_BV_WIDTH-1:0]),
.app_periodic_rd_req (app_periodic_rd_req),
.app_ref_req (app_ref_req),
.app_ref_ack (app_ref_ack),
.app_zq_req (app_zq_req),
.app_zq_ack (app_zq_ack),
.app_sr_req (app_sr_req),
.app_sr_active (app_sr_active),
.col_rd_wr (col_rd_wr),
.clk (clk),
.init_calib_complete (init_calib_complete),
.insert_maint_r1 (insert_maint_r1),
.maint_wip_r (maint_wip_r),
.periodic_rd_ack_r (periodic_rd_ack_r),
.rank_busy_r (rank_busy_r[(RANKS*nBANK_MACHS)-1:0]),
.rd_this_rank_r (rd_this_rank_r[RANK_BM_BV_WIDTH-1:0]),
.rst (rst),
.sending_col (sending_col[nBANK_MACHS-1:0]),
.sending_row (sending_row[nBANK_MACHS-1:0]),
.slot_0_present (slot_0_present[7:0]),
.slot_1_present (slot_1_present[7:0]),
.wr_this_rank_r (wr_this_rank_r[RANK_BM_BV_WIDTH-1:0])
);
//***************************************************************************
// Manage requests, reordering and bank timing
//***************************************************************************
mig_7series_v1_9_bank_mach #
(
// Parameters
.TCQ (TCQ),
.EVEN_CWL_2T_MODE (EVEN_CWL_2T_MODE),
.ADDR_CMD_MODE (ADDR_CMD_MODE),
.BANK_WIDTH (BANK_WIDTH),
.BM_CNT_WIDTH (BM_CNT_WIDTH),
.BURST_MODE (BURST_MODE),
.COL_WIDTH (COL_WIDTH),
.CS_WIDTH (CS_WIDTH),
.CL (CL_M),
.CWL (CWL_M),
.CKE_ODT_AUX (CKE_ODT_AUX),
.DATA_BUF_ADDR_WIDTH (DATA_BUF_ADDR_WIDTH),
.DRAM_TYPE (DRAM_TYPE),
.EARLY_WR_DATA_ADDR (EARLY_WR_DATA_ADDR),
.ECC (ECC),
.LOW_IDLE_CNT (LOW_IDLE_CNT),
.nBANK_MACHS (nBANK_MACHS),
.nCK_PER_CLK (nCK_PER_CLK),
.nCS_PER_RANK (nCS_PER_RANK),
.nOP_WAIT (nOP_WAIT),
.nRAS (nRAS),
.nRCD (nRCD),
.nRFC (nRFC),
.nRP (nRP),
.nRTP (nRTP),
.nSLOTS (nSLOTS),
.nWR (nWR),
.nXSDLL (tXSDLL),
.ORDERING (ORDERING),
.RANK_BM_BV_WIDTH (RANK_BM_BV_WIDTH),
.RANK_WIDTH (RANK_WIDTH),
.RANKS (RANKS),
.ROW_WIDTH (ROW_WIDTH),
.RTT_NOM (RTT_NOM),
.RTT_WR (RTT_WR),
.SLOT_0_CONFIG (SLOT_0_CONFIG),
.SLOT_1_CONFIG (SLOT_1_CONFIG),
.STARVE_LIMIT (STARVE_LIMIT),
.tZQCS (tZQCS)
)
bank_mach0
(
// Outputs
.accept (accept),
.accept_ns (accept_ns),
.act_this_rank_r (act_this_rank_r[RANK_BM_BV_WIDTH-1:0]),
.bank_mach_next (bank_mach_next[BM_CNT_WIDTH-1:0]),
.col_a (col_a[ROW_WIDTH-1:0]),
.col_ba (col_ba[BANK_WIDTH-1:0]),
.col_data_buf_addr (col_data_buf_addr[DATA_BUF_ADDR_WIDTH-1:0]),
.col_periodic_rd (col_periodic_rd),
.col_ra (col_ra[RANK_WIDTH-1:0]),
.col_rmw (col_rmw),
.col_rd_wr (col_rd_wr),
.col_row (col_row[ROW_WIDTH-1:0]),
.col_size (col_size),
.col_wr_data_buf_addr (col_wr_data_buf_addr[DATA_BUF_ADDR_WIDTH-1:0]),
.mc_bank (mc_bank_ns),
.mc_address (mc_address_ns),
.mc_ras_n (mc_ras_n_ns),
.mc_cas_n (mc_cas_n_ns),
.mc_we_n (mc_we_n_ns),
.mc_cs_n (mc_cs_n_ns),
.mc_odt (mc_odt_ns),
.mc_cke (mc_cke_ns),
.mc_aux_out0 (mc_aux_out0_ns),
.mc_aux_out1 (mc_aux_out1_ns),
.mc_cmd (mc_cmd_ns),
.mc_data_offset (mc_data_offset_ns),
.mc_data_offset_1 (mc_data_offset_1_ns),
.mc_data_offset_2 (mc_data_offset_2_ns),
.mc_cas_slot (mc_cas_slot_ns),
.insert_maint_r1 (insert_maint_r1),
.maint_wip_r (maint_wip_r),
.periodic_rd_ack_r (periodic_rd_ack_r),
.rank_busy_r (rank_busy_r[(RANKS*nBANK_MACHS)-1:0]),
.rd_this_rank_r (rd_this_rank_r[RANK_BM_BV_WIDTH-1:0]),
.sending_row (sending_row[nBANK_MACHS-1:0]),
.sending_col (sending_col[nBANK_MACHS-1:0]),
.sent_col (sent_col),
.sent_col_r (sent_col_r),
.wr_this_rank_r (wr_this_rank_r[RANK_BM_BV_WIDTH-1:0]),
// Inputs
.bank (bank[BANK_WIDTH-1:0]),
.calib_rddata_offset (calib_rd_data_offset),
.calib_rddata_offset_1 (calib_rd_data_offset_1),
.calib_rddata_offset_2 (calib_rd_data_offset_2),
.clk (clk),
.cmd (cmd[2:0]),
.col (col[COL_WIDTH-1:0]),
.data_buf_addr (data_buf_addr[DATA_BUF_ADDR_WIDTH-1:0]),
.init_calib_complete (init_calib_complete),
.phy_rddata_valid (phy_rddata_valid),
.dq_busy_data (dq_busy_data),
.hi_priority (hi_priority),
.inhbt_act_faw_r (inhbt_act_faw_r[RANKS-1:0]),
.inhbt_rd (inhbt_rd[RANKS-1:0]),
.inhbt_wr (inhbt_wr[RANKS-1:0]),
.maint_rank_r (maint_rank_r[RANK_WIDTH-1:0]),
.maint_req_r (maint_req_r),
.maint_zq_r (maint_zq_r),
.maint_sre_r (maint_sre_r),
.maint_srx_r (maint_srx_r),
.periodic_rd_r (periodic_rd_r),
.periodic_rd_rank_r (periodic_rd_rank_r[RANK_WIDTH-1:0]),
.phy_mc_cmd_full (phy_mc_cmd_full),
.phy_mc_ctl_full (phy_mc_ctl_full),
.phy_mc_data_full (phy_mc_data_full),
.rank (rank[RANK_WIDTH-1:0]),
.rd_data_addr (rd_data_addr[DATA_BUF_ADDR_WIDTH-1:0]),
.rd_rmw (rd_rmw),
.row (row[ROW_WIDTH-1:0]),
.rst (rst),
.size (size),
.slot_0_present (slot_0_present[7:0]),
.slot_1_present (slot_1_present[7:0]),
.use_addr (use_addr)
);
//***************************************************************************
// Manage DQ bus
//***************************************************************************
mig_7series_v1_9_col_mach #
(
// Parameters
.TCQ (TCQ),
.BANK_WIDTH (BANK_WIDTH),
.BURST_MODE (BURST_MODE),
.COL_WIDTH (COL_WIDTH),
.CS_WIDTH (CS_WIDTH),
.DATA_BUF_ADDR_WIDTH (DATA_BUF_ADDR_WIDTH),
.DATA_BUF_OFFSET_WIDTH (DATA_BUF_OFFSET_WIDTH),
.DELAY_WR_DATA_CNTRL (DELAY_WR_DATA_CNTRL),
.DQS_WIDTH (DQS_WIDTH),
.DRAM_TYPE (DRAM_TYPE),
.EARLY_WR_DATA_ADDR (EARLY_WR_DATA_ADDR),
.ECC (ECC),
.MC_ERR_ADDR_WIDTH (MC_ERR_ADDR_WIDTH),
.nCK_PER_CLK (nCK_PER_CLK),
.nPHY_WRLAT (nPHY_WRLAT),
.RANK_WIDTH (RANK_WIDTH),
.ROW_WIDTH (ROW_WIDTH)
)
col_mach0
(
// Outputs
.mc_wrdata_en (mc_wrdata_en_ns),
.dq_busy_data (dq_busy_data),
.ecc_err_addr (ecc_err_addr[MC_ERR_ADDR_WIDTH-1:0]),
.ecc_status_valid (ecc_status_valid),
.rd_data_addr (rd_data_addr[DATA_BUF_ADDR_WIDTH-1:0]),
.rd_data_en (rd_data_en),
.rd_data_end (rd_data_end),
.rd_data_offset (rd_data_offset),
.rd_rmw (rd_rmw),
.wr_data_addr (wr_data_addr_ns),
.wr_data_en (wr_data_en_ns),
.wr_data_offset (wr_data_offset_ns),
.wr_ecc_buf (wr_ecc_buf),
.col_read_fifo_empty (col_read_fifo_empty),
// Inputs
.clk (clk),
.rst (rst),
.col_a (col_a[ROW_WIDTH-1:0]),
.col_ba (col_ba[BANK_WIDTH-1:0]),
.col_data_buf_addr (col_data_buf_addr[DATA_BUF_ADDR_WIDTH-1:0]),
.col_periodic_rd (col_periodic_rd),
.col_ra (col_ra[RANK_WIDTH-1:0]),
.col_rmw (col_rmw),
.col_rd_wr (col_rd_wr),
.col_row (col_row[ROW_WIDTH-1:0]),
.col_size (col_size),
.col_wr_data_buf_addr (col_wr_data_buf_addr[DATA_BUF_ADDR_WIDTH-1:0]),
.phy_rddata_valid (phy_rddata_valid),
.sent_col (EVEN_CWL_2T_MODE == "ON" ? sent_col_r : sent_col)
);
//***************************************************************************
// Implement ECC
//***************************************************************************
// Total ECC word length = ECC code width + Data width
localparam CODE_WIDTH = DATA_WIDTH + ECC_WIDTH;
generate
if (ECC == "OFF") begin : ecc_off
assign rd_data = phy_rd_data;
assign mc_wrdata = wr_data;
assign mc_wrdata_mask = wr_data_mask;
assign ecc_single = 4'b0;
assign ecc_multiple = 4'b0;
end
else begin : ecc_on
wire [CODE_WIDTH*ECC_WIDTH-1:0] h_rows;
wire [2*nCK_PER_CLK*DATA_WIDTH-1:0] rd_merge_data;
// Merge and encode
mig_7series_v1_9_ecc_merge_enc #
(
// Parameters
.TCQ (TCQ),
.CODE_WIDTH (CODE_WIDTH),
.DATA_BUF_ADDR_WIDTH (DATA_BUF_ADDR_WIDTH),
.DATA_WIDTH (DATA_WIDTH),
.DQ_WIDTH (DQ_WIDTH),
.ECC_WIDTH (ECC_WIDTH),
.PAYLOAD_WIDTH (PAYLOAD_WIDTH),
.nCK_PER_CLK (nCK_PER_CLK)
)
ecc_merge_enc0
(
// Outputs
.mc_wrdata (mc_wrdata),
.mc_wrdata_mask (mc_wrdata_mask),
// Inputs
.clk (clk),
.rst (rst),
.h_rows (h_rows),
.rd_merge_data (rd_merge_data),
.raw_not_ecc (raw_not_ecc),
.wr_data (wr_data),
.wr_data_mask (wr_data_mask)
);
// Decode and fix
mig_7series_v1_9_ecc_dec_fix #
(
// Parameters
.TCQ (TCQ),
.CODE_WIDTH (CODE_WIDTH),
.DATA_WIDTH (DATA_WIDTH),
.DQ_WIDTH (DQ_WIDTH),
.ECC_WIDTH (ECC_WIDTH),
.PAYLOAD_WIDTH (PAYLOAD_WIDTH),
.nCK_PER_CLK (nCK_PER_CLK)
)
ecc_dec_fix0
(
// Outputs
.ecc_multiple (ecc_multiple),
.ecc_single (ecc_single),
.rd_data (rd_data),
// Inputs
.clk (clk),
.rst (rst),
.correct_en (correct_en),
.phy_rddata (phy_rd_data),
.ecc_status_valid (ecc_status_valid),
.h_rows (h_rows)
);
// ECC Buffer
mig_7series_v1_9_ecc_buf #
(
// Parameters
.TCQ (TCQ),
.DATA_BUF_ADDR_WIDTH (DATA_BUF_ADDR_WIDTH),
.DATA_BUF_OFFSET_WIDTH (DATA_BUF_OFFSET_WIDTH),
.DATA_WIDTH (DATA_WIDTH),
.PAYLOAD_WIDTH (PAYLOAD_WIDTH),
.nCK_PER_CLK (nCK_PER_CLK)
)
ecc_buf0
(
// Outputs
.rd_merge_data (rd_merge_data),
// Inputs
.clk (clk),
.rst (rst),
.rd_data (rd_data),
.rd_data_addr (rd_data_addr),
.rd_data_offset (rd_data_offset),
.wr_data_addr (wr_data_addr),
.wr_data_offset (wr_data_offset),
.wr_ecc_buf (wr_ecc_buf)
);
// Generate ECC table
mig_7series_v1_9_ecc_gen #
(
// Parameters
.CODE_WIDTH (CODE_WIDTH),
.DATA_WIDTH (DATA_WIDTH),
.ECC_WIDTH (ECC_WIDTH)
)
ecc_gen0
(
// Outputs
.h_rows (h_rows)
);
`ifdef DISPLAY_H_MATRIX
integer i;
always @(negedge rst) begin
$display ("**********************************************");
$display ("H Matrix:");
for (i=0; i<ECC_WIDTH; i=i+1)
$display ("%b", h_rows[i*CODE_WIDTH+:CODE_WIDTH]);
$display ("**********************************************");
end
`endif
end
endgenerate
endmodule // mc
|
//*****************************************************************************
// (c) Copyright 2008 - 2013 Xilinx, Inc. All rights reserved.
//
// This file contains confidential and proprietary information
// of Xilinx, Inc. and is protected under U.S. and
// international copyright and other intellectual property
// laws.
//
// DISCLAIMER
// This disclaimer is not a license and does not grant any
// rights to the materials distributed herewith. Except as
// otherwise provided in a valid license issued to you by
// Xilinx, and to the maximum extent permitted by applicable
// law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND
// WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES
// AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
// BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-
// INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and
// (2) Xilinx shall not be liable (whether in contract or tort,
// including negligence, or under any other theory of
// liability) for any loss or damage of any kind or nature
// related to, arising under or in connection with these
// materials, including for any direct, or any indirect,
// special, incidental, or consequential loss or damage
// (including loss of data, profits, goodwill, or any type of
// loss or damage suffered as a result of any action brought
// by a third party) even if such damage or loss was
// reasonably foreseeable or Xilinx had been advised of the
// possibility of the same.
//
// CRITICAL APPLICATIONS
// Xilinx products are not designed or intended to be fail-
// safe, or for use in any application requiring fail-safe
// performance, such as life-support or safety devices or
// systems, Class III medical devices, nuclear facilities,
// applications related to the deployment of airbags, or any
// other applications that could lead to death, personal
// injury, or severe property or environmental damage
// (individually and collectively, "Critical
// Applications"). Customer assumes the sole risk and
// liability of any use of Xilinx products in Critical
// Applications, subject only to applicable laws and
// regulations governing limitations on product liability.
//
// THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS
// PART OF THIS FILE AT ALL TIMES.
//
//*****************************************************************************
// ____ ____
// / /\/ /
// /___/ \ / Vendor : Xilinx
// \ \ \/ Version : %version
// \ \ Application : MIG
// / / Filename : mc.v
// /___/ /\ Date Last Modified : $date$
// \ \ / \ Date Created : Tue Jun 30 2009
// \___\/\___\
//
//Device : 7-Series
//Design Name : DDR3 SDRAM
//Purpose :
//Reference :
//Revision History :
//*****************************************************************************
//*****************************************************************************
// Top level memory sequencer structural block. This block
// instantiates the rank, bank, and column machines.
//*****************************************************************************
`timescale 1ps/1ps
module mig_7series_v1_9_mc #
(
parameter TCQ = 100, // clk->out delay(sim only)
parameter ADDR_CMD_MODE = "1T", // registered or
// 1Tfered mem?
parameter BANK_WIDTH = 3, // bank address width
parameter BM_CNT_WIDTH = 2, // # BM counter width
// i.e., log2(nBANK_MACHS)
parameter BURST_MODE = "8", // Burst length
parameter CL = 5, // Read CAS latency
// (in clk cyc)
parameter CMD_PIPE_PLUS1 = "ON", // add register stage
// between MC and PHY
parameter COL_WIDTH = 12, // column address width
parameter CS_WIDTH = 4, // # of unique CS outputs
parameter CWL = 5, // Write CAS latency
// (in clk cyc)
parameter DATA_BUF_ADDR_WIDTH = 8, // User request tag (e.g.
// user src/dest buf addr)
parameter DATA_BUF_OFFSET_WIDTH = 1, // User buffer offset width
parameter DATA_WIDTH = 64, // Data bus width
parameter DQ_WIDTH = 64, // # of DQ (data)
parameter DQS_WIDTH = 8, // # of DQS (strobe)
parameter DRAM_TYPE = "DDR3", // Memory I/F type:
// "DDR3", "DDR2"
parameter ECC = "OFF", // ECC ON/OFF?
parameter ECC_WIDTH = 8, // # of ECC bits
parameter MAINT_PRESCALER_PERIOD= 200000, // maintenance period (ps)
parameter MC_ERR_ADDR_WIDTH = 31, // # of error address bits
parameter nBANK_MACHS = 4, // # of bank machines (BM)
parameter nCK_PER_CLK = 4, // DRAM clock : MC clock
// frequency ratio
parameter nCS_PER_RANK = 1, // # of unique CS outputs
// per rank
parameter nREFRESH_BANK = 1, // # of REF cmds to pull-in
parameter nSLOTS = 1, // # DIMM slots in system
parameter ORDERING = "NORM", // request ordering mode
parameter PAYLOAD_WIDTH = 64, // Width of data payload
// from PHY
parameter RANK_WIDTH = 2, // # of bits to count ranks
parameter RANKS = 4, // # of ranks of DRAM
parameter REG_CTRL = "ON", // "ON" for registered DIMM
parameter ROW_WIDTH = 16, // row address width
parameter RTT_NOM = "40", // Nominal ODT value
parameter RTT_WR = "120", // Write ODT value
parameter SLOT_0_CONFIG = 8'b0000_0101, // ranks allowed in slot 0
parameter SLOT_1_CONFIG = 8'b0000_1010, // ranks allowed in slot 1
parameter STARVE_LIMIT = 2, // max # of times a user
// request is allowed to
// lose arbitration when
// reordering is enabled
parameter tCK = 2500, // memory clk period(ps)
parameter tCKE = 10000, // CKE minimum pulse (ps)
parameter tFAW = 40000, // four activate window(ps)
parameter tRAS = 37500, // ACT->PRE cmd period (ps)
parameter tRCD = 12500, // ACT->R/W delay (ps)
parameter tREFI = 7800000, // average periodic
// refresh interval(ps)
parameter CKE_ODT_AUX = "FALSE", //Parameter to turn on/off the aux_out signal
parameter tRFC = 110000, // REF->ACT/REF delay (ps)
parameter tRP = 12500, // PRE cmd period (ps)
parameter tRRD = 10000, // ACT->ACT period (ps)
parameter tRTP = 7500, // Read->PRE cmd delay (ps)
parameter tWTR = 7500, // Internal write->read
// delay (ps)
// requiring DLL lock (CKs)
parameter tZQCS = 64, // ZQCS cmd period (CKs)
parameter tZQI = 128_000_000, // ZQCS interval (ps)
parameter tPRDI = 1_000_000, // pS
parameter USER_REFRESH = "OFF" // Whether user manages REF
)
(
// System inputs
input clk,
input rst,
// Physical memory slot presence
input [7:0] slot_0_present,
input [7:0] slot_1_present,
// Native Interface
input [2:0] cmd,
input [DATA_BUF_ADDR_WIDTH-1:0] data_buf_addr,
input hi_priority,
input size,
input [BANK_WIDTH-1:0] bank,
input [COL_WIDTH-1:0] col,
input [RANK_WIDTH-1:0] rank,
input [ROW_WIDTH-1:0] row,
input use_addr,
input [2*nCK_PER_CLK*PAYLOAD_WIDTH-1:0] wr_data,
input [2*nCK_PER_CLK*DATA_WIDTH/8-1:0] wr_data_mask,
output accept,
output accept_ns,
output [BM_CNT_WIDTH-1:0] bank_mach_next,
output wire [2*nCK_PER_CLK*PAYLOAD_WIDTH-1:0] rd_data,
output [DATA_BUF_ADDR_WIDTH-1:0] rd_data_addr,
output rd_data_en,
output rd_data_end,
output [DATA_BUF_OFFSET_WIDTH-1:0] rd_data_offset,
(* keep = "true", max_fanout = 30 *) output reg [DATA_BUF_ADDR_WIDTH-1:0] wr_data_addr /* synthesis syn_maxfan = 30 */,
output reg wr_data_en,
(* keep = "true", max_fanout = 30 *) output reg [DATA_BUF_OFFSET_WIDTH-1:0] wr_data_offset /* synthesis syn_maxfan = 30 */,
output mc_read_idle,
output mc_ref_zq_wip,
// ECC interface
input correct_en,
input [2*nCK_PER_CLK-1:0] raw_not_ecc,
output [MC_ERR_ADDR_WIDTH-1:0] ecc_err_addr,
output [2*nCK_PER_CLK-1:0] ecc_single,
output [2*nCK_PER_CLK-1:0] ecc_multiple,
// User maintenance requests
input app_periodic_rd_req,
input app_ref_req,
input app_zq_req,
input app_sr_req,
output app_sr_active,
output app_ref_ack,
output app_zq_ack,
// MC <==> PHY Interface
output reg [nCK_PER_CLK-1:0] mc_ras_n,
output reg [nCK_PER_CLK-1:0] mc_cas_n,
output reg [nCK_PER_CLK-1:0] mc_we_n,
output reg [nCK_PER_CLK*ROW_WIDTH-1:0] mc_address,
output reg [nCK_PER_CLK*BANK_WIDTH-1:0] mc_bank,
output reg [CS_WIDTH*nCS_PER_RANK*nCK_PER_CLK-1:0] mc_cs_n,
output reg [1:0] mc_odt,
output reg [nCK_PER_CLK-1:0] mc_cke,
output wire mc_reset_n,
output wire [2*nCK_PER_CLK*DQ_WIDTH-1:0] mc_wrdata,
output wire [2*nCK_PER_CLK*DQ_WIDTH/8-1:0]mc_wrdata_mask,
output reg mc_wrdata_en,
output wire mc_cmd_wren,
output wire mc_ctl_wren,
output reg [2:0] mc_cmd,
output reg [5:0] mc_data_offset,
output reg [5:0] mc_data_offset_1,
output reg [5:0] mc_data_offset_2,
output reg [1:0] mc_cas_slot,
output reg [3:0] mc_aux_out0,
output reg [3:0] mc_aux_out1,
output reg [1:0] mc_rank_cnt,
input phy_mc_ctl_full,
input phy_mc_cmd_full,
input phy_mc_data_full,
input [2*nCK_PER_CLK*DQ_WIDTH-1:0] phy_rd_data,
input phy_rddata_valid,
input init_calib_complete,
input [6*RANKS-1:0] calib_rd_data_offset,
input [6*RANKS-1:0] calib_rd_data_offset_1,
input [6*RANKS-1:0] calib_rd_data_offset_2
);
assign mc_reset_n = 1'b1; // never reset memory
assign mc_cmd_wren = 1'b1; // always write CMD FIFO(issue DSEL when idle)
assign mc_ctl_wren = 1'b1; // always write CTL FIFO(issue nondata when idle)
// Ensure there is always at least one rank present during operation
`ifdef MC_SVA
ranks_present: assert property
(@(posedge clk) (rst || (|(slot_0_present | slot_1_present))));
`endif
// Reserved. Do not change.
localparam nPHY_WRLAT = 2;
// always delay write data control unless ECC mode is enabled
localparam DELAY_WR_DATA_CNTRL = ECC == "ON" ? 0 : 1;
// Ensure that write control is delayed for appropriate CWL
/*`ifdef MC_SVA
delay_wr_data_zero_CWL_le_6: assert property
(@(posedge clk) ((CWL > 6) || (DELAY_WR_DATA_CNTRL == 0)));
`endif*/
// Never retrieve WR_DATA_ADDR early
localparam EARLY_WR_DATA_ADDR = "OFF";
//***************************************************************************
// Convert timing parameters from time to clock cycles
//***************************************************************************
localparam nCKE = cdiv(tCKE, tCK);
localparam nRP = cdiv(tRP, tCK);
localparam nRCD = cdiv(tRCD, tCK);
localparam nRAS = cdiv(tRAS, tCK);
localparam nFAW = cdiv(tFAW, tCK);
localparam nRFC = cdiv(tRFC, tCK);
// Convert tWR. As per specification, write recover for autoprecharge
// cycles doesn't support values of 9 and 11. Round up 9 to 10 and 11 to 12
localparam nWR_CK = cdiv(15000, tCK) ;
localparam nWR = (nWR_CK == 9) ? 10 : (nWR_CK == 11) ? 12 : nWR_CK;
// tRRD, tWTR at tRTP have a 4 cycle floor in DDR3 and 2 cycle floor in DDR2
localparam nRRD_CK = cdiv(tRRD, tCK);
localparam nRRD = (DRAM_TYPE == "DDR3") ? (nRRD_CK < 4) ? 4 : nRRD_CK
: (nRRD_CK < 2) ? 2 : nRRD_CK;
localparam nWTR_CK = cdiv(tWTR, tCK);
localparam nWTR = (DRAM_TYPE == "DDR3") ? (nWTR_CK < 4) ? 4 : nWTR_CK
: (nWTR_CK < 2) ? 2 : nWTR_CK;
localparam nRTP_CK = cdiv(tRTP, tCK);
localparam nRTP = (DRAM_TYPE == "DDR3") ? (nRTP_CK < 4) ? 4 : nRTP_CK
: (nRTP_CK < 2) ? 2 : nRTP_CK;
// Add a cycle to CL/CWL for the register in RDIMM devices
localparam CWL_M = (REG_CTRL == "ON") ? CWL + 1 : CWL;
localparam CL_M = (REG_CTRL == "ON") ? CL + 1 : CL;
// Tuneable delay between read and write data on the DQ bus
localparam DQRD2DQWR_DLY = 4;
// CKE minimum pulse width for self-refresh (SRE->SRX minimum time)
localparam nCKESR = nCKE + 1;
// Delay from SRE to command requiring locked DLL. Currently fixed at 512 for
// all devices per JEDEC spec.
localparam tXSDLL = 512;
//***************************************************************************
// Set up maintenance counter dividers
//***************************************************************************
// CK clock divisor to generate maintenance prescaler period (round down)
localparam MAINT_PRESCALER_DIV = MAINT_PRESCALER_PERIOD / (tCK*nCK_PER_CLK);
// Maintenance prescaler divisor for refresh timer. Essentially, this is
// just (tREFI / MAINT_PRESCALER_PERIOD), but we must account for the worst
// case delay from the time we get a tick from the refresh counter to the
// time that we can actually issue the REF command. Thus, subtract tRCD, CL,
// data burst time and tRP for each implemented bank machine to ensure that
// all transactions can complete before tREFI expires
localparam REFRESH_TIMER_DIV =
USER_REFRESH == "ON" ? 0 :
(tREFI-((tRCD+((CL+4)*tCK)+tRP)*nBANK_MACHS)) / MAINT_PRESCALER_PERIOD;
// Periodic read (RESERVED - not currently required or supported in 7 series)
// tPRDI should only be set to 0
// localparam tPRDI = 0; // Do NOT change.
localparam PERIODIC_RD_TIMER_DIV = tPRDI / MAINT_PRESCALER_PERIOD;
// Convert maintenance prescaler from ps to ns
localparam MAINT_PRESCALER_PERIOD_NS = MAINT_PRESCALER_PERIOD / 1000;
// Maintenance prescaler divisor for ZQ calibration (ZQCS) timer
localparam ZQ_TIMER_DIV = tZQI / MAINT_PRESCALER_PERIOD_NS;
// Bus width required to broadcast a single bit rank signal among all the
// bank machines - 1 bit per rank, per bank
localparam RANK_BM_BV_WIDTH = nBANK_MACHS * RANKS;
//***************************************************************************
// Define 2T, CWL-even mode to enable multi-fabric-cycle 2T commands
//***************************************************************************
localparam EVEN_CWL_2T_MODE =
((ADDR_CMD_MODE == "2T") && (!(CWL % 2))) ? "ON" : "OFF";
//***************************************************************************
// Reserved feature control.
//***************************************************************************
// Open page wait mode is reserved.
// nOP_WAIT is the number of states a bank machine will park itself
// on an otherwise inactive open page before closing the page. If
// nOP_WAIT == 0, open page wait mode is disabled. If nOP_WAIT == -1,
// the bank machine will remain parked until the pool of idle bank machines
// are less than LOW_IDLE_CNT. At which point parked bank machines
// are selected to exit until the number of idle bank machines exceeds the
// LOW_IDLE_CNT.
localparam nOP_WAIT = 0; // Open page mode
localparam LOW_IDLE_CNT = 0; // Low idle bank machine threshold
//***************************************************************************
// Internal wires
//***************************************************************************
wire [RANK_BM_BV_WIDTH-1:0] act_this_rank_r;
wire [ROW_WIDTH-1:0] col_a;
wire [BANK_WIDTH-1:0] col_ba;
wire [DATA_BUF_ADDR_WIDTH-1:0] col_data_buf_addr;
wire col_periodic_rd;
wire [RANK_WIDTH-1:0] col_ra;
wire col_rmw;
wire col_rd_wr;
wire [ROW_WIDTH-1:0] col_row;
wire col_size;
wire [DATA_BUF_ADDR_WIDTH-1:0] col_wr_data_buf_addr;
wire dq_busy_data;
wire ecc_status_valid;
wire [RANKS-1:0] inhbt_act_faw_r;
wire [RANKS-1:0] inhbt_rd;
wire [RANKS-1:0] inhbt_wr;
wire insert_maint_r1;
wire [RANK_WIDTH-1:0] maint_rank_r;
wire maint_req_r;
wire maint_wip_r;
wire maint_zq_r;
wire maint_sre_r;
wire maint_srx_r;
wire periodic_rd_ack_r;
wire periodic_rd_r;
wire [RANK_WIDTH-1:0] periodic_rd_rank_r;
wire [(RANKS*nBANK_MACHS)-1:0] rank_busy_r;
wire rd_rmw;
wire [RANK_BM_BV_WIDTH-1:0] rd_this_rank_r;
wire [nBANK_MACHS-1:0] sending_col;
wire [nBANK_MACHS-1:0] sending_row;
wire sent_col;
wire sent_col_r;
wire wr_ecc_buf;
wire [RANK_BM_BV_WIDTH-1:0] wr_this_rank_r;
// MC/PHY optional pipeline stage support
wire [nCK_PER_CLK-1:0] mc_ras_n_ns;
wire [nCK_PER_CLK-1:0] mc_cas_n_ns;
wire [nCK_PER_CLK-1:0] mc_we_n_ns;
wire [nCK_PER_CLK*ROW_WIDTH-1:0] mc_address_ns;
wire [nCK_PER_CLK*BANK_WIDTH-1:0] mc_bank_ns;
wire [CS_WIDTH*nCS_PER_RANK*nCK_PER_CLK-1:0] mc_cs_n_ns;
wire [1:0] mc_odt_ns;
wire [nCK_PER_CLK-1:0] mc_cke_ns;
wire [3:0] mc_aux_out0_ns;
wire [3:0] mc_aux_out1_ns;
wire [1:0] mc_rank_cnt_ns = col_ra;
wire [2:0] mc_cmd_ns;
wire [5:0] mc_data_offset_ns;
wire [5:0] mc_data_offset_1_ns;
wire [5:0] mc_data_offset_2_ns;
wire [1:0] mc_cas_slot_ns;
wire mc_wrdata_en_ns;
wire [DATA_BUF_ADDR_WIDTH-1:0] wr_data_addr_ns;
wire wr_data_en_ns;
wire [DATA_BUF_OFFSET_WIDTH-1:0] wr_data_offset_ns;
integer i;
// MC Read idle support
wire col_read_fifo_empty;
wire mc_read_idle_ns;
reg mc_read_idle_r;
// MC Maintenance in progress with bus idle indication
wire maint_ref_zq_wip;
wire mc_ref_zq_wip_ns;
reg mc_ref_zq_wip_r;
//***************************************************************************
// Function cdiv
// Description:
// This function performs ceiling division (divide and round-up)
// Inputs:
// num: integer to be divided
// div: divisor
// Outputs:
// cdiv: result of ceiling division (num/div, rounded up)
//***************************************************************************
function integer cdiv (input integer num, input integer div);
begin
// perform division, then add 1 if and only if remainder is non-zero
cdiv = (num/div) + (((num%div)>0) ? 1 : 0);
end
endfunction // cdiv
//***************************************************************************
// Optional pipeline register stage on MC/PHY interface
//***************************************************************************
generate
if (CMD_PIPE_PLUS1 == "ON") begin : cmd_pipe_plus // register interface
always @(posedge clk) begin
mc_address <= #TCQ mc_address_ns;
mc_bank <= #TCQ mc_bank_ns;
mc_cas_n <= #TCQ mc_cas_n_ns;
mc_cs_n <= #TCQ mc_cs_n_ns;
mc_odt <= #TCQ mc_odt_ns;
mc_cke <= #TCQ mc_cke_ns;
mc_aux_out0 <= #TCQ mc_aux_out0_ns;
mc_aux_out1 <= #TCQ mc_aux_out1_ns;
mc_cmd <= #TCQ mc_cmd_ns;
mc_ras_n <= #TCQ mc_ras_n_ns;
mc_we_n <= #TCQ mc_we_n_ns;
mc_data_offset <= #TCQ mc_data_offset_ns;
mc_data_offset_1 <= #TCQ mc_data_offset_1_ns;
mc_data_offset_2 <= #TCQ mc_data_offset_2_ns;
mc_cas_slot <= #TCQ mc_cas_slot_ns;
mc_wrdata_en <= #TCQ mc_wrdata_en_ns;
mc_rank_cnt <= #TCQ mc_rank_cnt_ns;
wr_data_addr <= #TCQ wr_data_addr_ns;
wr_data_en <= #TCQ wr_data_en_ns;
wr_data_offset <= #TCQ wr_data_offset_ns;
end // always @ (posedge clk)
end // block: cmd_pipe_plus
else begin : cmd_pipe_plus0 // don't register interface
always @( mc_address_ns or mc_aux_out0_ns or mc_aux_out1_ns or
mc_bank_ns or mc_cas_n_ns or mc_cmd_ns or mc_cs_n_ns or
mc_odt_ns or mc_cke_ns or mc_data_offset_ns or
mc_data_offset_1_ns or mc_data_offset_2_ns or mc_rank_cnt_ns or
mc_ras_n_ns or mc_we_n_ns or mc_wrdata_en_ns or
wr_data_addr_ns or wr_data_en_ns or wr_data_offset_ns or
mc_cas_slot_ns)
begin
mc_address = #TCQ mc_address_ns;
mc_bank = #TCQ mc_bank_ns;
mc_cas_n = #TCQ mc_cas_n_ns;
mc_cs_n = #TCQ mc_cs_n_ns;
mc_odt = #TCQ mc_odt_ns;
mc_cke = #TCQ mc_cke_ns;
mc_aux_out0 = #TCQ mc_aux_out0_ns;
mc_aux_out1 = #TCQ mc_aux_out1_ns;
mc_cmd = #TCQ mc_cmd_ns;
mc_ras_n = #TCQ mc_ras_n_ns;
mc_we_n = #TCQ mc_we_n_ns;
mc_data_offset = #TCQ mc_data_offset_ns;
mc_data_offset_1 = #TCQ mc_data_offset_1_ns;
mc_data_offset_2 = #TCQ mc_data_offset_2_ns;
mc_cas_slot = #TCQ mc_cas_slot_ns;
mc_wrdata_en = #TCQ mc_wrdata_en_ns;
mc_rank_cnt = #TCQ mc_rank_cnt_ns;
wr_data_addr = #TCQ wr_data_addr_ns;
wr_data_en = #TCQ wr_data_en_ns;
wr_data_offset = #TCQ wr_data_offset_ns;
end // always @ (...
end // block: cmd_pipe_plus0
endgenerate
//***************************************************************************
// Indicate when there are no pending reads so that input features can be
// powered down
//***************************************************************************
assign mc_read_idle_ns = col_read_fifo_empty & init_calib_complete;
always @(posedge clk) mc_read_idle_r <= #TCQ mc_read_idle_ns;
assign mc_read_idle = mc_read_idle_r;
//***************************************************************************
// Indicate when there is a refresh in progress and the bus is idle so that
// tap adjustments can be made
//***************************************************************************
assign mc_ref_zq_wip_ns = maint_ref_zq_wip && col_read_fifo_empty;
always @(posedge clk) mc_ref_zq_wip_r <= mc_ref_zq_wip_ns;
assign mc_ref_zq_wip = mc_ref_zq_wip_r;
//***************************************************************************
// Manage rank-level timing and maintanence
//***************************************************************************
mig_7series_v1_9_rank_mach #
(
// Parameters
.BURST_MODE (BURST_MODE),
.CL (CL),
.CWL (CWL),
.CS_WIDTH (CS_WIDTH),
.DQRD2DQWR_DLY (DQRD2DQWR_DLY),
.DRAM_TYPE (DRAM_TYPE),
.MAINT_PRESCALER_DIV (MAINT_PRESCALER_DIV),
.nBANK_MACHS (nBANK_MACHS),
.nCKESR (nCKESR),
.nCK_PER_CLK (nCK_PER_CLK),
.nFAW (nFAW),
.nREFRESH_BANK (nREFRESH_BANK),
.nRRD (nRRD),
.nWTR (nWTR),
.PERIODIC_RD_TIMER_DIV (PERIODIC_RD_TIMER_DIV),
.RANK_BM_BV_WIDTH (RANK_BM_BV_WIDTH),
.RANK_WIDTH (RANK_WIDTH),
.RANKS (RANKS),
.REFRESH_TIMER_DIV (REFRESH_TIMER_DIV),
.ZQ_TIMER_DIV (ZQ_TIMER_DIV)
)
rank_mach0
(
// Outputs
.inhbt_act_faw_r (inhbt_act_faw_r[RANKS-1:0]),
.inhbt_rd (inhbt_rd[RANKS-1:0]),
.inhbt_wr (inhbt_wr[RANKS-1:0]),
.maint_rank_r (maint_rank_r[RANK_WIDTH-1:0]),
.maint_req_r (maint_req_r),
.maint_zq_r (maint_zq_r),
.maint_sre_r (maint_sre_r),
.maint_srx_r (maint_srx_r),
.maint_ref_zq_wip (maint_ref_zq_wip),
.periodic_rd_r (periodic_rd_r),
.periodic_rd_rank_r (periodic_rd_rank_r[RANK_WIDTH-1:0]),
// Inputs
.act_this_rank_r (act_this_rank_r[RANK_BM_BV_WIDTH-1:0]),
.app_periodic_rd_req (app_periodic_rd_req),
.app_ref_req (app_ref_req),
.app_ref_ack (app_ref_ack),
.app_zq_req (app_zq_req),
.app_zq_ack (app_zq_ack),
.app_sr_req (app_sr_req),
.app_sr_active (app_sr_active),
.col_rd_wr (col_rd_wr),
.clk (clk),
.init_calib_complete (init_calib_complete),
.insert_maint_r1 (insert_maint_r1),
.maint_wip_r (maint_wip_r),
.periodic_rd_ack_r (periodic_rd_ack_r),
.rank_busy_r (rank_busy_r[(RANKS*nBANK_MACHS)-1:0]),
.rd_this_rank_r (rd_this_rank_r[RANK_BM_BV_WIDTH-1:0]),
.rst (rst),
.sending_col (sending_col[nBANK_MACHS-1:0]),
.sending_row (sending_row[nBANK_MACHS-1:0]),
.slot_0_present (slot_0_present[7:0]),
.slot_1_present (slot_1_present[7:0]),
.wr_this_rank_r (wr_this_rank_r[RANK_BM_BV_WIDTH-1:0])
);
//***************************************************************************
// Manage requests, reordering and bank timing
//***************************************************************************
mig_7series_v1_9_bank_mach #
(
// Parameters
.TCQ (TCQ),
.EVEN_CWL_2T_MODE (EVEN_CWL_2T_MODE),
.ADDR_CMD_MODE (ADDR_CMD_MODE),
.BANK_WIDTH (BANK_WIDTH),
.BM_CNT_WIDTH (BM_CNT_WIDTH),
.BURST_MODE (BURST_MODE),
.COL_WIDTH (COL_WIDTH),
.CS_WIDTH (CS_WIDTH),
.CL (CL_M),
.CWL (CWL_M),
.CKE_ODT_AUX (CKE_ODT_AUX),
.DATA_BUF_ADDR_WIDTH (DATA_BUF_ADDR_WIDTH),
.DRAM_TYPE (DRAM_TYPE),
.EARLY_WR_DATA_ADDR (EARLY_WR_DATA_ADDR),
.ECC (ECC),
.LOW_IDLE_CNT (LOW_IDLE_CNT),
.nBANK_MACHS (nBANK_MACHS),
.nCK_PER_CLK (nCK_PER_CLK),
.nCS_PER_RANK (nCS_PER_RANK),
.nOP_WAIT (nOP_WAIT),
.nRAS (nRAS),
.nRCD (nRCD),
.nRFC (nRFC),
.nRP (nRP),
.nRTP (nRTP),
.nSLOTS (nSLOTS),
.nWR (nWR),
.nXSDLL (tXSDLL),
.ORDERING (ORDERING),
.RANK_BM_BV_WIDTH (RANK_BM_BV_WIDTH),
.RANK_WIDTH (RANK_WIDTH),
.RANKS (RANKS),
.ROW_WIDTH (ROW_WIDTH),
.RTT_NOM (RTT_NOM),
.RTT_WR (RTT_WR),
.SLOT_0_CONFIG (SLOT_0_CONFIG),
.SLOT_1_CONFIG (SLOT_1_CONFIG),
.STARVE_LIMIT (STARVE_LIMIT),
.tZQCS (tZQCS)
)
bank_mach0
(
// Outputs
.accept (accept),
.accept_ns (accept_ns),
.act_this_rank_r (act_this_rank_r[RANK_BM_BV_WIDTH-1:0]),
.bank_mach_next (bank_mach_next[BM_CNT_WIDTH-1:0]),
.col_a (col_a[ROW_WIDTH-1:0]),
.col_ba (col_ba[BANK_WIDTH-1:0]),
.col_data_buf_addr (col_data_buf_addr[DATA_BUF_ADDR_WIDTH-1:0]),
.col_periodic_rd (col_periodic_rd),
.col_ra (col_ra[RANK_WIDTH-1:0]),
.col_rmw (col_rmw),
.col_rd_wr (col_rd_wr),
.col_row (col_row[ROW_WIDTH-1:0]),
.col_size (col_size),
.col_wr_data_buf_addr (col_wr_data_buf_addr[DATA_BUF_ADDR_WIDTH-1:0]),
.mc_bank (mc_bank_ns),
.mc_address (mc_address_ns),
.mc_ras_n (mc_ras_n_ns),
.mc_cas_n (mc_cas_n_ns),
.mc_we_n (mc_we_n_ns),
.mc_cs_n (mc_cs_n_ns),
.mc_odt (mc_odt_ns),
.mc_cke (mc_cke_ns),
.mc_aux_out0 (mc_aux_out0_ns),
.mc_aux_out1 (mc_aux_out1_ns),
.mc_cmd (mc_cmd_ns),
.mc_data_offset (mc_data_offset_ns),
.mc_data_offset_1 (mc_data_offset_1_ns),
.mc_data_offset_2 (mc_data_offset_2_ns),
.mc_cas_slot (mc_cas_slot_ns),
.insert_maint_r1 (insert_maint_r1),
.maint_wip_r (maint_wip_r),
.periodic_rd_ack_r (periodic_rd_ack_r),
.rank_busy_r (rank_busy_r[(RANKS*nBANK_MACHS)-1:0]),
.rd_this_rank_r (rd_this_rank_r[RANK_BM_BV_WIDTH-1:0]),
.sending_row (sending_row[nBANK_MACHS-1:0]),
.sending_col (sending_col[nBANK_MACHS-1:0]),
.sent_col (sent_col),
.sent_col_r (sent_col_r),
.wr_this_rank_r (wr_this_rank_r[RANK_BM_BV_WIDTH-1:0]),
// Inputs
.bank (bank[BANK_WIDTH-1:0]),
.calib_rddata_offset (calib_rd_data_offset),
.calib_rddata_offset_1 (calib_rd_data_offset_1),
.calib_rddata_offset_2 (calib_rd_data_offset_2),
.clk (clk),
.cmd (cmd[2:0]),
.col (col[COL_WIDTH-1:0]),
.data_buf_addr (data_buf_addr[DATA_BUF_ADDR_WIDTH-1:0]),
.init_calib_complete (init_calib_complete),
.phy_rddata_valid (phy_rddata_valid),
.dq_busy_data (dq_busy_data),
.hi_priority (hi_priority),
.inhbt_act_faw_r (inhbt_act_faw_r[RANKS-1:0]),
.inhbt_rd (inhbt_rd[RANKS-1:0]),
.inhbt_wr (inhbt_wr[RANKS-1:0]),
.maint_rank_r (maint_rank_r[RANK_WIDTH-1:0]),
.maint_req_r (maint_req_r),
.maint_zq_r (maint_zq_r),
.maint_sre_r (maint_sre_r),
.maint_srx_r (maint_srx_r),
.periodic_rd_r (periodic_rd_r),
.periodic_rd_rank_r (periodic_rd_rank_r[RANK_WIDTH-1:0]),
.phy_mc_cmd_full (phy_mc_cmd_full),
.phy_mc_ctl_full (phy_mc_ctl_full),
.phy_mc_data_full (phy_mc_data_full),
.rank (rank[RANK_WIDTH-1:0]),
.rd_data_addr (rd_data_addr[DATA_BUF_ADDR_WIDTH-1:0]),
.rd_rmw (rd_rmw),
.row (row[ROW_WIDTH-1:0]),
.rst (rst),
.size (size),
.slot_0_present (slot_0_present[7:0]),
.slot_1_present (slot_1_present[7:0]),
.use_addr (use_addr)
);
//***************************************************************************
// Manage DQ bus
//***************************************************************************
mig_7series_v1_9_col_mach #
(
// Parameters
.TCQ (TCQ),
.BANK_WIDTH (BANK_WIDTH),
.BURST_MODE (BURST_MODE),
.COL_WIDTH (COL_WIDTH),
.CS_WIDTH (CS_WIDTH),
.DATA_BUF_ADDR_WIDTH (DATA_BUF_ADDR_WIDTH),
.DATA_BUF_OFFSET_WIDTH (DATA_BUF_OFFSET_WIDTH),
.DELAY_WR_DATA_CNTRL (DELAY_WR_DATA_CNTRL),
.DQS_WIDTH (DQS_WIDTH),
.DRAM_TYPE (DRAM_TYPE),
.EARLY_WR_DATA_ADDR (EARLY_WR_DATA_ADDR),
.ECC (ECC),
.MC_ERR_ADDR_WIDTH (MC_ERR_ADDR_WIDTH),
.nCK_PER_CLK (nCK_PER_CLK),
.nPHY_WRLAT (nPHY_WRLAT),
.RANK_WIDTH (RANK_WIDTH),
.ROW_WIDTH (ROW_WIDTH)
)
col_mach0
(
// Outputs
.mc_wrdata_en (mc_wrdata_en_ns),
.dq_busy_data (dq_busy_data),
.ecc_err_addr (ecc_err_addr[MC_ERR_ADDR_WIDTH-1:0]),
.ecc_status_valid (ecc_status_valid),
.rd_data_addr (rd_data_addr[DATA_BUF_ADDR_WIDTH-1:0]),
.rd_data_en (rd_data_en),
.rd_data_end (rd_data_end),
.rd_data_offset (rd_data_offset),
.rd_rmw (rd_rmw),
.wr_data_addr (wr_data_addr_ns),
.wr_data_en (wr_data_en_ns),
.wr_data_offset (wr_data_offset_ns),
.wr_ecc_buf (wr_ecc_buf),
.col_read_fifo_empty (col_read_fifo_empty),
// Inputs
.clk (clk),
.rst (rst),
.col_a (col_a[ROW_WIDTH-1:0]),
.col_ba (col_ba[BANK_WIDTH-1:0]),
.col_data_buf_addr (col_data_buf_addr[DATA_BUF_ADDR_WIDTH-1:0]),
.col_periodic_rd (col_periodic_rd),
.col_ra (col_ra[RANK_WIDTH-1:0]),
.col_rmw (col_rmw),
.col_rd_wr (col_rd_wr),
.col_row (col_row[ROW_WIDTH-1:0]),
.col_size (col_size),
.col_wr_data_buf_addr (col_wr_data_buf_addr[DATA_BUF_ADDR_WIDTH-1:0]),
.phy_rddata_valid (phy_rddata_valid),
.sent_col (EVEN_CWL_2T_MODE == "ON" ? sent_col_r : sent_col)
);
//***************************************************************************
// Implement ECC
//***************************************************************************
// Total ECC word length = ECC code width + Data width
localparam CODE_WIDTH = DATA_WIDTH + ECC_WIDTH;
generate
if (ECC == "OFF") begin : ecc_off
assign rd_data = phy_rd_data;
assign mc_wrdata = wr_data;
assign mc_wrdata_mask = wr_data_mask;
assign ecc_single = 4'b0;
assign ecc_multiple = 4'b0;
end
else begin : ecc_on
wire [CODE_WIDTH*ECC_WIDTH-1:0] h_rows;
wire [2*nCK_PER_CLK*DATA_WIDTH-1:0] rd_merge_data;
// Merge and encode
mig_7series_v1_9_ecc_merge_enc #
(
// Parameters
.TCQ (TCQ),
.CODE_WIDTH (CODE_WIDTH),
.DATA_BUF_ADDR_WIDTH (DATA_BUF_ADDR_WIDTH),
.DATA_WIDTH (DATA_WIDTH),
.DQ_WIDTH (DQ_WIDTH),
.ECC_WIDTH (ECC_WIDTH),
.PAYLOAD_WIDTH (PAYLOAD_WIDTH),
.nCK_PER_CLK (nCK_PER_CLK)
)
ecc_merge_enc0
(
// Outputs
.mc_wrdata (mc_wrdata),
.mc_wrdata_mask (mc_wrdata_mask),
// Inputs
.clk (clk),
.rst (rst),
.h_rows (h_rows),
.rd_merge_data (rd_merge_data),
.raw_not_ecc (raw_not_ecc),
.wr_data (wr_data),
.wr_data_mask (wr_data_mask)
);
// Decode and fix
mig_7series_v1_9_ecc_dec_fix #
(
// Parameters
.TCQ (TCQ),
.CODE_WIDTH (CODE_WIDTH),
.DATA_WIDTH (DATA_WIDTH),
.DQ_WIDTH (DQ_WIDTH),
.ECC_WIDTH (ECC_WIDTH),
.PAYLOAD_WIDTH (PAYLOAD_WIDTH),
.nCK_PER_CLK (nCK_PER_CLK)
)
ecc_dec_fix0
(
// Outputs
.ecc_multiple (ecc_multiple),
.ecc_single (ecc_single),
.rd_data (rd_data),
// Inputs
.clk (clk),
.rst (rst),
.correct_en (correct_en),
.phy_rddata (phy_rd_data),
.ecc_status_valid (ecc_status_valid),
.h_rows (h_rows)
);
// ECC Buffer
mig_7series_v1_9_ecc_buf #
(
// Parameters
.TCQ (TCQ),
.DATA_BUF_ADDR_WIDTH (DATA_BUF_ADDR_WIDTH),
.DATA_BUF_OFFSET_WIDTH (DATA_BUF_OFFSET_WIDTH),
.DATA_WIDTH (DATA_WIDTH),
.PAYLOAD_WIDTH (PAYLOAD_WIDTH),
.nCK_PER_CLK (nCK_PER_CLK)
)
ecc_buf0
(
// Outputs
.rd_merge_data (rd_merge_data),
// Inputs
.clk (clk),
.rst (rst),
.rd_data (rd_data),
.rd_data_addr (rd_data_addr),
.rd_data_offset (rd_data_offset),
.wr_data_addr (wr_data_addr),
.wr_data_offset (wr_data_offset),
.wr_ecc_buf (wr_ecc_buf)
);
// Generate ECC table
mig_7series_v1_9_ecc_gen #
(
// Parameters
.CODE_WIDTH (CODE_WIDTH),
.DATA_WIDTH (DATA_WIDTH),
.ECC_WIDTH (ECC_WIDTH)
)
ecc_gen0
(
// Outputs
.h_rows (h_rows)
);
`ifdef DISPLAY_H_MATRIX
integer i;
always @(negedge rst) begin
$display ("**********************************************");
$display ("H Matrix:");
for (i=0; i<ECC_WIDTH; i=i+1)
$display ("%b", h_rows[i*CODE_WIDTH+:CODE_WIDTH]);
$display ("**********************************************");
end
`endif
end
endgenerate
endmodule // mc
|
//*****************************************************************************
// (c) Copyright 2008 - 2013 Xilinx, Inc. All rights reserved.
//
// This file contains confidential and proprietary information
// of Xilinx, Inc. and is protected under U.S. and
// international copyright and other intellectual property
// laws.
//
// DISCLAIMER
// This disclaimer is not a license and does not grant any
// rights to the materials distributed herewith. Except as
// otherwise provided in a valid license issued to you by
// Xilinx, and to the maximum extent permitted by applicable
// law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND
// WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES
// AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
// BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-
// INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and
// (2) Xilinx shall not be liable (whether in contract or tort,
// including negligence, or under any other theory of
// liability) for any loss or damage of any kind or nature
// related to, arising under or in connection with these
// materials, including for any direct, or any indirect,
// special, incidental, or consequential loss or damage
// (including loss of data, profits, goodwill, or any type of
// loss or damage suffered as a result of any action brought
// by a third party) even if such damage or loss was
// reasonably foreseeable or Xilinx had been advised of the
// possibility of the same.
//
// CRITICAL APPLICATIONS
// Xilinx products are not designed or intended to be fail-
// safe, or for use in any application requiring fail-safe
// performance, such as life-support or safety devices or
// systems, Class III medical devices, nuclear facilities,
// applications related to the deployment of airbags, or any
// other applications that could lead to death, personal
// injury, or severe property or environmental damage
// (individually and collectively, "Critical
// Applications"). Customer assumes the sole risk and
// liability of any use of Xilinx products in Critical
// Applications, subject only to applicable laws and
// regulations governing limitations on product liability.
//
// THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS
// PART OF THIS FILE AT ALL TIMES.
//
//*****************************************************************************
// ____ ____
// / /\/ /
// /___/ \ / Vendor : Xilinx
// \ \ \/ Version : %version
// \ \ Application : MIG
// / / Filename : mc.v
// /___/ /\ Date Last Modified : $date$
// \ \ / \ Date Created : Tue Jun 30 2009
// \___\/\___\
//
//Device : 7-Series
//Design Name : DDR3 SDRAM
//Purpose :
//Reference :
//Revision History :
//*****************************************************************************
//*****************************************************************************
// Top level memory sequencer structural block. This block
// instantiates the rank, bank, and column machines.
//*****************************************************************************
`timescale 1ps/1ps
module mig_7series_v1_9_mc #
(
parameter TCQ = 100, // clk->out delay(sim only)
parameter ADDR_CMD_MODE = "1T", // registered or
// 1Tfered mem?
parameter BANK_WIDTH = 3, // bank address width
parameter BM_CNT_WIDTH = 2, // # BM counter width
// i.e., log2(nBANK_MACHS)
parameter BURST_MODE = "8", // Burst length
parameter CL = 5, // Read CAS latency
// (in clk cyc)
parameter CMD_PIPE_PLUS1 = "ON", // add register stage
// between MC and PHY
parameter COL_WIDTH = 12, // column address width
parameter CS_WIDTH = 4, // # of unique CS outputs
parameter CWL = 5, // Write CAS latency
// (in clk cyc)
parameter DATA_BUF_ADDR_WIDTH = 8, // User request tag (e.g.
// user src/dest buf addr)
parameter DATA_BUF_OFFSET_WIDTH = 1, // User buffer offset width
parameter DATA_WIDTH = 64, // Data bus width
parameter DQ_WIDTH = 64, // # of DQ (data)
parameter DQS_WIDTH = 8, // # of DQS (strobe)
parameter DRAM_TYPE = "DDR3", // Memory I/F type:
// "DDR3", "DDR2"
parameter ECC = "OFF", // ECC ON/OFF?
parameter ECC_WIDTH = 8, // # of ECC bits
parameter MAINT_PRESCALER_PERIOD= 200000, // maintenance period (ps)
parameter MC_ERR_ADDR_WIDTH = 31, // # of error address bits
parameter nBANK_MACHS = 4, // # of bank machines (BM)
parameter nCK_PER_CLK = 4, // DRAM clock : MC clock
// frequency ratio
parameter nCS_PER_RANK = 1, // # of unique CS outputs
// per rank
parameter nREFRESH_BANK = 1, // # of REF cmds to pull-in
parameter nSLOTS = 1, // # DIMM slots in system
parameter ORDERING = "NORM", // request ordering mode
parameter PAYLOAD_WIDTH = 64, // Width of data payload
// from PHY
parameter RANK_WIDTH = 2, // # of bits to count ranks
parameter RANKS = 4, // # of ranks of DRAM
parameter REG_CTRL = "ON", // "ON" for registered DIMM
parameter ROW_WIDTH = 16, // row address width
parameter RTT_NOM = "40", // Nominal ODT value
parameter RTT_WR = "120", // Write ODT value
parameter SLOT_0_CONFIG = 8'b0000_0101, // ranks allowed in slot 0
parameter SLOT_1_CONFIG = 8'b0000_1010, // ranks allowed in slot 1
parameter STARVE_LIMIT = 2, // max # of times a user
// request is allowed to
// lose arbitration when
// reordering is enabled
parameter tCK = 2500, // memory clk period(ps)
parameter tCKE = 10000, // CKE minimum pulse (ps)
parameter tFAW = 40000, // four activate window(ps)
parameter tRAS = 37500, // ACT->PRE cmd period (ps)
parameter tRCD = 12500, // ACT->R/W delay (ps)
parameter tREFI = 7800000, // average periodic
// refresh interval(ps)
parameter CKE_ODT_AUX = "FALSE", //Parameter to turn on/off the aux_out signal
parameter tRFC = 110000, // REF->ACT/REF delay (ps)
parameter tRP = 12500, // PRE cmd period (ps)
parameter tRRD = 10000, // ACT->ACT period (ps)
parameter tRTP = 7500, // Read->PRE cmd delay (ps)
parameter tWTR = 7500, // Internal write->read
// delay (ps)
// requiring DLL lock (CKs)
parameter tZQCS = 64, // ZQCS cmd period (CKs)
parameter tZQI = 128_000_000, // ZQCS interval (ps)
parameter tPRDI = 1_000_000, // pS
parameter USER_REFRESH = "OFF" // Whether user manages REF
)
(
// System inputs
input clk,
input rst,
// Physical memory slot presence
input [7:0] slot_0_present,
input [7:0] slot_1_present,
// Native Interface
input [2:0] cmd,
input [DATA_BUF_ADDR_WIDTH-1:0] data_buf_addr,
input hi_priority,
input size,
input [BANK_WIDTH-1:0] bank,
input [COL_WIDTH-1:0] col,
input [RANK_WIDTH-1:0] rank,
input [ROW_WIDTH-1:0] row,
input use_addr,
input [2*nCK_PER_CLK*PAYLOAD_WIDTH-1:0] wr_data,
input [2*nCK_PER_CLK*DATA_WIDTH/8-1:0] wr_data_mask,
output accept,
output accept_ns,
output [BM_CNT_WIDTH-1:0] bank_mach_next,
output wire [2*nCK_PER_CLK*PAYLOAD_WIDTH-1:0] rd_data,
output [DATA_BUF_ADDR_WIDTH-1:0] rd_data_addr,
output rd_data_en,
output rd_data_end,
output [DATA_BUF_OFFSET_WIDTH-1:0] rd_data_offset,
(* keep = "true", max_fanout = 30 *) output reg [DATA_BUF_ADDR_WIDTH-1:0] wr_data_addr /* synthesis syn_maxfan = 30 */,
output reg wr_data_en,
(* keep = "true", max_fanout = 30 *) output reg [DATA_BUF_OFFSET_WIDTH-1:0] wr_data_offset /* synthesis syn_maxfan = 30 */,
output mc_read_idle,
output mc_ref_zq_wip,
// ECC interface
input correct_en,
input [2*nCK_PER_CLK-1:0] raw_not_ecc,
output [MC_ERR_ADDR_WIDTH-1:0] ecc_err_addr,
output [2*nCK_PER_CLK-1:0] ecc_single,
output [2*nCK_PER_CLK-1:0] ecc_multiple,
// User maintenance requests
input app_periodic_rd_req,
input app_ref_req,
input app_zq_req,
input app_sr_req,
output app_sr_active,
output app_ref_ack,
output app_zq_ack,
// MC <==> PHY Interface
output reg [nCK_PER_CLK-1:0] mc_ras_n,
output reg [nCK_PER_CLK-1:0] mc_cas_n,
output reg [nCK_PER_CLK-1:0] mc_we_n,
output reg [nCK_PER_CLK*ROW_WIDTH-1:0] mc_address,
output reg [nCK_PER_CLK*BANK_WIDTH-1:0] mc_bank,
output reg [CS_WIDTH*nCS_PER_RANK*nCK_PER_CLK-1:0] mc_cs_n,
output reg [1:0] mc_odt,
output reg [nCK_PER_CLK-1:0] mc_cke,
output wire mc_reset_n,
output wire [2*nCK_PER_CLK*DQ_WIDTH-1:0] mc_wrdata,
output wire [2*nCK_PER_CLK*DQ_WIDTH/8-1:0]mc_wrdata_mask,
output reg mc_wrdata_en,
output wire mc_cmd_wren,
output wire mc_ctl_wren,
output reg [2:0] mc_cmd,
output reg [5:0] mc_data_offset,
output reg [5:0] mc_data_offset_1,
output reg [5:0] mc_data_offset_2,
output reg [1:0] mc_cas_slot,
output reg [3:0] mc_aux_out0,
output reg [3:0] mc_aux_out1,
output reg [1:0] mc_rank_cnt,
input phy_mc_ctl_full,
input phy_mc_cmd_full,
input phy_mc_data_full,
input [2*nCK_PER_CLK*DQ_WIDTH-1:0] phy_rd_data,
input phy_rddata_valid,
input init_calib_complete,
input [6*RANKS-1:0] calib_rd_data_offset,
input [6*RANKS-1:0] calib_rd_data_offset_1,
input [6*RANKS-1:0] calib_rd_data_offset_2
);
assign mc_reset_n = 1'b1; // never reset memory
assign mc_cmd_wren = 1'b1; // always write CMD FIFO(issue DSEL when idle)
assign mc_ctl_wren = 1'b1; // always write CTL FIFO(issue nondata when idle)
// Ensure there is always at least one rank present during operation
`ifdef MC_SVA
ranks_present: assert property
(@(posedge clk) (rst || (|(slot_0_present | slot_1_present))));
`endif
// Reserved. Do not change.
localparam nPHY_WRLAT = 2;
// always delay write data control unless ECC mode is enabled
localparam DELAY_WR_DATA_CNTRL = ECC == "ON" ? 0 : 1;
// Ensure that write control is delayed for appropriate CWL
/*`ifdef MC_SVA
delay_wr_data_zero_CWL_le_6: assert property
(@(posedge clk) ((CWL > 6) || (DELAY_WR_DATA_CNTRL == 0)));
`endif*/
// Never retrieve WR_DATA_ADDR early
localparam EARLY_WR_DATA_ADDR = "OFF";
//***************************************************************************
// Convert timing parameters from time to clock cycles
//***************************************************************************
localparam nCKE = cdiv(tCKE, tCK);
localparam nRP = cdiv(tRP, tCK);
localparam nRCD = cdiv(tRCD, tCK);
localparam nRAS = cdiv(tRAS, tCK);
localparam nFAW = cdiv(tFAW, tCK);
localparam nRFC = cdiv(tRFC, tCK);
// Convert tWR. As per specification, write recover for autoprecharge
// cycles doesn't support values of 9 and 11. Round up 9 to 10 and 11 to 12
localparam nWR_CK = cdiv(15000, tCK) ;
localparam nWR = (nWR_CK == 9) ? 10 : (nWR_CK == 11) ? 12 : nWR_CK;
// tRRD, tWTR at tRTP have a 4 cycle floor in DDR3 and 2 cycle floor in DDR2
localparam nRRD_CK = cdiv(tRRD, tCK);
localparam nRRD = (DRAM_TYPE == "DDR3") ? (nRRD_CK < 4) ? 4 : nRRD_CK
: (nRRD_CK < 2) ? 2 : nRRD_CK;
localparam nWTR_CK = cdiv(tWTR, tCK);
localparam nWTR = (DRAM_TYPE == "DDR3") ? (nWTR_CK < 4) ? 4 : nWTR_CK
: (nWTR_CK < 2) ? 2 : nWTR_CK;
localparam nRTP_CK = cdiv(tRTP, tCK);
localparam nRTP = (DRAM_TYPE == "DDR3") ? (nRTP_CK < 4) ? 4 : nRTP_CK
: (nRTP_CK < 2) ? 2 : nRTP_CK;
// Add a cycle to CL/CWL for the register in RDIMM devices
localparam CWL_M = (REG_CTRL == "ON") ? CWL + 1 : CWL;
localparam CL_M = (REG_CTRL == "ON") ? CL + 1 : CL;
// Tuneable delay between read and write data on the DQ bus
localparam DQRD2DQWR_DLY = 4;
// CKE minimum pulse width for self-refresh (SRE->SRX minimum time)
localparam nCKESR = nCKE + 1;
// Delay from SRE to command requiring locked DLL. Currently fixed at 512 for
// all devices per JEDEC spec.
localparam tXSDLL = 512;
//***************************************************************************
// Set up maintenance counter dividers
//***************************************************************************
// CK clock divisor to generate maintenance prescaler period (round down)
localparam MAINT_PRESCALER_DIV = MAINT_PRESCALER_PERIOD / (tCK*nCK_PER_CLK);
// Maintenance prescaler divisor for refresh timer. Essentially, this is
// just (tREFI / MAINT_PRESCALER_PERIOD), but we must account for the worst
// case delay from the time we get a tick from the refresh counter to the
// time that we can actually issue the REF command. Thus, subtract tRCD, CL,
// data burst time and tRP for each implemented bank machine to ensure that
// all transactions can complete before tREFI expires
localparam REFRESH_TIMER_DIV =
USER_REFRESH == "ON" ? 0 :
(tREFI-((tRCD+((CL+4)*tCK)+tRP)*nBANK_MACHS)) / MAINT_PRESCALER_PERIOD;
// Periodic read (RESERVED - not currently required or supported in 7 series)
// tPRDI should only be set to 0
// localparam tPRDI = 0; // Do NOT change.
localparam PERIODIC_RD_TIMER_DIV = tPRDI / MAINT_PRESCALER_PERIOD;
// Convert maintenance prescaler from ps to ns
localparam MAINT_PRESCALER_PERIOD_NS = MAINT_PRESCALER_PERIOD / 1000;
// Maintenance prescaler divisor for ZQ calibration (ZQCS) timer
localparam ZQ_TIMER_DIV = tZQI / MAINT_PRESCALER_PERIOD_NS;
// Bus width required to broadcast a single bit rank signal among all the
// bank machines - 1 bit per rank, per bank
localparam RANK_BM_BV_WIDTH = nBANK_MACHS * RANKS;
//***************************************************************************
// Define 2T, CWL-even mode to enable multi-fabric-cycle 2T commands
//***************************************************************************
localparam EVEN_CWL_2T_MODE =
((ADDR_CMD_MODE == "2T") && (!(CWL % 2))) ? "ON" : "OFF";
//***************************************************************************
// Reserved feature control.
//***************************************************************************
// Open page wait mode is reserved.
// nOP_WAIT is the number of states a bank machine will park itself
// on an otherwise inactive open page before closing the page. If
// nOP_WAIT == 0, open page wait mode is disabled. If nOP_WAIT == -1,
// the bank machine will remain parked until the pool of idle bank machines
// are less than LOW_IDLE_CNT. At which point parked bank machines
// are selected to exit until the number of idle bank machines exceeds the
// LOW_IDLE_CNT.
localparam nOP_WAIT = 0; // Open page mode
localparam LOW_IDLE_CNT = 0; // Low idle bank machine threshold
//***************************************************************************
// Internal wires
//***************************************************************************
wire [RANK_BM_BV_WIDTH-1:0] act_this_rank_r;
wire [ROW_WIDTH-1:0] col_a;
wire [BANK_WIDTH-1:0] col_ba;
wire [DATA_BUF_ADDR_WIDTH-1:0] col_data_buf_addr;
wire col_periodic_rd;
wire [RANK_WIDTH-1:0] col_ra;
wire col_rmw;
wire col_rd_wr;
wire [ROW_WIDTH-1:0] col_row;
wire col_size;
wire [DATA_BUF_ADDR_WIDTH-1:0] col_wr_data_buf_addr;
wire dq_busy_data;
wire ecc_status_valid;
wire [RANKS-1:0] inhbt_act_faw_r;
wire [RANKS-1:0] inhbt_rd;
wire [RANKS-1:0] inhbt_wr;
wire insert_maint_r1;
wire [RANK_WIDTH-1:0] maint_rank_r;
wire maint_req_r;
wire maint_wip_r;
wire maint_zq_r;
wire maint_sre_r;
wire maint_srx_r;
wire periodic_rd_ack_r;
wire periodic_rd_r;
wire [RANK_WIDTH-1:0] periodic_rd_rank_r;
wire [(RANKS*nBANK_MACHS)-1:0] rank_busy_r;
wire rd_rmw;
wire [RANK_BM_BV_WIDTH-1:0] rd_this_rank_r;
wire [nBANK_MACHS-1:0] sending_col;
wire [nBANK_MACHS-1:0] sending_row;
wire sent_col;
wire sent_col_r;
wire wr_ecc_buf;
wire [RANK_BM_BV_WIDTH-1:0] wr_this_rank_r;
// MC/PHY optional pipeline stage support
wire [nCK_PER_CLK-1:0] mc_ras_n_ns;
wire [nCK_PER_CLK-1:0] mc_cas_n_ns;
wire [nCK_PER_CLK-1:0] mc_we_n_ns;
wire [nCK_PER_CLK*ROW_WIDTH-1:0] mc_address_ns;
wire [nCK_PER_CLK*BANK_WIDTH-1:0] mc_bank_ns;
wire [CS_WIDTH*nCS_PER_RANK*nCK_PER_CLK-1:0] mc_cs_n_ns;
wire [1:0] mc_odt_ns;
wire [nCK_PER_CLK-1:0] mc_cke_ns;
wire [3:0] mc_aux_out0_ns;
wire [3:0] mc_aux_out1_ns;
wire [1:0] mc_rank_cnt_ns = col_ra;
wire [2:0] mc_cmd_ns;
wire [5:0] mc_data_offset_ns;
wire [5:0] mc_data_offset_1_ns;
wire [5:0] mc_data_offset_2_ns;
wire [1:0] mc_cas_slot_ns;
wire mc_wrdata_en_ns;
wire [DATA_BUF_ADDR_WIDTH-1:0] wr_data_addr_ns;
wire wr_data_en_ns;
wire [DATA_BUF_OFFSET_WIDTH-1:0] wr_data_offset_ns;
integer i;
// MC Read idle support
wire col_read_fifo_empty;
wire mc_read_idle_ns;
reg mc_read_idle_r;
// MC Maintenance in progress with bus idle indication
wire maint_ref_zq_wip;
wire mc_ref_zq_wip_ns;
reg mc_ref_zq_wip_r;
//***************************************************************************
// Function cdiv
// Description:
// This function performs ceiling division (divide and round-up)
// Inputs:
// num: integer to be divided
// div: divisor
// Outputs:
// cdiv: result of ceiling division (num/div, rounded up)
//***************************************************************************
function integer cdiv (input integer num, input integer div);
begin
// perform division, then add 1 if and only if remainder is non-zero
cdiv = (num/div) + (((num%div)>0) ? 1 : 0);
end
endfunction // cdiv
//***************************************************************************
// Optional pipeline register stage on MC/PHY interface
//***************************************************************************
generate
if (CMD_PIPE_PLUS1 == "ON") begin : cmd_pipe_plus // register interface
always @(posedge clk) begin
mc_address <= #TCQ mc_address_ns;
mc_bank <= #TCQ mc_bank_ns;
mc_cas_n <= #TCQ mc_cas_n_ns;
mc_cs_n <= #TCQ mc_cs_n_ns;
mc_odt <= #TCQ mc_odt_ns;
mc_cke <= #TCQ mc_cke_ns;
mc_aux_out0 <= #TCQ mc_aux_out0_ns;
mc_aux_out1 <= #TCQ mc_aux_out1_ns;
mc_cmd <= #TCQ mc_cmd_ns;
mc_ras_n <= #TCQ mc_ras_n_ns;
mc_we_n <= #TCQ mc_we_n_ns;
mc_data_offset <= #TCQ mc_data_offset_ns;
mc_data_offset_1 <= #TCQ mc_data_offset_1_ns;
mc_data_offset_2 <= #TCQ mc_data_offset_2_ns;
mc_cas_slot <= #TCQ mc_cas_slot_ns;
mc_wrdata_en <= #TCQ mc_wrdata_en_ns;
mc_rank_cnt <= #TCQ mc_rank_cnt_ns;
wr_data_addr <= #TCQ wr_data_addr_ns;
wr_data_en <= #TCQ wr_data_en_ns;
wr_data_offset <= #TCQ wr_data_offset_ns;
end // always @ (posedge clk)
end // block: cmd_pipe_plus
else begin : cmd_pipe_plus0 // don't register interface
always @( mc_address_ns or mc_aux_out0_ns or mc_aux_out1_ns or
mc_bank_ns or mc_cas_n_ns or mc_cmd_ns or mc_cs_n_ns or
mc_odt_ns or mc_cke_ns or mc_data_offset_ns or
mc_data_offset_1_ns or mc_data_offset_2_ns or mc_rank_cnt_ns or
mc_ras_n_ns or mc_we_n_ns or mc_wrdata_en_ns or
wr_data_addr_ns or wr_data_en_ns or wr_data_offset_ns or
mc_cas_slot_ns)
begin
mc_address = #TCQ mc_address_ns;
mc_bank = #TCQ mc_bank_ns;
mc_cas_n = #TCQ mc_cas_n_ns;
mc_cs_n = #TCQ mc_cs_n_ns;
mc_odt = #TCQ mc_odt_ns;
mc_cke = #TCQ mc_cke_ns;
mc_aux_out0 = #TCQ mc_aux_out0_ns;
mc_aux_out1 = #TCQ mc_aux_out1_ns;
mc_cmd = #TCQ mc_cmd_ns;
mc_ras_n = #TCQ mc_ras_n_ns;
mc_we_n = #TCQ mc_we_n_ns;
mc_data_offset = #TCQ mc_data_offset_ns;
mc_data_offset_1 = #TCQ mc_data_offset_1_ns;
mc_data_offset_2 = #TCQ mc_data_offset_2_ns;
mc_cas_slot = #TCQ mc_cas_slot_ns;
mc_wrdata_en = #TCQ mc_wrdata_en_ns;
mc_rank_cnt = #TCQ mc_rank_cnt_ns;
wr_data_addr = #TCQ wr_data_addr_ns;
wr_data_en = #TCQ wr_data_en_ns;
wr_data_offset = #TCQ wr_data_offset_ns;
end // always @ (...
end // block: cmd_pipe_plus0
endgenerate
//***************************************************************************
// Indicate when there are no pending reads so that input features can be
// powered down
//***************************************************************************
assign mc_read_idle_ns = col_read_fifo_empty & init_calib_complete;
always @(posedge clk) mc_read_idle_r <= #TCQ mc_read_idle_ns;
assign mc_read_idle = mc_read_idle_r;
//***************************************************************************
// Indicate when there is a refresh in progress and the bus is idle so that
// tap adjustments can be made
//***************************************************************************
assign mc_ref_zq_wip_ns = maint_ref_zq_wip && col_read_fifo_empty;
always @(posedge clk) mc_ref_zq_wip_r <= mc_ref_zq_wip_ns;
assign mc_ref_zq_wip = mc_ref_zq_wip_r;
//***************************************************************************
// Manage rank-level timing and maintanence
//***************************************************************************
mig_7series_v1_9_rank_mach #
(
// Parameters
.BURST_MODE (BURST_MODE),
.CL (CL),
.CWL (CWL),
.CS_WIDTH (CS_WIDTH),
.DQRD2DQWR_DLY (DQRD2DQWR_DLY),
.DRAM_TYPE (DRAM_TYPE),
.MAINT_PRESCALER_DIV (MAINT_PRESCALER_DIV),
.nBANK_MACHS (nBANK_MACHS),
.nCKESR (nCKESR),
.nCK_PER_CLK (nCK_PER_CLK),
.nFAW (nFAW),
.nREFRESH_BANK (nREFRESH_BANK),
.nRRD (nRRD),
.nWTR (nWTR),
.PERIODIC_RD_TIMER_DIV (PERIODIC_RD_TIMER_DIV),
.RANK_BM_BV_WIDTH (RANK_BM_BV_WIDTH),
.RANK_WIDTH (RANK_WIDTH),
.RANKS (RANKS),
.REFRESH_TIMER_DIV (REFRESH_TIMER_DIV),
.ZQ_TIMER_DIV (ZQ_TIMER_DIV)
)
rank_mach0
(
// Outputs
.inhbt_act_faw_r (inhbt_act_faw_r[RANKS-1:0]),
.inhbt_rd (inhbt_rd[RANKS-1:0]),
.inhbt_wr (inhbt_wr[RANKS-1:0]),
.maint_rank_r (maint_rank_r[RANK_WIDTH-1:0]),
.maint_req_r (maint_req_r),
.maint_zq_r (maint_zq_r),
.maint_sre_r (maint_sre_r),
.maint_srx_r (maint_srx_r),
.maint_ref_zq_wip (maint_ref_zq_wip),
.periodic_rd_r (periodic_rd_r),
.periodic_rd_rank_r (periodic_rd_rank_r[RANK_WIDTH-1:0]),
// Inputs
.act_this_rank_r (act_this_rank_r[RANK_BM_BV_WIDTH-1:0]),
.app_periodic_rd_req (app_periodic_rd_req),
.app_ref_req (app_ref_req),
.app_ref_ack (app_ref_ack),
.app_zq_req (app_zq_req),
.app_zq_ack (app_zq_ack),
.app_sr_req (app_sr_req),
.app_sr_active (app_sr_active),
.col_rd_wr (col_rd_wr),
.clk (clk),
.init_calib_complete (init_calib_complete),
.insert_maint_r1 (insert_maint_r1),
.maint_wip_r (maint_wip_r),
.periodic_rd_ack_r (periodic_rd_ack_r),
.rank_busy_r (rank_busy_r[(RANKS*nBANK_MACHS)-1:0]),
.rd_this_rank_r (rd_this_rank_r[RANK_BM_BV_WIDTH-1:0]),
.rst (rst),
.sending_col (sending_col[nBANK_MACHS-1:0]),
.sending_row (sending_row[nBANK_MACHS-1:0]),
.slot_0_present (slot_0_present[7:0]),
.slot_1_present (slot_1_present[7:0]),
.wr_this_rank_r (wr_this_rank_r[RANK_BM_BV_WIDTH-1:0])
);
//***************************************************************************
// Manage requests, reordering and bank timing
//***************************************************************************
mig_7series_v1_9_bank_mach #
(
// Parameters
.TCQ (TCQ),
.EVEN_CWL_2T_MODE (EVEN_CWL_2T_MODE),
.ADDR_CMD_MODE (ADDR_CMD_MODE),
.BANK_WIDTH (BANK_WIDTH),
.BM_CNT_WIDTH (BM_CNT_WIDTH),
.BURST_MODE (BURST_MODE),
.COL_WIDTH (COL_WIDTH),
.CS_WIDTH (CS_WIDTH),
.CL (CL_M),
.CWL (CWL_M),
.CKE_ODT_AUX (CKE_ODT_AUX),
.DATA_BUF_ADDR_WIDTH (DATA_BUF_ADDR_WIDTH),
.DRAM_TYPE (DRAM_TYPE),
.EARLY_WR_DATA_ADDR (EARLY_WR_DATA_ADDR),
.ECC (ECC),
.LOW_IDLE_CNT (LOW_IDLE_CNT),
.nBANK_MACHS (nBANK_MACHS),
.nCK_PER_CLK (nCK_PER_CLK),
.nCS_PER_RANK (nCS_PER_RANK),
.nOP_WAIT (nOP_WAIT),
.nRAS (nRAS),
.nRCD (nRCD),
.nRFC (nRFC),
.nRP (nRP),
.nRTP (nRTP),
.nSLOTS (nSLOTS),
.nWR (nWR),
.nXSDLL (tXSDLL),
.ORDERING (ORDERING),
.RANK_BM_BV_WIDTH (RANK_BM_BV_WIDTH),
.RANK_WIDTH (RANK_WIDTH),
.RANKS (RANKS),
.ROW_WIDTH (ROW_WIDTH),
.RTT_NOM (RTT_NOM),
.RTT_WR (RTT_WR),
.SLOT_0_CONFIG (SLOT_0_CONFIG),
.SLOT_1_CONFIG (SLOT_1_CONFIG),
.STARVE_LIMIT (STARVE_LIMIT),
.tZQCS (tZQCS)
)
bank_mach0
(
// Outputs
.accept (accept),
.accept_ns (accept_ns),
.act_this_rank_r (act_this_rank_r[RANK_BM_BV_WIDTH-1:0]),
.bank_mach_next (bank_mach_next[BM_CNT_WIDTH-1:0]),
.col_a (col_a[ROW_WIDTH-1:0]),
.col_ba (col_ba[BANK_WIDTH-1:0]),
.col_data_buf_addr (col_data_buf_addr[DATA_BUF_ADDR_WIDTH-1:0]),
.col_periodic_rd (col_periodic_rd),
.col_ra (col_ra[RANK_WIDTH-1:0]),
.col_rmw (col_rmw),
.col_rd_wr (col_rd_wr),
.col_row (col_row[ROW_WIDTH-1:0]),
.col_size (col_size),
.col_wr_data_buf_addr (col_wr_data_buf_addr[DATA_BUF_ADDR_WIDTH-1:0]),
.mc_bank (mc_bank_ns),
.mc_address (mc_address_ns),
.mc_ras_n (mc_ras_n_ns),
.mc_cas_n (mc_cas_n_ns),
.mc_we_n (mc_we_n_ns),
.mc_cs_n (mc_cs_n_ns),
.mc_odt (mc_odt_ns),
.mc_cke (mc_cke_ns),
.mc_aux_out0 (mc_aux_out0_ns),
.mc_aux_out1 (mc_aux_out1_ns),
.mc_cmd (mc_cmd_ns),
.mc_data_offset (mc_data_offset_ns),
.mc_data_offset_1 (mc_data_offset_1_ns),
.mc_data_offset_2 (mc_data_offset_2_ns),
.mc_cas_slot (mc_cas_slot_ns),
.insert_maint_r1 (insert_maint_r1),
.maint_wip_r (maint_wip_r),
.periodic_rd_ack_r (periodic_rd_ack_r),
.rank_busy_r (rank_busy_r[(RANKS*nBANK_MACHS)-1:0]),
.rd_this_rank_r (rd_this_rank_r[RANK_BM_BV_WIDTH-1:0]),
.sending_row (sending_row[nBANK_MACHS-1:0]),
.sending_col (sending_col[nBANK_MACHS-1:0]),
.sent_col (sent_col),
.sent_col_r (sent_col_r),
.wr_this_rank_r (wr_this_rank_r[RANK_BM_BV_WIDTH-1:0]),
// Inputs
.bank (bank[BANK_WIDTH-1:0]),
.calib_rddata_offset (calib_rd_data_offset),
.calib_rddata_offset_1 (calib_rd_data_offset_1),
.calib_rddata_offset_2 (calib_rd_data_offset_2),
.clk (clk),
.cmd (cmd[2:0]),
.col (col[COL_WIDTH-1:0]),
.data_buf_addr (data_buf_addr[DATA_BUF_ADDR_WIDTH-1:0]),
.init_calib_complete (init_calib_complete),
.phy_rddata_valid (phy_rddata_valid),
.dq_busy_data (dq_busy_data),
.hi_priority (hi_priority),
.inhbt_act_faw_r (inhbt_act_faw_r[RANKS-1:0]),
.inhbt_rd (inhbt_rd[RANKS-1:0]),
.inhbt_wr (inhbt_wr[RANKS-1:0]),
.maint_rank_r (maint_rank_r[RANK_WIDTH-1:0]),
.maint_req_r (maint_req_r),
.maint_zq_r (maint_zq_r),
.maint_sre_r (maint_sre_r),
.maint_srx_r (maint_srx_r),
.periodic_rd_r (periodic_rd_r),
.periodic_rd_rank_r (periodic_rd_rank_r[RANK_WIDTH-1:0]),
.phy_mc_cmd_full (phy_mc_cmd_full),
.phy_mc_ctl_full (phy_mc_ctl_full),
.phy_mc_data_full (phy_mc_data_full),
.rank (rank[RANK_WIDTH-1:0]),
.rd_data_addr (rd_data_addr[DATA_BUF_ADDR_WIDTH-1:0]),
.rd_rmw (rd_rmw),
.row (row[ROW_WIDTH-1:0]),
.rst (rst),
.size (size),
.slot_0_present (slot_0_present[7:0]),
.slot_1_present (slot_1_present[7:0]),
.use_addr (use_addr)
);
//***************************************************************************
// Manage DQ bus
//***************************************************************************
mig_7series_v1_9_col_mach #
(
// Parameters
.TCQ (TCQ),
.BANK_WIDTH (BANK_WIDTH),
.BURST_MODE (BURST_MODE),
.COL_WIDTH (COL_WIDTH),
.CS_WIDTH (CS_WIDTH),
.DATA_BUF_ADDR_WIDTH (DATA_BUF_ADDR_WIDTH),
.DATA_BUF_OFFSET_WIDTH (DATA_BUF_OFFSET_WIDTH),
.DELAY_WR_DATA_CNTRL (DELAY_WR_DATA_CNTRL),
.DQS_WIDTH (DQS_WIDTH),
.DRAM_TYPE (DRAM_TYPE),
.EARLY_WR_DATA_ADDR (EARLY_WR_DATA_ADDR),
.ECC (ECC),
.MC_ERR_ADDR_WIDTH (MC_ERR_ADDR_WIDTH),
.nCK_PER_CLK (nCK_PER_CLK),
.nPHY_WRLAT (nPHY_WRLAT),
.RANK_WIDTH (RANK_WIDTH),
.ROW_WIDTH (ROW_WIDTH)
)
col_mach0
(
// Outputs
.mc_wrdata_en (mc_wrdata_en_ns),
.dq_busy_data (dq_busy_data),
.ecc_err_addr (ecc_err_addr[MC_ERR_ADDR_WIDTH-1:0]),
.ecc_status_valid (ecc_status_valid),
.rd_data_addr (rd_data_addr[DATA_BUF_ADDR_WIDTH-1:0]),
.rd_data_en (rd_data_en),
.rd_data_end (rd_data_end),
.rd_data_offset (rd_data_offset),
.rd_rmw (rd_rmw),
.wr_data_addr (wr_data_addr_ns),
.wr_data_en (wr_data_en_ns),
.wr_data_offset (wr_data_offset_ns),
.wr_ecc_buf (wr_ecc_buf),
.col_read_fifo_empty (col_read_fifo_empty),
// Inputs
.clk (clk),
.rst (rst),
.col_a (col_a[ROW_WIDTH-1:0]),
.col_ba (col_ba[BANK_WIDTH-1:0]),
.col_data_buf_addr (col_data_buf_addr[DATA_BUF_ADDR_WIDTH-1:0]),
.col_periodic_rd (col_periodic_rd),
.col_ra (col_ra[RANK_WIDTH-1:0]),
.col_rmw (col_rmw),
.col_rd_wr (col_rd_wr),
.col_row (col_row[ROW_WIDTH-1:0]),
.col_size (col_size),
.col_wr_data_buf_addr (col_wr_data_buf_addr[DATA_BUF_ADDR_WIDTH-1:0]),
.phy_rddata_valid (phy_rddata_valid),
.sent_col (EVEN_CWL_2T_MODE == "ON" ? sent_col_r : sent_col)
);
//***************************************************************************
// Implement ECC
//***************************************************************************
// Total ECC word length = ECC code width + Data width
localparam CODE_WIDTH = DATA_WIDTH + ECC_WIDTH;
generate
if (ECC == "OFF") begin : ecc_off
assign rd_data = phy_rd_data;
assign mc_wrdata = wr_data;
assign mc_wrdata_mask = wr_data_mask;
assign ecc_single = 4'b0;
assign ecc_multiple = 4'b0;
end
else begin : ecc_on
wire [CODE_WIDTH*ECC_WIDTH-1:0] h_rows;
wire [2*nCK_PER_CLK*DATA_WIDTH-1:0] rd_merge_data;
// Merge and encode
mig_7series_v1_9_ecc_merge_enc #
(
// Parameters
.TCQ (TCQ),
.CODE_WIDTH (CODE_WIDTH),
.DATA_BUF_ADDR_WIDTH (DATA_BUF_ADDR_WIDTH),
.DATA_WIDTH (DATA_WIDTH),
.DQ_WIDTH (DQ_WIDTH),
.ECC_WIDTH (ECC_WIDTH),
.PAYLOAD_WIDTH (PAYLOAD_WIDTH),
.nCK_PER_CLK (nCK_PER_CLK)
)
ecc_merge_enc0
(
// Outputs
.mc_wrdata (mc_wrdata),
.mc_wrdata_mask (mc_wrdata_mask),
// Inputs
.clk (clk),
.rst (rst),
.h_rows (h_rows),
.rd_merge_data (rd_merge_data),
.raw_not_ecc (raw_not_ecc),
.wr_data (wr_data),
.wr_data_mask (wr_data_mask)
);
// Decode and fix
mig_7series_v1_9_ecc_dec_fix #
(
// Parameters
.TCQ (TCQ),
.CODE_WIDTH (CODE_WIDTH),
.DATA_WIDTH (DATA_WIDTH),
.DQ_WIDTH (DQ_WIDTH),
.ECC_WIDTH (ECC_WIDTH),
.PAYLOAD_WIDTH (PAYLOAD_WIDTH),
.nCK_PER_CLK (nCK_PER_CLK)
)
ecc_dec_fix0
(
// Outputs
.ecc_multiple (ecc_multiple),
.ecc_single (ecc_single),
.rd_data (rd_data),
// Inputs
.clk (clk),
.rst (rst),
.correct_en (correct_en),
.phy_rddata (phy_rd_data),
.ecc_status_valid (ecc_status_valid),
.h_rows (h_rows)
);
// ECC Buffer
mig_7series_v1_9_ecc_buf #
(
// Parameters
.TCQ (TCQ),
.DATA_BUF_ADDR_WIDTH (DATA_BUF_ADDR_WIDTH),
.DATA_BUF_OFFSET_WIDTH (DATA_BUF_OFFSET_WIDTH),
.DATA_WIDTH (DATA_WIDTH),
.PAYLOAD_WIDTH (PAYLOAD_WIDTH),
.nCK_PER_CLK (nCK_PER_CLK)
)
ecc_buf0
(
// Outputs
.rd_merge_data (rd_merge_data),
// Inputs
.clk (clk),
.rst (rst),
.rd_data (rd_data),
.rd_data_addr (rd_data_addr),
.rd_data_offset (rd_data_offset),
.wr_data_addr (wr_data_addr),
.wr_data_offset (wr_data_offset),
.wr_ecc_buf (wr_ecc_buf)
);
// Generate ECC table
mig_7series_v1_9_ecc_gen #
(
// Parameters
.CODE_WIDTH (CODE_WIDTH),
.DATA_WIDTH (DATA_WIDTH),
.ECC_WIDTH (ECC_WIDTH)
)
ecc_gen0
(
// Outputs
.h_rows (h_rows)
);
`ifdef DISPLAY_H_MATRIX
integer i;
always @(negedge rst) begin
$display ("**********************************************");
$display ("H Matrix:");
for (i=0; i<ECC_WIDTH; i=i+1)
$display ("%b", h_rows[i*CODE_WIDTH+:CODE_WIDTH]);
$display ("**********************************************");
end
`endif
end
endgenerate
endmodule // mc
|
//*****************************************************************************
// (c) Copyright 2008 - 2013 Xilinx, Inc. All rights reserved.
//
// This file contains confidential and proprietary information
// of Xilinx, Inc. and is protected under U.S. and
// international copyright and other intellectual property
// laws.
//
// DISCLAIMER
// This disclaimer is not a license and does not grant any
// rights to the materials distributed herewith. Except as
// otherwise provided in a valid license issued to you by
// Xilinx, and to the maximum extent permitted by applicable
// law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND
// WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES
// AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
// BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-
// INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and
// (2) Xilinx shall not be liable (whether in contract or tort,
// including negligence, or under any other theory of
// liability) for any loss or damage of any kind or nature
// related to, arising under or in connection with these
// materials, including for any direct, or any indirect,
// special, incidental, or consequential loss or damage
// (including loss of data, profits, goodwill, or any type of
// loss or damage suffered as a result of any action brought
// by a third party) even if such damage or loss was
// reasonably foreseeable or Xilinx had been advised of the
// possibility of the same.
//
// CRITICAL APPLICATIONS
// Xilinx products are not designed or intended to be fail-
// safe, or for use in any application requiring fail-safe
// performance, such as life-support or safety devices or
// systems, Class III medical devices, nuclear facilities,
// applications related to the deployment of airbags, or any
// other applications that could lead to death, personal
// injury, or severe property or environmental damage
// (individually and collectively, "Critical
// Applications"). Customer assumes the sole risk and
// liability of any use of Xilinx products in Critical
// Applications, subject only to applicable laws and
// regulations governing limitations on product liability.
//
// THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS
// PART OF THIS FILE AT ALL TIMES.
//
//*****************************************************************************
// ____ ____
// / /\/ /
// /___/ \ / Vendor : Xilinx
// \ \ \/ Version : %version
// \ \ Application : MIG
// / / Filename : ecc_dec_fix.v
// /___/ /\ Date Last Modified : $date$
// \ \ / \ Date Created : Tue Jun 30 2009
// \___\/\___\
//
//Device : 7-Series
//Design Name : DDR3 SDRAM
//Purpose :
//Reference :
//Revision History :
//*****************************************************************************
`timescale 1ps/1ps
module mig_7series_v1_9_ecc_dec_fix
#(
parameter TCQ = 100,
parameter PAYLOAD_WIDTH = 64,
parameter CODE_WIDTH = 72,
parameter DATA_WIDTH = 64,
parameter DQ_WIDTH = 72,
parameter ECC_WIDTH = 8,
parameter nCK_PER_CLK = 4
)
(
/*AUTOARG*/
// Outputs
rd_data, ecc_single, ecc_multiple,
// Inputs
clk, rst, h_rows, phy_rddata, correct_en, ecc_status_valid
);
input clk;
input rst;
// Compute syndromes.
input [CODE_WIDTH*ECC_WIDTH-1:0] h_rows;
input [2*nCK_PER_CLK*DQ_WIDTH-1:0] phy_rddata;
wire [2*nCK_PER_CLK*ECC_WIDTH-1:0] syndrome_ns;
genvar k;
genvar m;
generate
for (k=0; k<2*nCK_PER_CLK; k=k+1) begin : ecc_word
for (m=0; m<ECC_WIDTH; m=m+1) begin : ecc_bit
assign syndrome_ns[k*ECC_WIDTH+m] =
^(phy_rddata[k*DQ_WIDTH+:CODE_WIDTH] & h_rows[m*CODE_WIDTH+:CODE_WIDTH]);
end
end
endgenerate
reg [2*nCK_PER_CLK*ECC_WIDTH-1:0] syndrome_r;
always @(posedge clk) syndrome_r <= #TCQ syndrome_ns;
// Extract payload bits from raw DRAM bits and register.
wire [2*nCK_PER_CLK*PAYLOAD_WIDTH-1:0] ecc_rddata_ns;
genvar i;
generate
for (i=0; i<2*nCK_PER_CLK; i=i+1) begin : extract_payload
assign ecc_rddata_ns[i*PAYLOAD_WIDTH+:PAYLOAD_WIDTH] =
phy_rddata[i*DQ_WIDTH+:PAYLOAD_WIDTH];
end
endgenerate
reg [2*nCK_PER_CLK*PAYLOAD_WIDTH-1:0] ecc_rddata_r;
always @(posedge clk) ecc_rddata_r <= #TCQ ecc_rddata_ns;
// Regenerate h_matrix from h_rows leaving out the identity part
// since we're not going to correct the ECC bits themselves.
genvar n;
genvar p;
wire [ECC_WIDTH-1:0] h_matrix [DATA_WIDTH-1:0];
generate
for (n=0; n<DATA_WIDTH; n=n+1) begin : h_col
for (p=0; p<ECC_WIDTH; p=p+1) begin : h_bit
assign h_matrix [n][p] = h_rows [p*CODE_WIDTH+n];
end
end
endgenerate
// Compute flip bits.
wire [2*nCK_PER_CLK*DATA_WIDTH-1:0] flip_bits;
genvar q;
genvar r;
generate
for (q=0; q<2*nCK_PER_CLK; q=q+1) begin : flip_word
for (r=0; r<DATA_WIDTH; r=r+1) begin : flip_bit
assign flip_bits[q*DATA_WIDTH+r] =
h_matrix[r] == syndrome_r[q*ECC_WIDTH+:ECC_WIDTH];
end
end
endgenerate
// Correct data.
output reg [2*nCK_PER_CLK*PAYLOAD_WIDTH-1:0] rd_data;
input correct_en;
integer s;
always @(/*AS*/correct_en or ecc_rddata_r or flip_bits)
for (s=0; s<2*nCK_PER_CLK; s=s+1)
if (correct_en)
rd_data[s*PAYLOAD_WIDTH+:DATA_WIDTH] =
ecc_rddata_r[s*PAYLOAD_WIDTH+:DATA_WIDTH] ^
flip_bits[s*DATA_WIDTH+:DATA_WIDTH];
else rd_data[s*PAYLOAD_WIDTH+:DATA_WIDTH] =
ecc_rddata_r[s*PAYLOAD_WIDTH+:DATA_WIDTH];
// Copy raw payload bits if ECC_TEST is ON.
localparam RAW_BIT_WIDTH = PAYLOAD_WIDTH - DATA_WIDTH;
genvar t;
generate
if (RAW_BIT_WIDTH > 0)
for (t=0; t<2*nCK_PER_CLK; t=t+1) begin : copy_raw_bits
always @(/*AS*/ecc_rddata_r)
rd_data[(t+1)*PAYLOAD_WIDTH-1-:RAW_BIT_WIDTH] =
ecc_rddata_r[(t+1)*PAYLOAD_WIDTH-1-:RAW_BIT_WIDTH];
end
endgenerate
// Generate status information.
input ecc_status_valid;
output wire [2*nCK_PER_CLK-1:0] ecc_single;
output wire [2*nCK_PER_CLK-1:0] ecc_multiple;
genvar v;
generate
for (v=0; v<2*nCK_PER_CLK; v=v+1) begin : compute_status
wire zero = ~|syndrome_r[v*ECC_WIDTH+:ECC_WIDTH];
wire odd = ^syndrome_r[v*ECC_WIDTH+:ECC_WIDTH];
assign ecc_single[v] = ecc_status_valid && ~zero && odd;
assign ecc_multiple[v] = ecc_status_valid && ~zero && ~odd;
end
endgenerate
endmodule
|
//*****************************************************************************
// (c) Copyright 2008 - 2013 Xilinx, Inc. All rights reserved.
//
// This file contains confidential and proprietary information
// of Xilinx, Inc. and is protected under U.S. and
// international copyright and other intellectual property
// laws.
//
// DISCLAIMER
// This disclaimer is not a license and does not grant any
// rights to the materials distributed herewith. Except as
// otherwise provided in a valid license issued to you by
// Xilinx, and to the maximum extent permitted by applicable
// law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND
// WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES
// AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
// BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-
// INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and
// (2) Xilinx shall not be liable (whether in contract or tort,
// including negligence, or under any other theory of
// liability) for any loss or damage of any kind or nature
// related to, arising under or in connection with these
// materials, including for any direct, or any indirect,
// special, incidental, or consequential loss or damage
// (including loss of data, profits, goodwill, or any type of
// loss or damage suffered as a result of any action brought
// by a third party) even if such damage or loss was
// reasonably foreseeable or Xilinx had been advised of the
// possibility of the same.
//
// CRITICAL APPLICATIONS
// Xilinx products are not designed or intended to be fail-
// safe, or for use in any application requiring fail-safe
// performance, such as life-support or safety devices or
// systems, Class III medical devices, nuclear facilities,
// applications related to the deployment of airbags, or any
// other applications that could lead to death, personal
// injury, or severe property or environmental damage
// (individually and collectively, "Critical
// Applications"). Customer assumes the sole risk and
// liability of any use of Xilinx products in Critical
// Applications, subject only to applicable laws and
// regulations governing limitations on product liability.
//
// THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS
// PART OF THIS FILE AT ALL TIMES.
//
//*****************************************************************************
// ____ ____
// / /\/ /
// /___/ \ / Vendor : Xilinx
// \ \ \/ Version : %version
// \ \ Application : MIG
// / / Filename : ecc_dec_fix.v
// /___/ /\ Date Last Modified : $date$
// \ \ / \ Date Created : Tue Jun 30 2009
// \___\/\___\
//
//Device : 7-Series
//Design Name : DDR3 SDRAM
//Purpose :
//Reference :
//Revision History :
//*****************************************************************************
`timescale 1ps/1ps
module mig_7series_v1_9_ecc_dec_fix
#(
parameter TCQ = 100,
parameter PAYLOAD_WIDTH = 64,
parameter CODE_WIDTH = 72,
parameter DATA_WIDTH = 64,
parameter DQ_WIDTH = 72,
parameter ECC_WIDTH = 8,
parameter nCK_PER_CLK = 4
)
(
/*AUTOARG*/
// Outputs
rd_data, ecc_single, ecc_multiple,
// Inputs
clk, rst, h_rows, phy_rddata, correct_en, ecc_status_valid
);
input clk;
input rst;
// Compute syndromes.
input [CODE_WIDTH*ECC_WIDTH-1:0] h_rows;
input [2*nCK_PER_CLK*DQ_WIDTH-1:0] phy_rddata;
wire [2*nCK_PER_CLK*ECC_WIDTH-1:0] syndrome_ns;
genvar k;
genvar m;
generate
for (k=0; k<2*nCK_PER_CLK; k=k+1) begin : ecc_word
for (m=0; m<ECC_WIDTH; m=m+1) begin : ecc_bit
assign syndrome_ns[k*ECC_WIDTH+m] =
^(phy_rddata[k*DQ_WIDTH+:CODE_WIDTH] & h_rows[m*CODE_WIDTH+:CODE_WIDTH]);
end
end
endgenerate
reg [2*nCK_PER_CLK*ECC_WIDTH-1:0] syndrome_r;
always @(posedge clk) syndrome_r <= #TCQ syndrome_ns;
// Extract payload bits from raw DRAM bits and register.
wire [2*nCK_PER_CLK*PAYLOAD_WIDTH-1:0] ecc_rddata_ns;
genvar i;
generate
for (i=0; i<2*nCK_PER_CLK; i=i+1) begin : extract_payload
assign ecc_rddata_ns[i*PAYLOAD_WIDTH+:PAYLOAD_WIDTH] =
phy_rddata[i*DQ_WIDTH+:PAYLOAD_WIDTH];
end
endgenerate
reg [2*nCK_PER_CLK*PAYLOAD_WIDTH-1:0] ecc_rddata_r;
always @(posedge clk) ecc_rddata_r <= #TCQ ecc_rddata_ns;
// Regenerate h_matrix from h_rows leaving out the identity part
// since we're not going to correct the ECC bits themselves.
genvar n;
genvar p;
wire [ECC_WIDTH-1:0] h_matrix [DATA_WIDTH-1:0];
generate
for (n=0; n<DATA_WIDTH; n=n+1) begin : h_col
for (p=0; p<ECC_WIDTH; p=p+1) begin : h_bit
assign h_matrix [n][p] = h_rows [p*CODE_WIDTH+n];
end
end
endgenerate
// Compute flip bits.
wire [2*nCK_PER_CLK*DATA_WIDTH-1:0] flip_bits;
genvar q;
genvar r;
generate
for (q=0; q<2*nCK_PER_CLK; q=q+1) begin : flip_word
for (r=0; r<DATA_WIDTH; r=r+1) begin : flip_bit
assign flip_bits[q*DATA_WIDTH+r] =
h_matrix[r] == syndrome_r[q*ECC_WIDTH+:ECC_WIDTH];
end
end
endgenerate
// Correct data.
output reg [2*nCK_PER_CLK*PAYLOAD_WIDTH-1:0] rd_data;
input correct_en;
integer s;
always @(/*AS*/correct_en or ecc_rddata_r or flip_bits)
for (s=0; s<2*nCK_PER_CLK; s=s+1)
if (correct_en)
rd_data[s*PAYLOAD_WIDTH+:DATA_WIDTH] =
ecc_rddata_r[s*PAYLOAD_WIDTH+:DATA_WIDTH] ^
flip_bits[s*DATA_WIDTH+:DATA_WIDTH];
else rd_data[s*PAYLOAD_WIDTH+:DATA_WIDTH] =
ecc_rddata_r[s*PAYLOAD_WIDTH+:DATA_WIDTH];
// Copy raw payload bits if ECC_TEST is ON.
localparam RAW_BIT_WIDTH = PAYLOAD_WIDTH - DATA_WIDTH;
genvar t;
generate
if (RAW_BIT_WIDTH > 0)
for (t=0; t<2*nCK_PER_CLK; t=t+1) begin : copy_raw_bits
always @(/*AS*/ecc_rddata_r)
rd_data[(t+1)*PAYLOAD_WIDTH-1-:RAW_BIT_WIDTH] =
ecc_rddata_r[(t+1)*PAYLOAD_WIDTH-1-:RAW_BIT_WIDTH];
end
endgenerate
// Generate status information.
input ecc_status_valid;
output wire [2*nCK_PER_CLK-1:0] ecc_single;
output wire [2*nCK_PER_CLK-1:0] ecc_multiple;
genvar v;
generate
for (v=0; v<2*nCK_PER_CLK; v=v+1) begin : compute_status
wire zero = ~|syndrome_r[v*ECC_WIDTH+:ECC_WIDTH];
wire odd = ^syndrome_r[v*ECC_WIDTH+:ECC_WIDTH];
assign ecc_single[v] = ecc_status_valid && ~zero && odd;
assign ecc_multiple[v] = ecc_status_valid && ~zero && ~odd;
end
endgenerate
endmodule
|
//*****************************************************************************
// (c) Copyright 2008 - 2013 Xilinx, Inc. All rights reserved.
//
// This file contains confidential and proprietary information
// of Xilinx, Inc. and is protected under U.S. and
// international copyright and other intellectual property
// laws.
//
// DISCLAIMER
// This disclaimer is not a license and does not grant any
// rights to the materials distributed herewith. Except as
// otherwise provided in a valid license issued to you by
// Xilinx, and to the maximum extent permitted by applicable
// law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND
// WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES
// AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
// BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-
// INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and
// (2) Xilinx shall not be liable (whether in contract or tort,
// including negligence, or under any other theory of
// liability) for any loss or damage of any kind or nature
// related to, arising under or in connection with these
// materials, including for any direct, or any indirect,
// special, incidental, or consequential loss or damage
// (including loss of data, profits, goodwill, or any type of
// loss or damage suffered as a result of any action brought
// by a third party) even if such damage or loss was
// reasonably foreseeable or Xilinx had been advised of the
// possibility of the same.
//
// CRITICAL APPLICATIONS
// Xilinx products are not designed or intended to be fail-
// safe, or for use in any application requiring fail-safe
// performance, such as life-support or safety devices or
// systems, Class III medical devices, nuclear facilities,
// applications related to the deployment of airbags, or any
// other applications that could lead to death, personal
// injury, or severe property or environmental damage
// (individually and collectively, "Critical
// Applications"). Customer assumes the sole risk and
// liability of any use of Xilinx products in Critical
// Applications, subject only to applicable laws and
// regulations governing limitations on product liability.
//
// THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS
// PART OF THIS FILE AT ALL TIMES.
//
//*****************************************************************************
// ____ ____
// / /\/ /
// /___/ \ / Vendor : Xilinx
// \ \ \/ Version : %version
// \ \ Application : MIG
// / / Filename : col_mach.v
// /___/ /\ Date Last Modified : $date$
// \ \ / \ Date Created : Tue Jun 30 2009
// \___\/\___\
//
//Device : 7-Series
//Design Name : DDR3 SDRAM
//Purpose :
//Reference :
//Revision History :
//*****************************************************************************
// The column machine manages the dq bus. Since there is a single DQ
// bus, and the column part of the DRAM is tightly coupled to this DQ
// bus, conceptually, the DQ bus and all of the column hardware in
// a multi rank DRAM array are managed as a single unit.
//
//
// The column machine does not "enforce" the column timing directly.
// It generates information and sends it to the bank machines. If the
// bank machines incorrectly make a request, the column machine will
// simply overwrite the existing request with the new request even
// if this would result in a timing or protocol violation.
//
// The column machine
// hosts the block that controls read and write data transfer
// to and from the dq bus.
//
// And if configured, there is provision for tracking the address
// of a command as it moves through the column pipeline. This
// address will be logged for detected ECC errors.
`timescale 1 ps / 1 ps
module mig_7series_v1_9_col_mach #
(
parameter TCQ = 100,
parameter BANK_WIDTH = 3,
parameter BURST_MODE = "8",
parameter COL_WIDTH = 12,
parameter CS_WIDTH = 4,
parameter DATA_BUF_ADDR_WIDTH = 8,
parameter DATA_BUF_OFFSET_WIDTH = 1,
parameter DELAY_WR_DATA_CNTRL = 0,
parameter DQS_WIDTH = 8,
parameter DRAM_TYPE = "DDR3",
parameter EARLY_WR_DATA_ADDR = "OFF",
parameter ECC = "OFF",
parameter MC_ERR_ADDR_WIDTH = 31,
parameter nCK_PER_CLK = 2,
parameter nPHY_WRLAT = 0,
parameter RANK_WIDTH = 2,
parameter ROW_WIDTH = 16
)
(/*AUTOARG*/
// Outputs
dq_busy_data, wr_data_offset, mc_wrdata_en, wr_data_en,
wr_data_addr, rd_rmw, ecc_err_addr, ecc_status_valid, wr_ecc_buf, rd_data_end,
rd_data_addr, rd_data_offset, rd_data_en, col_read_fifo_empty,
// Inputs
clk, rst, sent_col, col_size, col_wr_data_buf_addr,
phy_rddata_valid, col_periodic_rd, col_data_buf_addr, col_rmw,
col_rd_wr, col_ra, col_ba, col_row, col_a
);
input clk;
input rst;
input sent_col;
input col_rd_wr;
output reg dq_busy_data = 1'b0;
// The following generates a column command disable based mostly on the type
// of DRAM and the fabric to DRAM CK ratio.
generate
if ((nCK_PER_CLK == 1) && ((BURST_MODE == "8") || (DRAM_TYPE == "DDR3")))
begin : three_bumps
reg [1:0] granted_col_d_r;
wire [1:0] granted_col_d_ns = {sent_col, granted_col_d_r[1]};
always @(posedge clk) granted_col_d_r <= #TCQ granted_col_d_ns;
always @(/*AS*/granted_col_d_r or sent_col)
dq_busy_data = sent_col || |granted_col_d_r;
end
if (((nCK_PER_CLK == 2) && ((BURST_MODE == "8") || (DRAM_TYPE == "DDR3")))
|| ((nCK_PER_CLK == 1) && ((BURST_MODE == "4") || (DRAM_TYPE == "DDR2"))))
begin : one_bump
always @(/*AS*/sent_col) dq_busy_data = sent_col;
end
endgenerate
// This generates a data offset based on fabric clock to DRAM CK ratio and
// the size bit. Note that this is different that the dq_busy_data signal
// generated above.
reg [1:0] offset_r = 2'b0;
reg [1:0] offset_ns = 2'b0;
input col_size;
wire data_end;
generate
if(nCK_PER_CLK == 4) begin : data_valid_4_1
// For 4:1 mode all data is transfered in a single beat so the default
// values of 0 for offset_r/offset_ns suffice - just tie off data_end
assign data_end = 1'b1;
end
else begin
if(DATA_BUF_OFFSET_WIDTH == 2) begin : data_valid_1_1
always @(col_size or offset_r or rst or sent_col) begin
if (rst) offset_ns = 2'b0;
else begin
offset_ns = offset_r;
if (sent_col) offset_ns = 2'b1;
else if (|offset_r && (offset_r != {col_size, 1'b1}))
offset_ns = offset_r + 2'b1;
else offset_ns = 2'b0;
end
end
always @(posedge clk) offset_r <= #TCQ offset_ns;
assign data_end = col_size ? (offset_r == 2'b11) : offset_r[0];
end
else begin : data_valid_2_1
always @(col_size or rst or sent_col)
offset_ns[0] = rst ? 1'b0 : sent_col && col_size;
always @(posedge clk) offset_r[0] <= #TCQ offset_ns[0];
assign data_end = col_size ? offset_r[0] : 1'b1;
end
end
endgenerate
reg [DATA_BUF_OFFSET_WIDTH-1:0] offset_r1 = {DATA_BUF_OFFSET_WIDTH{1'b0}};
reg [DATA_BUF_OFFSET_WIDTH-1:0] offset_r2 = {DATA_BUF_OFFSET_WIDTH{1'b0}};
reg col_rd_wr_r1;
reg col_rd_wr_r2;
generate
if ((nPHY_WRLAT >= 1) || (DELAY_WR_DATA_CNTRL == 1)) begin : offset_pipe_0
always @(posedge clk) offset_r1 <=
#TCQ offset_r[DATA_BUF_OFFSET_WIDTH-1:0];
always @(posedge clk) col_rd_wr_r1 <= #TCQ col_rd_wr;
end
if(nPHY_WRLAT == 2) begin : offset_pipe_1
always @(posedge clk) offset_r2 <=
#TCQ offset_r1[DATA_BUF_OFFSET_WIDTH-1:0];
always @(posedge clk) col_rd_wr_r2 <= #TCQ col_rd_wr_r1;
end
endgenerate
output wire [DATA_BUF_OFFSET_WIDTH-1:0] wr_data_offset;
assign wr_data_offset = (DELAY_WR_DATA_CNTRL == 1)
? offset_r1[DATA_BUF_OFFSET_WIDTH-1:0]
: (EARLY_WR_DATA_ADDR == "OFF")
? offset_r[DATA_BUF_OFFSET_WIDTH-1:0]
: offset_ns[DATA_BUF_OFFSET_WIDTH-1:0];
reg sent_col_r1;
reg sent_col_r2;
always @(posedge clk) sent_col_r1 <= #TCQ sent_col;
always @(posedge clk) sent_col_r2 <= #TCQ sent_col_r1;
wire wrdata_en = (nPHY_WRLAT == 0) ?
(sent_col || |offset_r) & ~col_rd_wr :
(nPHY_WRLAT == 1) ?
(sent_col_r1 || |offset_r1) & ~col_rd_wr_r1 :
//(nPHY_WRLAT >= 2) ?
(sent_col_r2 || |offset_r2) & ~col_rd_wr_r2;
output wire mc_wrdata_en;
assign mc_wrdata_en = wrdata_en;
output wire wr_data_en;
assign wr_data_en = (DELAY_WR_DATA_CNTRL == 1)
? ((sent_col_r1 || |offset_r1) && ~col_rd_wr_r1)
: ((sent_col || |offset_r) && ~col_rd_wr);
input [DATA_BUF_ADDR_WIDTH-1:0] col_wr_data_buf_addr;
output wire [DATA_BUF_ADDR_WIDTH-1:0] wr_data_addr;
generate
if (DELAY_WR_DATA_CNTRL == 1) begin : delay_wr_data_cntrl_eq_1
reg [DATA_BUF_ADDR_WIDTH-1:0] col_wr_data_buf_addr_r;
always @(posedge clk) col_wr_data_buf_addr_r <=
#TCQ col_wr_data_buf_addr;
assign wr_data_addr = col_wr_data_buf_addr_r;
end
else begin : delay_wr_data_cntrl_ne_1
assign wr_data_addr = col_wr_data_buf_addr;
end
endgenerate
// CAS-RD to mc_rddata_en
wire read_data_valid = (sent_col || |offset_r) && col_rd_wr;
function integer clogb2 (input integer size); // ceiling logb2
begin
size = size - 1;
for (clogb2=1; size>1; clogb2=clogb2+1)
size = size >> 1;
end
endfunction // clogb2
// Implement FIFO that records reads as they are sent to the DRAM.
// When phy_rddata_valid is returned some unknown time later, the
// FIFO output is used to control how the data is interpreted.
input phy_rddata_valid;
output wire rd_rmw;
output reg [MC_ERR_ADDR_WIDTH-1:0] ecc_err_addr;
output reg ecc_status_valid;
output reg wr_ecc_buf;
output reg rd_data_end;
output reg [DATA_BUF_ADDR_WIDTH-1:0] rd_data_addr;
output reg [DATA_BUF_OFFSET_WIDTH-1:0] rd_data_offset;
(* keep = "true", max_fanout = 10 *) output reg rd_data_en /* synthesis syn_maxfan = 10 */;
output col_read_fifo_empty;
input col_periodic_rd;
input [DATA_BUF_ADDR_WIDTH-1:0] col_data_buf_addr;
input col_rmw;
input [RANK_WIDTH-1:0] col_ra;
input [BANK_WIDTH-1:0] col_ba;
input [ROW_WIDTH-1:0] col_row;
input [ROW_WIDTH-1:0] col_a;
// Real column address (skip A10/AP and A12/BC#). The maximum width is 12;
// the width will be tailored for the target DRAM downstream.
wire [11:0] col_a_full;
// Minimum row width is 12; take remaining 11 bits after omitting A10/AP
assign col_a_full[10:0] = {col_a[11], col_a[9:0]};
// Get the 12th bit when row address width accommodates it; omit A12/BC#
generate
if (ROW_WIDTH >= 14) begin : COL_A_FULL_11_1
assign col_a_full[11] = col_a[13];
end else begin : COL_A_FULL_11_0
assign col_a_full[11] = 0;
end
endgenerate
// Extract only the width of the target DRAM
wire [COL_WIDTH-1:0] col_a_extracted = col_a_full[COL_WIDTH-1:0];
localparam MC_ERR_LINE_WIDTH = MC_ERR_ADDR_WIDTH-DATA_BUF_OFFSET_WIDTH;
localparam FIFO_WIDTH = 1 /*data_end*/ +
1 /*periodic_rd*/ +
DATA_BUF_ADDR_WIDTH +
DATA_BUF_OFFSET_WIDTH +
((ECC == "OFF") ? 0 : 1+MC_ERR_LINE_WIDTH);
localparam FULL_RAM_CNT = (FIFO_WIDTH/6);
localparam REMAINDER = FIFO_WIDTH % 6;
localparam RAM_CNT = FULL_RAM_CNT + ((REMAINDER == 0 ) ? 0 : 1);
localparam RAM_WIDTH = (RAM_CNT*6);
generate
begin : read_fifo
wire [MC_ERR_LINE_WIDTH:0] ecc_line;
if (CS_WIDTH == 1)
assign ecc_line = {col_rmw, col_ba, col_row, col_a_extracted};
else
assign ecc_line = {col_rmw,
col_ra,
col_ba,
col_row,
col_a_extracted};
wire [FIFO_WIDTH-1:0] real_fifo_data;
if (ECC == "OFF")
assign real_fifo_data = {data_end,
col_periodic_rd,
col_data_buf_addr,
offset_r[DATA_BUF_OFFSET_WIDTH-1:0]};
else
assign real_fifo_data = {data_end,
col_periodic_rd,
col_data_buf_addr,
offset_r[DATA_BUF_OFFSET_WIDTH-1:0],
ecc_line};
wire [RAM_WIDTH-1:0] fifo_in_data;
if (REMAINDER == 0)
assign fifo_in_data = real_fifo_data;
else
assign fifo_in_data = {{6-REMAINDER{1'b0}}, real_fifo_data};
wire [RAM_WIDTH-1:0] fifo_out_data_ns;
reg [4:0] head_r;
wire [4:0] head_ns = rst ? 5'b0 : read_data_valid
? (head_r + 5'b1)
: head_r;
always @(posedge clk) head_r <= #TCQ head_ns;
reg [4:0] tail_r;
wire [4:0] tail_ns = rst ? 5'b0 : phy_rddata_valid
? (tail_r + 5'b1)
: tail_r;
always @(posedge clk) tail_r <= #TCQ tail_ns;
assign col_read_fifo_empty = head_r == tail_r ? 1'b1 : 1'b0;
genvar i;
for (i=0; i<RAM_CNT; i=i+1) begin : fifo_ram
RAM32M
#(.INIT_A(64'h0000000000000000),
.INIT_B(64'h0000000000000000),
.INIT_C(64'h0000000000000000),
.INIT_D(64'h0000000000000000)
) RAM32M0 (
.DOA(fifo_out_data_ns[((i*6)+4)+:2]),
.DOB(fifo_out_data_ns[((i*6)+2)+:2]),
.DOC(fifo_out_data_ns[((i*6)+0)+:2]),
.DOD(),
.DIA(fifo_in_data[((i*6)+4)+:2]),
.DIB(fifo_in_data[((i*6)+2)+:2]),
.DIC(fifo_in_data[((i*6)+0)+:2]),
.DID(2'b0),
.ADDRA(tail_ns),
.ADDRB(tail_ns),
.ADDRC(tail_ns),
.ADDRD(head_r),
.WE(1'b1),
.WCLK(clk)
);
end // block: fifo_ram
reg [RAM_WIDTH-1:0] fifo_out_data_r;
always @(posedge clk) fifo_out_data_r <= #TCQ fifo_out_data_ns;
// When ECC is ON, most of the FIFO output is delayed
// by one state.
if (ECC == "OFF") begin
reg periodic_rd;
always @(/*AS*/phy_rddata_valid or fifo_out_data_r) begin
{rd_data_end,
periodic_rd,
rd_data_addr,
rd_data_offset} = fifo_out_data_r[FIFO_WIDTH-1:0];
ecc_err_addr = {MC_ERR_ADDR_WIDTH{1'b0}};
rd_data_en = phy_rddata_valid && ~periodic_rd;
ecc_status_valid = 1'b0;
wr_ecc_buf = 1'b0;
end
assign rd_rmw = 1'b0;
end
else begin
wire rd_data_end_ns;
wire periodic_rd;
wire [DATA_BUF_ADDR_WIDTH-1:0] rd_data_addr_ns;
wire [DATA_BUF_OFFSET_WIDTH-1:0] rd_data_offset_ns;
wire [MC_ERR_ADDR_WIDTH-1:0] ecc_err_addr_ns;
assign {rd_data_end_ns,
periodic_rd,
rd_data_addr_ns,
rd_data_offset_ns,
rd_rmw,
ecc_err_addr_ns[DATA_BUF_OFFSET_WIDTH+:MC_ERR_LINE_WIDTH]} =
{fifo_out_data_r[FIFO_WIDTH-1:0]};
assign ecc_err_addr_ns[0+:DATA_BUF_OFFSET_WIDTH] = rd_data_offset_ns;
always @(posedge clk) rd_data_end <= #TCQ rd_data_end_ns;
always @(posedge clk) rd_data_addr <= #TCQ rd_data_addr_ns;
always @(posedge clk) rd_data_offset <= #TCQ rd_data_offset_ns;
always @(posedge clk) ecc_err_addr <= #TCQ ecc_err_addr_ns;
wire rd_data_en_ns = phy_rddata_valid && ~(periodic_rd || rd_rmw);
always @(posedge clk) rd_data_en <= rd_data_en_ns;
wire ecc_status_valid_ns = phy_rddata_valid && ~periodic_rd;
always @(posedge clk) ecc_status_valid <= #TCQ ecc_status_valid_ns;
wire wr_ecc_buf_ns = phy_rddata_valid && ~periodic_rd && rd_rmw;
always @(posedge clk) wr_ecc_buf <= #TCQ wr_ecc_buf_ns;
end
end
endgenerate
endmodule
|
//*****************************************************************************
// (c) Copyright 2009 - 2013 Xilinx, Inc. All rights reserved.
//
// This file contains confidential and proprietary information
// of Xilinx, Inc. and is protected under U.S. and
// international copyright and other intellectual property
// laws.
//
// DISCLAIMER
// This disclaimer is not a license and does not grant any
// rights to the materials distributed herewith. Except as
// otherwise provided in a valid license issued to you by
// Xilinx, and to the maximum extent permitted by applicable
// law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND
// WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES
// AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
// BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-
// INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and
// (2) Xilinx shall not be liable (whether in contract or tort,
// including negligence, or under any other theory of
// liability) for any loss or damage of any kind or nature
// related to, arising under or in connection with these
// materials, including for any direct, or any indirect,
// special, incidental, or consequential loss or damage
// (including loss of data, profits, goodwill, or any type of
// loss or damage suffered as a result of any action brought
// by a third party) even if such damage or loss was
// reasonably foreseeable or Xilinx had been advised of the
// possibility of the same.
//
// CRITICAL APPLICATIONS
// Xilinx products are not designed or intended to be fail-
// safe, or for use in any application requiring fail-safe
// performance, such as life-support or safety devices or
// systems, Class III medical devices, nuclear facilities,
// applications related to the deployment of airbags, or any
// other applications that could lead to death, personal
// injury, or severe property or environmental damage
// (individually and collectively, "Critical
// Applications"). Customer assumes the sole risk and
// liability of any use of Xilinx products in Critical
// Applications, subject only to applicable laws and
// regulations governing limitations on product liability.
//
// THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS
// PART OF THIS FILE AT ALL TIMES.
//
//*****************************************************************************
// ____ ____
// / /\/ /
// /___/ \ / Vendor: Xilinx
// \ \ \/ Version:
// \ \ Application: MIG
// / / Filename: ddr_phy_prbs_rdlvl.v
// /___/ /\ Date Last Modified: $Date: 2011/06/24 14:49:00 $
// \ \ / \ Date Created:
// \___\/\___\
//
//Device: 7 Series
//Design Name: DDR3 SDRAM
//Purpose:
// PRBS Read leveling calibration logic
// NOTES:
// 1. Window detection with PRBS pattern.
//Reference:
//Revision History:
//*****************************************************************************
/******************************************************************************
**$Id: ddr_phy_prbs_rdlvl.v,v 1.2 2011/06/24 14:49:00 mgeorge Exp $
**$Date: 2011/06/24 14:49:00 $
**$Author: mgeorge $
**$Revision: 1.2 $
**$Source: /devl/xcs/repo/env/Databases/ip/src2/O/mig_7series_v1_3/data/dlib/7series/ddr3_sdram/verilog/rtl/phy/ddr_phy_prbs_rdlvl.v,v $
******************************************************************************/
`timescale 1ps/1ps
module mig_7series_v1_9_ddr_phy_prbs_rdlvl #
(
parameter TCQ = 100, // clk->out delay (sim only)
parameter nCK_PER_CLK = 2, // # of memory clocks per CLK
parameter DQ_WIDTH = 64, // # of DQ (data)
parameter DQS_CNT_WIDTH = 3, // = ceil(log2(DQS_WIDTH))
parameter DQS_WIDTH = 8, // # of DQS (strobe)
parameter DRAM_WIDTH = 8, // # of DQ per DQS
parameter RANKS = 1, // # of DRAM ranks
parameter SIM_CAL_OPTION = "NONE", // Skip various calibration steps
parameter PRBS_WIDTH = 8 // PRBS generator output width
)
(
input clk,
input rst,
// Calibration status, control signals
input prbs_rdlvl_start,
output reg prbs_rdlvl_done,
output reg prbs_last_byte_done,
output reg prbs_rdlvl_prech_req,
input prech_done,
input phy_if_empty,
// Captured data in fabric clock domain
input [2*nCK_PER_CLK*DQ_WIDTH-1:0] rd_data,
//Expected data from PRBS generator
input [2*nCK_PER_CLK*PRBS_WIDTH-1:0] compare_data,
// Decrement initial Phaser_IN Fine tap delay
input [5:0] pi_counter_read_val,
// Stage 1 calibration outputs
output reg pi_en_stg2_f,
output reg pi_stg2_f_incdec,
output [255:0] dbg_prbs_rdlvl,
output [DQS_CNT_WIDTH:0] pi_stg2_prbs_rdlvl_cnt
);
localparam [5:0] PRBS_IDLE = 6'h00;
localparam [5:0] PRBS_NEW_DQS_WAIT = 6'h01;
localparam [5:0] PRBS_PAT_COMPARE = 6'h02;
localparam [5:0] PRBS_DEC_DQS = 6'h03;
localparam [5:0] PRBS_DEC_DQS_WAIT = 6'h04;
localparam [5:0] PRBS_INC_DQS = 6'h05;
localparam [5:0] PRBS_INC_DQS_WAIT = 6'h06;
localparam [5:0] PRBS_CALC_TAPS = 6'h07;
localparam [5:0] PRBS_TAP_CHECK = 6'h08;
localparam [5:0] PRBS_NEXT_DQS = 6'h09;
localparam [5:0] PRBS_NEW_DQS_PREWAIT = 6'h0A;
localparam [5:0] PRBS_DONE = 6'h0B;
localparam [11:0] NUM_SAMPLES_CNT = (SIM_CAL_OPTION == "NONE") ? 12'hFFF : 12'h001;
localparam [11:0] NUM_SAMPLES_CNT1 = (SIM_CAL_OPTION == "NONE") ? 12'hFFF : 12'h001;
localparam [11:0] NUM_SAMPLES_CNT2 = (SIM_CAL_OPTION == "NONE") ? 12'hFFF : 12'h001;
wire [DQS_CNT_WIDTH+2:0]prbs_dqs_cnt_timing;
reg [DQS_CNT_WIDTH+2:0] prbs_dqs_cnt_timing_r;
reg [DQS_CNT_WIDTH:0] prbs_dqs_cnt_r;
reg prbs_prech_req_r;
reg [5:0] prbs_state_r;
reg [5:0] prbs_state_r1;
reg wait_state_cnt_en_r;
reg [3:0] wait_state_cnt_r;
reg cnt_wait_state;
reg found_edge_r;
reg prbs_found_1st_edge_r;
reg prbs_found_2nd_edge_r;
reg [5:0] prbs_1st_edge_taps_r;
reg found_stable_eye_r;
reg [5:0] prbs_dqs_tap_cnt_r;
reg [5:0] prbs_dec_tap_calc_plus_3;
reg [5:0] prbs_dec_tap_calc_minus_3;
reg prbs_dqs_tap_limit_r;
reg [5:0] prbs_inc_tap_cnt;
reg [5:0] prbs_dec_tap_cnt;
reg [DRAM_WIDTH-1:0] mux_rd_fall0_r1;
reg [DRAM_WIDTH-1:0] mux_rd_fall1_r1;
reg [DRAM_WIDTH-1:0] mux_rd_rise0_r1;
reg [DRAM_WIDTH-1:0] mux_rd_rise1_r1;
reg [DRAM_WIDTH-1:0] mux_rd_fall2_r1;
reg [DRAM_WIDTH-1:0] mux_rd_fall3_r1;
reg [DRAM_WIDTH-1:0] mux_rd_rise2_r1;
reg [DRAM_WIDTH-1:0] mux_rd_rise3_r1;
reg [DRAM_WIDTH-1:0] mux_rd_fall0_r2;
reg [DRAM_WIDTH-1:0] mux_rd_fall1_r2;
reg [DRAM_WIDTH-1:0] mux_rd_rise0_r2;
reg [DRAM_WIDTH-1:0] mux_rd_rise1_r2;
reg [DRAM_WIDTH-1:0] mux_rd_fall2_r2;
reg [DRAM_WIDTH-1:0] mux_rd_fall3_r2;
reg [DRAM_WIDTH-1:0] mux_rd_rise2_r2;
reg [DRAM_WIDTH-1:0] mux_rd_rise3_r2;
reg mux_rd_valid_r;
reg rd_valid_r1;
reg rd_valid_r2;
reg rd_valid_r3;
reg new_cnt_dqs_r;
reg prbs_tap_en_r;
reg prbs_tap_inc_r;
reg pi_en_stg2_f_timing;
reg pi_stg2_f_incdec_timing;
wire [DQ_WIDTH-1:0] rd_data_rise0;
wire [DQ_WIDTH-1:0] rd_data_fall0;
wire [DQ_WIDTH-1:0] rd_data_rise1;
wire [DQ_WIDTH-1:0] rd_data_fall1;
wire [DQ_WIDTH-1:0] rd_data_rise2;
wire [DQ_WIDTH-1:0] rd_data_fall2;
wire [DQ_WIDTH-1:0] rd_data_rise3;
wire [DQ_WIDTH-1:0] rd_data_fall3;
wire [PRBS_WIDTH-1:0] compare_data_r0;
wire [PRBS_WIDTH-1:0] compare_data_f0;
wire [PRBS_WIDTH-1:0] compare_data_r1;
wire [PRBS_WIDTH-1:0] compare_data_f1;
wire [PRBS_WIDTH-1:0] compare_data_r2;
wire [PRBS_WIDTH-1:0] compare_data_f2;
wire [PRBS_WIDTH-1:0] compare_data_r3;
wire [PRBS_WIDTH-1:0] compare_data_f3;
reg [DQS_CNT_WIDTH:0] rd_mux_sel_r;
reg [5:0] prbs_2nd_edge_taps_r;
reg [6*DQS_WIDTH*RANKS-1:0] prbs_final_dqs_tap_cnt_r;
reg [1:0] rnk_cnt_r;
reg [5:0] rdlvl_cpt_tap_cnt;
reg prbs_rdlvl_start_r;
reg compare_err;
reg compare_err_r0;
reg compare_err_f0;
reg compare_err_r1;
reg compare_err_f1;
reg compare_err_r2;
reg compare_err_f2;
reg compare_err_r3;
reg compare_err_f3;
reg samples_cnt1_en_r;
reg samples_cnt2_en_r;
reg [11:0] samples_cnt_r;
reg num_samples_done_r;
reg [DQS_WIDTH-1:0] prbs_tap_mod;
//**************************************************************************
// DQS count to hard PHY during write calibration using Phaser_OUT Stage2
// coarse delay
//**************************************************************************
// assign pi_stg2_prbs_rdlvl_cnt = prbs_dqs_cnt_r;
// assign dbg_prbs_rdlvl = {prbs_tap_mod, prbs_2nd_edge_taps_r, prbs_1st_edge_taps_r, rdlvl_cpt_tap_cnt, prbs_dqs_cnt_r,
// prbs_rdlvl_done, prbs_rdlvl_start, phy_if_empty, compare_err, prbs_found_2nd_edge_r, prbs_found_1st_edge_r, prbs_dqs_tap_cnt_r, pi_counter_read_val,
// mux_rd_fall3_r2, mux_rd_rise3_r2, mux_rd_fall2_r2, mux_rd_rise2_r2, mux_rd_fall1_r2, mux_rd_rise1_r2, mux_rd_fall0_r2, mux_rd_rise0_r2,
// compare_data_f3, compare_data_r3, compare_data_f2, compare_data_r2, compare_data_f1, compare_data_r1, compare_data_f0, compare_data_r0};
assign dbg_prbs_rdlvl[0+:8] = compare_data_r0;
assign dbg_prbs_rdlvl[8+:8] = compare_data_f0;
assign dbg_prbs_rdlvl[16+:8] = compare_data_r1;
assign dbg_prbs_rdlvl[24+:8] = compare_data_f1;
assign dbg_prbs_rdlvl[32+:8] = compare_data_r2;
assign dbg_prbs_rdlvl[40+:8] = compare_data_f2;
assign dbg_prbs_rdlvl[48+:8] = compare_data_r3;
assign dbg_prbs_rdlvl[56+:8] = compare_data_f3;
assign dbg_prbs_rdlvl[64+:8] = mux_rd_rise0_r2;
assign dbg_prbs_rdlvl[72+:8] = mux_rd_fall0_r2;
assign dbg_prbs_rdlvl[80+:8] = mux_rd_rise1_r2;
assign dbg_prbs_rdlvl[88+:8] = mux_rd_fall1_r2;
assign dbg_prbs_rdlvl[96+:8] = mux_rd_rise2_r2;
assign dbg_prbs_rdlvl[104+:8] = mux_rd_fall2_r2;
assign dbg_prbs_rdlvl[112+:8] = mux_rd_rise3_r2;
assign dbg_prbs_rdlvl[120+:8] = mux_rd_fall3_r2;
assign dbg_prbs_rdlvl[128+:6] = pi_counter_read_val;
assign dbg_prbs_rdlvl[134+:6] = prbs_dqs_tap_cnt_r;
assign dbg_prbs_rdlvl[140] = prbs_found_1st_edge_r;
assign dbg_prbs_rdlvl[141] = prbs_found_2nd_edge_r;
assign dbg_prbs_rdlvl[142] = compare_err;
assign dbg_prbs_rdlvl[143] = phy_if_empty;
assign dbg_prbs_rdlvl[144] = prbs_rdlvl_start;
assign dbg_prbs_rdlvl[145] = prbs_rdlvl_done;
assign dbg_prbs_rdlvl[146+:5] = prbs_dqs_cnt_r;
assign dbg_prbs_rdlvl[151+:6] = rdlvl_cpt_tap_cnt;
assign dbg_prbs_rdlvl[157+:6] = prbs_1st_edge_taps_r;
assign dbg_prbs_rdlvl[163+:6] = prbs_2nd_edge_taps_r;
assign dbg_prbs_rdlvl[169+:9] = prbs_tap_mod;
assign dbg_prbs_rdlvl[255:178]= 'b0;//reserved
//***************************************************************************
//***************************************************************************
// Data mux to route appropriate bit to calibration logic - i.e. calibration
// is done sequentially, one bit (or DQS group) at a time
//***************************************************************************
generate
if (nCK_PER_CLK == 4) begin: rd_data_div4_logic_clk
assign rd_data_rise0 = rd_data[DQ_WIDTH-1:0];
assign rd_data_fall0 = rd_data[2*DQ_WIDTH-1:DQ_WIDTH];
assign rd_data_rise1 = rd_data[3*DQ_WIDTH-1:2*DQ_WIDTH];
assign rd_data_fall1 = rd_data[4*DQ_WIDTH-1:3*DQ_WIDTH];
assign rd_data_rise2 = rd_data[5*DQ_WIDTH-1:4*DQ_WIDTH];
assign rd_data_fall2 = rd_data[6*DQ_WIDTH-1:5*DQ_WIDTH];
assign rd_data_rise3 = rd_data[7*DQ_WIDTH-1:6*DQ_WIDTH];
assign rd_data_fall3 = rd_data[8*DQ_WIDTH-1:7*DQ_WIDTH];
assign compare_data_r0 = compare_data[PRBS_WIDTH-1:0];
assign compare_data_f0 = compare_data[2*PRBS_WIDTH-1:PRBS_WIDTH];
assign compare_data_r1 = compare_data[3*PRBS_WIDTH-1:2*PRBS_WIDTH];
assign compare_data_f1 = compare_data[4*PRBS_WIDTH-1:3*PRBS_WIDTH];
assign compare_data_r2 = compare_data[5*PRBS_WIDTH-1:4*PRBS_WIDTH];
assign compare_data_f2 = compare_data[6*PRBS_WIDTH-1:5*PRBS_WIDTH];
assign compare_data_r3 = compare_data[7*PRBS_WIDTH-1:6*PRBS_WIDTH];
assign compare_data_f3 = compare_data[8*PRBS_WIDTH-1:7*PRBS_WIDTH];
end else begin: rd_data_div2_logic_clk
assign rd_data_rise0 = rd_data[DQ_WIDTH-1:0];
assign rd_data_fall0 = rd_data[2*DQ_WIDTH-1:DQ_WIDTH];
assign rd_data_rise1 = rd_data[3*DQ_WIDTH-1:2*DQ_WIDTH];
assign rd_data_fall1 = rd_data[4*DQ_WIDTH-1:3*DQ_WIDTH];
assign compare_data_r0 = compare_data[PRBS_WIDTH-1:0];
assign compare_data_f0 = compare_data[2*PRBS_WIDTH-1:PRBS_WIDTH];
assign compare_data_r1 = compare_data[3*PRBS_WIDTH-1:2*PRBS_WIDTH];
assign compare_data_f1 = compare_data[4*PRBS_WIDTH-1:3*PRBS_WIDTH];
end
endgenerate
always @(posedge clk) begin
rd_mux_sel_r <= #TCQ prbs_dqs_cnt_r;
end
// Register outputs for improved timing.
// NOTE: Will need to change when per-bit DQ deskew is supported.
// Currenly all bits in DQS group are checked in aggregate
generate
genvar mux_i;
for (mux_i = 0; mux_i < DRAM_WIDTH; mux_i = mux_i + 1) begin: gen_mux_rd
always @(posedge clk) begin
mux_rd_rise0_r1[mux_i] <= #TCQ rd_data_rise0[DRAM_WIDTH*rd_mux_sel_r + mux_i];
mux_rd_fall0_r1[mux_i] <= #TCQ rd_data_fall0[DRAM_WIDTH*rd_mux_sel_r + mux_i];
mux_rd_rise1_r1[mux_i] <= #TCQ rd_data_rise1[DRAM_WIDTH*rd_mux_sel_r + mux_i];
mux_rd_fall1_r1[mux_i] <= #TCQ rd_data_fall1[DRAM_WIDTH*rd_mux_sel_r + mux_i];
mux_rd_rise2_r1[mux_i] <= #TCQ rd_data_rise2[DRAM_WIDTH*rd_mux_sel_r + mux_i];
mux_rd_fall2_r1[mux_i] <= #TCQ rd_data_fall2[DRAM_WIDTH*rd_mux_sel_r + mux_i];
mux_rd_rise3_r1[mux_i] <= #TCQ rd_data_rise3[DRAM_WIDTH*rd_mux_sel_r + mux_i];
mux_rd_fall3_r1[mux_i] <= #TCQ rd_data_fall3[DRAM_WIDTH*rd_mux_sel_r + mux_i];
end
end
endgenerate
generate
genvar muxr2_i;
if (nCK_PER_CLK == 4) begin: gen_mux_div4
for (muxr2_i = 0; muxr2_i < DRAM_WIDTH; muxr2_i = muxr2_i + 1) begin: gen_rd_4
always @(posedge clk) begin
if (mux_rd_valid_r) begin
mux_rd_rise0_r2[muxr2_i] <= #TCQ mux_rd_rise0_r1[muxr2_i];
mux_rd_fall0_r2[muxr2_i] <= #TCQ mux_rd_fall0_r1[muxr2_i];
mux_rd_rise1_r2[muxr2_i] <= #TCQ mux_rd_rise1_r1[muxr2_i];
mux_rd_fall1_r2[muxr2_i] <= #TCQ mux_rd_fall1_r1[muxr2_i];
mux_rd_rise2_r2[muxr2_i] <= #TCQ mux_rd_rise2_r1[muxr2_i];
mux_rd_fall2_r2[muxr2_i] <= #TCQ mux_rd_fall2_r1[muxr2_i];
mux_rd_rise3_r2[muxr2_i] <= #TCQ mux_rd_rise3_r1[muxr2_i];
mux_rd_fall3_r2[muxr2_i] <= #TCQ mux_rd_fall3_r1[muxr2_i];
end
end
end
end else if (nCK_PER_CLK == 2) begin: gen_mux_div2
for (muxr2_i = 0; muxr2_i < DRAM_WIDTH; muxr2_i = muxr2_i + 1) begin: gen_rd_2
always @(posedge clk) begin
if (mux_rd_valid_r) begin
mux_rd_rise0_r2[muxr2_i] <= #TCQ mux_rd_rise0_r1[muxr2_i];
mux_rd_fall0_r2[muxr2_i] <= #TCQ mux_rd_fall0_r1[muxr2_i];
mux_rd_rise1_r2[muxr2_i] <= #TCQ mux_rd_rise1_r1[muxr2_i];
mux_rd_fall1_r2[muxr2_i] <= #TCQ mux_rd_fall1_r1[muxr2_i];
end
end
end
end
endgenerate
// Registered signal indicates when mux_rd_rise/fall_r is valid
always @(posedge clk) begin
mux_rd_valid_r <= #TCQ ~phy_if_empty && prbs_rdlvl_start;
rd_valid_r1 <= #TCQ mux_rd_valid_r;
rd_valid_r2 <= #TCQ rd_valid_r1;
end
// Counter counts # of samples compared
// Reset sample counter when not "sampling"
// Otherwise, count # of samples compared
// Same counter is shared for three samples checked
always @(posedge clk)
if (rst)
samples_cnt_r <= #TCQ 'b0;
else begin
if (!rd_valid_r1 ||
(prbs_state_r == PRBS_DEC_DQS_WAIT) ||
(prbs_state_r == PRBS_INC_DQS_WAIT) ||
(prbs_state_r == PRBS_DEC_DQS) ||
(prbs_state_r == PRBS_INC_DQS) ||
(samples_cnt_r == NUM_SAMPLES_CNT) ||
(samples_cnt_r == NUM_SAMPLES_CNT1))
samples_cnt_r <= #TCQ 'b0;
else if (rd_valid_r1 &&
(((samples_cnt_r < NUM_SAMPLES_CNT) && ~samples_cnt1_en_r) ||
((samples_cnt_r < NUM_SAMPLES_CNT1) && ~samples_cnt2_en_r) ||
((samples_cnt_r < NUM_SAMPLES_CNT2) && samples_cnt2_en_r)))
samples_cnt_r <= #TCQ samples_cnt_r + 1;
end
// Count #2 enable generation
// Assert when correct number of samples compared
always @(posedge clk)
if (rst)
samples_cnt1_en_r <= #TCQ 1'b0;
else begin
if ((prbs_state_r == PRBS_IDLE) ||
(prbs_state_r == PRBS_DEC_DQS) ||
(prbs_state_r == PRBS_INC_DQS) ||
(prbs_state_r == PRBS_NEW_DQS_PREWAIT))
samples_cnt1_en_r <= #TCQ 1'b0;
else if ((samples_cnt_r == NUM_SAMPLES_CNT) && rd_valid_r1)
samples_cnt1_en_r <= #TCQ 1'b1;
end
// Counter #3 enable generation
// Assert when correct number of samples compared
always @(posedge clk)
if (rst)
samples_cnt2_en_r <= #TCQ 1'b0;
else begin
if ((prbs_state_r == PRBS_IDLE) ||
(prbs_state_r == PRBS_DEC_DQS) ||
(prbs_state_r == PRBS_INC_DQS) ||
(prbs_state_r == PRBS_NEW_DQS_PREWAIT))
samples_cnt2_en_r <= #TCQ 1'b0;
else if ((samples_cnt_r == NUM_SAMPLES_CNT1) && rd_valid_r1 && samples_cnt1_en_r)
samples_cnt2_en_r <= #TCQ 1'b1;
end
// Assert when all the three sample counts are done
always @(posedge clk)
if (rst)
num_samples_done_r <= #TCQ 1'b0;
else begin
if (!rd_valid_r1 ||
(prbs_state_r == PRBS_DEC_DQS) ||
(prbs_state_r == PRBS_INC_DQS))
num_samples_done_r <= #TCQ 'b0;
else begin
if ((samples_cnt_r == NUM_SAMPLES_CNT2-1) && samples_cnt2_en_r)
num_samples_done_r <= #TCQ 1'b1;
end
end
//***************************************************************************
// Compare Read Data for the byte being Leveled with Expected data from PRBS
// generator. Resulting compare_err signal used to determine read data valid
// edge.
//***************************************************************************
generate
if (nCK_PER_CLK == 4) begin: cmp_err_4to1
always @ (posedge clk) begin
if (rst || new_cnt_dqs_r) begin
compare_err <= #TCQ 1'b0;
compare_err_r0 <= #TCQ 1'b0;
compare_err_f0 <= #TCQ 1'b0;
compare_err_r1 <= #TCQ 1'b0;
compare_err_f1 <= #TCQ 1'b0;
compare_err_r2 <= #TCQ 1'b0;
compare_err_f2 <= #TCQ 1'b0;
compare_err_r3 <= #TCQ 1'b0;
compare_err_f3 <= #TCQ 1'b0;
end else if (rd_valid_r1) begin
compare_err_r0 <= #TCQ (mux_rd_rise0_r2 != compare_data_r0);
compare_err_f0 <= #TCQ (mux_rd_fall0_r2 != compare_data_f0);
compare_err_r1 <= #TCQ (mux_rd_rise1_r2 != compare_data_r1);
compare_err_f1 <= #TCQ (mux_rd_fall1_r2 != compare_data_f1);
compare_err_r2 <= #TCQ (mux_rd_rise2_r2 != compare_data_r2);
compare_err_f2 <= #TCQ (mux_rd_fall2_r2 != compare_data_f2);
compare_err_r3 <= #TCQ (mux_rd_rise3_r2 != compare_data_r3);
compare_err_f3 <= #TCQ (mux_rd_fall3_r2 != compare_data_f3);
compare_err <= #TCQ (compare_err_r0 | compare_err_f0 |
compare_err_r1 | compare_err_f1 |
compare_err_r2 | compare_err_f2 |
compare_err_r3 | compare_err_f3);
end
end
end else begin: cmp_err_2to1
always @ (posedge clk) begin
if (rst || new_cnt_dqs_r) begin
compare_err <= #TCQ 1'b0;
compare_err_r0 <= #TCQ 1'b0;
compare_err_f0 <= #TCQ 1'b0;
compare_err_r1 <= #TCQ 1'b0;
compare_err_f1 <= #TCQ 1'b0;
end else if (rd_valid_r1) begin
compare_err_r0 <= #TCQ (mux_rd_rise0_r2 != compare_data_r0);
compare_err_f0 <= #TCQ (mux_rd_fall0_r2 != compare_data_f0);
compare_err_r1 <= #TCQ (mux_rd_rise1_r2 != compare_data_r1);
compare_err_f1 <= #TCQ (mux_rd_fall1_r2 != compare_data_f1);
compare_err <= #TCQ (compare_err_r0 | compare_err_f0 |
compare_err_r1 | compare_err_f1);
end
end
end
endgenerate
//***************************************************************************
// Decrement initial Phaser_IN fine delay value before proceeding with
// read calibration
//***************************************************************************
//***************************************************************************
// Demultiplexor to control Phaser_IN delay values
//***************************************************************************
// Read DQS
always @(posedge clk) begin
if (rst) begin
pi_en_stg2_f_timing <= #TCQ 'b0;
pi_stg2_f_incdec_timing <= #TCQ 'b0;
end else if (prbs_tap_en_r) begin
// Change only specified DQS
pi_en_stg2_f_timing <= #TCQ 1'b1;
pi_stg2_f_incdec_timing <= #TCQ prbs_tap_inc_r;
end else begin
pi_en_stg2_f_timing <= #TCQ 'b0;
pi_stg2_f_incdec_timing <= #TCQ 'b0;
end
end
// registered for timing
always @(posedge clk) begin
pi_en_stg2_f <= #TCQ pi_en_stg2_f_timing;
pi_stg2_f_incdec <= #TCQ pi_stg2_f_incdec_timing;
end
//***************************************************************************
// generate request to PHY_INIT logic to issue precharged. Required when
// calibration can take a long time (during which there are only constant
// reads present on this bus). In this case need to issue perioidic
// precharges to avoid tRAS violation. This signal must meet the following
// requirements: (1) only transition from 0->1 when prech is first needed,
// (2) stay at 1 and only transition 1->0 when RDLVL_PRECH_DONE asserted
//***************************************************************************
always @(posedge clk)
if (rst)
prbs_rdlvl_prech_req <= #TCQ 1'b0;
else
prbs_rdlvl_prech_req <= #TCQ prbs_prech_req_r;
//*****************************************************************
// keep track of edge tap counts found, and current capture clock
// tap count
//*****************************************************************
always @(posedge clk)
if (rst) begin
prbs_dqs_tap_cnt_r <= #TCQ 'b0;
rdlvl_cpt_tap_cnt <= #TCQ 'b0;
end else if (new_cnt_dqs_r) begin
prbs_dqs_tap_cnt_r <= #TCQ pi_counter_read_val;
rdlvl_cpt_tap_cnt <= #TCQ pi_counter_read_val;
end else if (prbs_tap_en_r) begin
if (prbs_tap_inc_r)
prbs_dqs_tap_cnt_r <= #TCQ prbs_dqs_tap_cnt_r + 1;
else if (prbs_dqs_tap_cnt_r != 'd0)
prbs_dqs_tap_cnt_r <= #TCQ prbs_dqs_tap_cnt_r - 1;
end
always @(posedge clk)
if (rst) begin
prbs_dec_tap_calc_plus_3 <= #TCQ 'b0;
prbs_dec_tap_calc_minus_3 <= #TCQ 'b0;
end else if (new_cnt_dqs_r) begin
prbs_dec_tap_calc_plus_3 <= #TCQ 'b000011;
prbs_dec_tap_calc_minus_3 <= #TCQ 'b111100;
end else begin
prbs_dec_tap_calc_plus_3 <= #TCQ (prbs_dqs_tap_cnt_r - rdlvl_cpt_tap_cnt + 3);
prbs_dec_tap_calc_minus_3 <= #TCQ (prbs_dqs_tap_cnt_r - rdlvl_cpt_tap_cnt - 3);
end
always @(posedge clk)
if (rst || new_cnt_dqs_r)
prbs_dqs_tap_limit_r <= #TCQ 1'b0;
else if (prbs_dqs_tap_cnt_r == 6'd63)
prbs_dqs_tap_limit_r <= #TCQ 1'b1;
// Temp wire for timing.
// The following in the always block below causes timing issues
// due to DSP block inference
// 6*prbs_dqs_cnt_r.
// replacing this with two left shifts + one left shift to avoid
// DSP multiplier.
assign prbs_dqs_cnt_timing = {2'd0, prbs_dqs_cnt_r};
always @(posedge clk)
prbs_dqs_cnt_timing_r <= #TCQ prbs_dqs_cnt_timing;
// Storing DQS tap values at the end of each DQS read leveling
always @(posedge clk) begin
if (rst) begin
prbs_final_dqs_tap_cnt_r <= #TCQ 'b0;
end else if ((prbs_state_r == PRBS_NEXT_DQS) && (prbs_state_r1 != PRBS_NEXT_DQS)) begin
prbs_final_dqs_tap_cnt_r[(((prbs_dqs_cnt_timing_r <<2) + (prbs_dqs_cnt_timing_r <<1))
+(rnk_cnt_r*DQS_WIDTH*6))+:6]
<= #TCQ prbs_dqs_tap_cnt_r;
end
end
//*****************************************************************
always @(posedge clk) begin
prbs_state_r1 <= #TCQ prbs_state_r;
prbs_rdlvl_start_r <= #TCQ prbs_rdlvl_start;
end
// Wait counter for wait states
always @(posedge clk)
if ((prbs_state_r == PRBS_NEW_DQS_WAIT) ||
(prbs_state_r == PRBS_INC_DQS_WAIT) ||
(prbs_state_r == PRBS_DEC_DQS_WAIT) ||
(prbs_state_r == PRBS_NEW_DQS_PREWAIT))
wait_state_cnt_en_r <= #TCQ 1'b1;
else
wait_state_cnt_en_r <= #TCQ 1'b0;
always @(posedge clk)
if (!wait_state_cnt_en_r) begin
wait_state_cnt_r <= #TCQ 'b0;
cnt_wait_state <= #TCQ 1'b0;
end else begin
if (wait_state_cnt_r < 'd15) begin
wait_state_cnt_r <= #TCQ wait_state_cnt_r + 1;
cnt_wait_state <= #TCQ 1'b0;
end else begin
// Need to reset to 0 to handle the case when there are two
// different WAIT states back-to-back
wait_state_cnt_r <= #TCQ 'b0;
cnt_wait_state <= #TCQ 1'b1;
end
end
//*****************************************************************
// PRBS Read Level State Machine
//*****************************************************************
always @(posedge clk)
if (rst) begin
prbs_dqs_cnt_r <= #TCQ 'b0;
prbs_tap_en_r <= #TCQ 1'b0;
prbs_tap_inc_r <= #TCQ 1'b0;
prbs_prech_req_r <= #TCQ 1'b0;
prbs_state_r <= #TCQ PRBS_IDLE;
prbs_found_1st_edge_r <= #TCQ 1'b0;
prbs_found_2nd_edge_r <= #TCQ 1'b0;
prbs_1st_edge_taps_r <= #TCQ 6'bxxxxxx;
prbs_inc_tap_cnt <= #TCQ 'b0;
prbs_dec_tap_cnt <= #TCQ 'b0;
new_cnt_dqs_r <= #TCQ 1'b0;
if (SIM_CAL_OPTION == "FAST_CAL")
prbs_rdlvl_done <= #TCQ 1'b1;
else
prbs_rdlvl_done <= #TCQ 1'b0;
prbs_2nd_edge_taps_r <= #TCQ 6'bxxxxxx;
prbs_last_byte_done <= #TCQ 1'b0;
rnk_cnt_r <= #TCQ 2'b00;
prbs_tap_mod <= #TCQ 'd0;
end else begin
case (prbs_state_r)
PRBS_IDLE: begin
prbs_last_byte_done <= #TCQ 1'b0;
prbs_prech_req_r <= #TCQ 1'b0;
if (prbs_rdlvl_start && ~prbs_rdlvl_start_r) begin
if (SIM_CAL_OPTION == "SKIP_CAL")
prbs_state_r <= #TCQ PRBS_DONE;
else begin
new_cnt_dqs_r <= #TCQ 1'b1;
prbs_state_r <= #TCQ PRBS_NEW_DQS_WAIT;
end
end
end
// Wait for the new DQS group to change
// also gives time for the read data IN_FIFO to
// output the updated data for the new DQS group
PRBS_NEW_DQS_WAIT: begin
prbs_last_byte_done <= #TCQ 1'b0;
prbs_prech_req_r <= #TCQ 1'b0;
if (cnt_wait_state) begin
new_cnt_dqs_r <= #TCQ 1'b0;
prbs_state_r <= #TCQ PRBS_PAT_COMPARE;
end
end
// Check for presence of data eye edge. During this state, we
// sample the read data multiple times, and look for changes
// in the read data, specifically:
// 1. A change in the read data compared with the value of
// read data from the previous delay tap. This indicates
// that the most recent tap delay increment has moved us
// into either a new window, or moved/kept us in the
// transition/jitter region between windows. Note that this
// condition only needs to be checked for once, and for
// logistical purposes, we check this soon after entering
// this state (see comment in PRBS_PAT_COMPARE below for
// why this is done)
// 2. A change in the read data while we are in this state
// (i.e. in the absence of a tap delay increment). This
// indicates that we're close enough to a window edge that
// jitter will cause the read data to change even in the
// absence of a tap delay change
PRBS_PAT_COMPARE: begin
// Continue to sample read data and look for edges until the
// appropriate time interval (shorter for simulation-only,
// much, much longer for actual h/w) has elapsed
if (num_samples_done_r || compare_err) begin
if (prbs_dqs_tap_limit_r)
// Only one edge detected and ran out of taps since only one
// bit time worth of taps available for window detection. This
// can happen if at tap 0 DQS is in previous window which results
// in only left edge being detected. Or at tap 0 DQS is in the
// current window resulting in only right edge being detected.
// Depending on the frequency this case can also happen if at
// tap 0 DQS is in the left noise region resulting in only left
// edge being detected.
prbs_state_r <= #TCQ PRBS_CALC_TAPS;
else if (compare_err || (prbs_dqs_tap_cnt_r == 'd0)) begin
// Sticky bit - asserted after we encounter an edge, although
// the current edge may not be considered the "first edge" this
// just means we found at least one edge
prbs_found_1st_edge_r <= #TCQ 1'b1;
// Both edges of data valid window found:
// If we've found a second edge after a region of stability
// then we must have just passed the second ("right" edge of
// the window. Record this second_edge_taps = current tap-1,
// because we're one past the actual second edge tap, where
// the edge taps represent the extremes of the data valid
// window (i.e. smallest & largest taps where data still valid
if (prbs_found_1st_edge_r) begin
prbs_found_2nd_edge_r <= #TCQ 1'b1;
prbs_2nd_edge_taps_r <= #TCQ prbs_dqs_tap_cnt_r - 1;
prbs_state_r <= #TCQ PRBS_CALC_TAPS;
end else begin
// Otherwise, an edge was found (just not the "second" edge)
// Assuming DQS is in the correct window at tap 0 of Phaser IN
// fine tap. The first edge found is the right edge of the valid
// window and is the beginning of the jitter region hence done!
if (compare_err)
prbs_1st_edge_taps_r <= #TCQ prbs_dqs_tap_cnt_r + 1;
else
prbs_1st_edge_taps_r <= #TCQ 'd0;
prbs_inc_tap_cnt <= #TCQ rdlvl_cpt_tap_cnt - prbs_dqs_tap_cnt_r;
prbs_state_r <= #TCQ PRBS_INC_DQS;
end
end else begin
// Otherwise, if we haven't found an edge....
// If we still have taps left to use, then keep incrementing
if (prbs_found_1st_edge_r)
prbs_state_r <= #TCQ PRBS_INC_DQS;
else
prbs_state_r <= #TCQ PRBS_DEC_DQS;
end
end
end
// Increment Phaser_IN delay for DQS
PRBS_INC_DQS: begin
prbs_state_r <= #TCQ PRBS_INC_DQS_WAIT;
if (prbs_inc_tap_cnt > 'd0)
prbs_inc_tap_cnt <= #TCQ prbs_inc_tap_cnt - 1;
if (~prbs_dqs_tap_limit_r) begin
prbs_tap_en_r <= #TCQ 1'b1;
prbs_tap_inc_r <= #TCQ 1'b1;
end else begin
prbs_tap_en_r <= #TCQ 1'b0;
prbs_tap_inc_r <= #TCQ 1'b0;
end
end
// Wait for Phaser_In to settle, before checking again for an edge
PRBS_INC_DQS_WAIT: begin
prbs_tap_en_r <= #TCQ 1'b0;
prbs_tap_inc_r <= #TCQ 1'b0;
if (cnt_wait_state) begin
if (prbs_inc_tap_cnt > 'd0)
prbs_state_r <= #TCQ PRBS_INC_DQS;
else
prbs_state_r <= #TCQ PRBS_PAT_COMPARE;
end
end
// Calculate final value of Phaser_IN taps. At this point, one or both
// edges of data eye have been found, and/or all taps have been
// exhausted looking for the edges
// NOTE: The amount to be decrement by is calculated, not the
// absolute setting for DQS.
PRBS_CALC_TAPS: begin
if (prbs_found_2nd_edge_r && prbs_found_1st_edge_r)
// Both edges detected
prbs_dec_tap_cnt
<= #TCQ ((prbs_2nd_edge_taps_r -
prbs_1st_edge_taps_r)>>1) + 1;
else if (~prbs_found_2nd_edge_r && prbs_found_1st_edge_r)
// Only left edge detected
prbs_dec_tap_cnt
<= #TCQ ((prbs_dqs_tap_cnt_r - prbs_1st_edge_taps_r)>>1);
else
// No edges detected
prbs_dec_tap_cnt
<= #TCQ (prbs_dqs_tap_cnt_r>>1);
// Now use the value we just calculated to decrement CPT taps
// to the desired calibration point
prbs_state_r <= #TCQ PRBS_TAP_CHECK; //PRBS_DEC_DQS;
end
PRBS_TAP_CHECK: begin
// Fix for CR690798 - limit PRBS tap to +/- 3 taps of rdlvl_cpt_tap_cnt
if (prbs_dec_tap_calc_minus_3 > prbs_dec_tap_cnt) begin // proposing a re-order of the condition
prbs_tap_mod[prbs_dqs_cnt_timing_r] <= #TCQ 1'b1;
prbs_dec_tap_cnt <= #TCQ prbs_dec_tap_calc_minus_3;
end else if (prbs_dec_tap_calc_plus_3 < prbs_dec_tap_cnt) begin // proposing a re-order of the condition
prbs_tap_mod[prbs_dqs_cnt_timing_r] <= #TCQ 1'b1;
prbs_dec_tap_cnt <= #TCQ prbs_dec_tap_calc_plus_3;
end
prbs_state_r <= #TCQ PRBS_DEC_DQS;
end
// decrement capture clock for final adjustment - center
// capture clock in middle of data eye. This adjustment will occur
// only when both the edges are found usign CPT taps. Must do this
// incrementally to avoid clock glitching (since CPT drives clock
// divider within each ISERDES)
PRBS_DEC_DQS: begin
prbs_tap_en_r <= #TCQ 1'b1;
prbs_tap_inc_r <= #TCQ 1'b0;
// once adjustment is complete, we're done with calibration for
// this DQS, repeat for next DQS
if (prbs_dec_tap_cnt > 'd0)
prbs_dec_tap_cnt <= #TCQ prbs_dec_tap_cnt - 1;
if (prbs_dec_tap_cnt == 6'b000001)
prbs_state_r <= #TCQ PRBS_NEXT_DQS;
else
prbs_state_r <= #TCQ PRBS_DEC_DQS_WAIT;
end
PRBS_DEC_DQS_WAIT: begin
prbs_tap_en_r <= #TCQ 1'b0;
prbs_tap_inc_r <= #TCQ 1'b0;
if (cnt_wait_state) begin
if (prbs_dec_tap_cnt > 'd0)
prbs_state_r <= #TCQ PRBS_DEC_DQS;
else
prbs_state_r <= #TCQ PRBS_PAT_COMPARE;
end
end
// Determine whether we're done, or have more DQS's to calibrate
// Also request precharge after every byte, as appropriate
PRBS_NEXT_DQS: begin
prbs_prech_req_r <= #TCQ 1'b1;
prbs_tap_en_r <= #TCQ 1'b0;
prbs_tap_inc_r <= #TCQ 1'b0;
// Prepare for another iteration with next DQS group
prbs_found_1st_edge_r <= #TCQ 1'b0;
prbs_found_2nd_edge_r <= #TCQ 1'b0;
prbs_1st_edge_taps_r <= #TCQ 'd0;
prbs_2nd_edge_taps_r <= #TCQ 'd0;
if (prbs_dqs_cnt_r >= DQS_WIDTH-1) begin
prbs_last_byte_done <= #TCQ 1'b1;
end
// Wait until precharge that occurs in between calibration of
// DQS groups is finished
if (prech_done) begin
prbs_prech_req_r <= #TCQ 1'b0;
if (prbs_dqs_cnt_r >= DQS_WIDTH-1) begin
if (rnk_cnt_r == RANKS-1) begin
// All DQS groups in all ranks done
prbs_state_r <= #TCQ PRBS_DONE;
end else begin
// Process DQS groups in next rank
rnk_cnt_r <= #TCQ rnk_cnt_r + 1;
new_cnt_dqs_r <= #TCQ 1'b1;
prbs_dqs_cnt_r <= #TCQ 'b0;
prbs_state_r <= #TCQ PRBS_IDLE;
end
end else begin
// Process next DQS group
new_cnt_dqs_r <= #TCQ 1'b1;
prbs_dqs_cnt_r <= #TCQ prbs_dqs_cnt_r + 1;
prbs_state_r <= #TCQ PRBS_NEW_DQS_PREWAIT;
end
end
end
PRBS_NEW_DQS_PREWAIT: begin
if (cnt_wait_state) begin
prbs_state_r <= #TCQ PRBS_NEW_DQS_WAIT;
end
end
// Done with this stage of calibration
PRBS_DONE: begin
prbs_prech_req_r <= #TCQ 1'b0;
prbs_last_byte_done <= #TCQ 1'b0;
prbs_rdlvl_done <= #TCQ 1'b1;
end
endcase
end
endmodule
|
/*****************************************************************
-- (c) Copyright 2011 - 2013 Xilinx, Inc. All rights reserved.
--
-- This file contains confidential and proprietary information
-- of Xilinx, Inc. and is protected under U.S. and
-- international copyright and other intellectual property
-- laws.
--
-- DISCLAIMER
-- This disclaimer is not a license and does not grant any
-- rights to the materials distributed herewith. Except as
-- otherwise provided in a valid license issued to you by
-- Xilinx, and to the maximum extent permitted by applicable
-- law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND
-- WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES
-- AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
-- BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-
-- INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and
-- (2) Xilinx shall not be liable (whether in contract or tort,
-- including negligence, or under any other theory of
-- liability) for any loss or damage of any kind or nature
-- related to, arising under or in connection with these
-- materials, including for any direct, or any indirect,
-- special, incidental, or consequential loss or damage
-- (including loss of data, profits, goodwill, or any type of
-- loss or damage suffered as a result of any action brought
-- by a third party) even if such damage or loss was
-- reasonably foreseeable or Xilinx had been advised of the
-- possibility of the same.
--
-- CRITICAL APPLICATIONS
-- Xilinx products are not designed or intended to be fail-
-- safe, or for use in any application requiring fail-safe
-- performance, such as life-support or safety devices or
-- systems, Class III medical devices, nuclear facilities,
-- applications related to the deployment of airbags, or any
-- other applications that could lead to death, personal
-- injury, or severe property or environmental damage
-- (individually and collectively, "Critical
-- Applications"). A Customer assumes the sole risk and
-- liability of any use of Xilinx products in Critical
-- Applications, subject only to applicable laws and
-- regulations governing limitations on product liability.
--
-- THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS
-- PART OF THIS FILE AT ALL TIMES.
//
//
// Owner: Gary Martin
// Revision: $Id: //depot/icm/proj/common/head/rtl/v32_cmt/rtl/phy/byte_group_io.v#4 $
// $Author: $
// $DateTime: $
// $Change: $
// Description:
// This verilog file is a paramertizable I/O termination for
// the single byte lane.
// to create a N byte-lane wide phy.
//
// History:
// Date Engineer Description
// 04/01/2010 G. Martin Initial Checkin.
//
//////////////////////////////////////////////////////////////////
*****************************************************************/
`timescale 1ps/1ps
module mig_7series_v1_9_ddr_byte_group_io #(
// bit lane existance
parameter BITLANES = 12'b1111_1111_1111,
parameter BITLANES_OUTONLY = 12'b0000_0000_0000,
parameter PO_DATA_CTL = "FALSE",
parameter OSERDES_DATA_RATE = "DDR",
parameter OSERDES_DATA_WIDTH = 4,
parameter IDELAYE2_IDELAY_TYPE = "VARIABLE",
parameter IDELAYE2_IDELAY_VALUE = 00,
parameter IODELAY_GRP = "IODELAY_MIG",
// local usage only, don't pass down
parameter BUS_WIDTH = 12,
parameter SYNTHESIS = "FALSE"
)
(
input [9:0] mem_dq_in,
output [BUS_WIDTH-1:0] mem_dq_out,
output [BUS_WIDTH-1:0] mem_dq_ts,
input mem_dqs_in,
output mem_dqs_out,
output mem_dqs_ts,
output [(4*10)-1:0] iserdes_dout, // 2 extra 12-bit lanes not used
output dqs_to_phaser,
input iserdes_clk,
input iserdes_clkb,
input iserdes_clkdiv,
input phy_clk,
input rst,
input oserdes_rst,
input iserdes_rst,
input [1:0] oserdes_dqs,
input [1:0] oserdes_dqsts,
input [(4*BUS_WIDTH)-1:0] oserdes_dq,
input [1:0] oserdes_dqts,
input oserdes_clk,
input oserdes_clk_delayed,
input oserdes_clkdiv,
input idelay_inc,
input idelay_ce,
input idelay_ld,
input idelayctrl_refclk
);
/// INSTANCES
localparam ISERDES_DQ_DATA_RATE = "DDR";
localparam ISERDES_DQ_DATA_WIDTH = 4;
localparam ISERDES_DQ_DYN_CLKDIV_INV_EN = "FALSE";
localparam ISERDES_DQ_DYN_CLK_INV_EN = "FALSE";
localparam ISERDES_DQ_INIT_Q1 = 1'b0;
localparam ISERDES_DQ_INIT_Q2 = 1'b0;
localparam ISERDES_DQ_INIT_Q3 = 1'b0;
localparam ISERDES_DQ_INIT_Q4 = 1'b0;
localparam ISERDES_DQ_INTERFACE_TYPE = "MEMORY_DDR3";
localparam ISERDES_NUM_CE = 2;
localparam ISERDES_DQ_IOBDELAY = "IFD";
localparam ISERDES_DQ_OFB_USED = "FALSE";
localparam ISERDES_DQ_SERDES_MODE = "MASTER";
localparam ISERDES_DQ_SRVAL_Q1 = 1'b0;
localparam ISERDES_DQ_SRVAL_Q2 = 1'b0;
localparam ISERDES_DQ_SRVAL_Q3 = 1'b0;
localparam ISERDES_DQ_SRVAL_Q4 = 1'b0;
wire [BUS_WIDTH-1:0] data_in_dly;
wire [BUS_WIDTH-1:0] oserdes_dq_buf;
wire [BUS_WIDTH-1:0] oserdes_dqts_buf;
wire oserdes_dqs_buf;
wire oserdes_dqsts_buf;
wire [9:0] data_in;
wire tbyte_out;
assign mem_dq_out = oserdes_dq_buf;
assign mem_dq_ts = oserdes_dqts_buf;
assign data_in = mem_dq_in;
assign mem_dqs_out = oserdes_dqs_buf;
assign mem_dqs_ts = oserdes_dqsts_buf;
assign dqs_to_phaser = mem_dqs_in;
reg iserdes_clk_d;
always @(*)
iserdes_clk_d <= #(025) iserdes_clk;
reg idelay_ld_rst;
reg rst_r1;
reg rst_r2;
reg rst_r3;
reg rst_r4;
always @(posedge phy_clk) begin
rst_r1 <= #1 rst;
rst_r2 <= #1 rst_r1;
rst_r3 <= #1 rst_r2;
rst_r4 <= #1 rst_r3;
end
always @(posedge phy_clk) begin
if (rst)
idelay_ld_rst <= #1 1'b1;
else if (rst_r4)
idelay_ld_rst <= #1 1'b0;
end
genvar i;
generate
for ( i = 0; i != 10 && PO_DATA_CTL == "TRUE" ; i=i+1) begin : input_
if ( BITLANES[i] && !BITLANES_OUTONLY[i]) begin : iserdes_dq_
ISERDESE2 #(
.DATA_RATE ( ISERDES_DQ_DATA_RATE),
.DATA_WIDTH ( ISERDES_DQ_DATA_WIDTH),
.DYN_CLKDIV_INV_EN ( ISERDES_DQ_DYN_CLKDIV_INV_EN),
.DYN_CLK_INV_EN ( ISERDES_DQ_DYN_CLK_INV_EN),
.INIT_Q1 ( ISERDES_DQ_INIT_Q1),
.INIT_Q2 ( ISERDES_DQ_INIT_Q2),
.INIT_Q3 ( ISERDES_DQ_INIT_Q3),
.INIT_Q4 ( ISERDES_DQ_INIT_Q4),
.INTERFACE_TYPE ( ISERDES_DQ_INTERFACE_TYPE),
.NUM_CE ( ISERDES_NUM_CE),
.IOBDELAY ( ISERDES_DQ_IOBDELAY),
.OFB_USED ( ISERDES_DQ_OFB_USED),
.SERDES_MODE ( ISERDES_DQ_SERDES_MODE),
.SRVAL_Q1 ( ISERDES_DQ_SRVAL_Q1),
.SRVAL_Q2 ( ISERDES_DQ_SRVAL_Q2),
.SRVAL_Q3 ( ISERDES_DQ_SRVAL_Q3),
.SRVAL_Q4 ( ISERDES_DQ_SRVAL_Q4)
)
iserdesdq
(
.O (),
.Q1 (iserdes_dout[4*i + 3]),
.Q2 (iserdes_dout[4*i + 2]),
.Q3 (iserdes_dout[4*i + 1]),
.Q4 (iserdes_dout[4*i + 0]),
.Q5 (),
.Q6 (),
.SHIFTOUT1 (),
.SHIFTOUT2 (),
.BITSLIP (1'b0),
.CE1 (1'b1),
.CE2 (1'b1),
.CLK (iserdes_clk_d),
.CLKB (!iserdes_clk_d),
.CLKDIVP (iserdes_clkdiv),
.CLKDIV (),
.DDLY (data_in_dly[i]),
.D (data_in[i]), // dedicated route to iob for debugging
// or as needed, select with IOBDELAY
.DYNCLKDIVSEL (1'b0),
.DYNCLKSEL (1'b0),
// NOTE: OCLK is not used in this design, but is required to meet
// a design rule check in map and bitgen. Do not disconnect it.
.OCLK (oserdes_clk),
.OFB (),
.RST (1'b0),
// .RST (iserdes_rst),
.SHIFTIN1 (1'b0),
.SHIFTIN2 (1'b0)
);
localparam IDELAYE2_CINVCTRL_SEL = "FALSE";
localparam IDELAYE2_DELAY_SRC = "IDATAIN";
localparam IDELAYE2_HIGH_PERFORMANCE_MODE = "TRUE";
localparam IDELAYE2_PIPE_SEL = "FALSE";
localparam IDELAYE2_ODELAY_TYPE = "FIXED";
localparam IDELAYE2_REFCLK_FREQUENCY = 200.0;
localparam IDELAYE2_SIGNAL_PATTERN = "DATA";
(* IODELAY_GROUP = IODELAY_GRP *)
IDELAYE2 #(
.CINVCTRL_SEL ( IDELAYE2_CINVCTRL_SEL),
.DELAY_SRC ( IDELAYE2_DELAY_SRC),
.HIGH_PERFORMANCE_MODE ( IDELAYE2_HIGH_PERFORMANCE_MODE),
.IDELAY_TYPE ( IDELAYE2_IDELAY_TYPE),
.IDELAY_VALUE ( IDELAYE2_IDELAY_VALUE),
.PIPE_SEL ( IDELAYE2_PIPE_SEL),
.REFCLK_FREQUENCY ( IDELAYE2_REFCLK_FREQUENCY ),
.SIGNAL_PATTERN ( IDELAYE2_SIGNAL_PATTERN)
)
idelaye2
(
.CNTVALUEOUT (),
.DATAOUT (data_in_dly[i]),
.C (phy_clk), // automatically wired by ISE
.CE (idelay_ce),
.CINVCTRL (),
.CNTVALUEIN (5'b00000),
.DATAIN (1'b0),
.IDATAIN (data_in[i]),
.INC (idelay_inc),
.LD (idelay_ld | idelay_ld_rst),
.LDPIPEEN (1'b0),
.REGRST (rst)
);
end // iserdes_dq
else begin
assign iserdes_dout[4*i + 3] = 0;
assign iserdes_dout[4*i + 2] = 0;
assign iserdes_dout[4*i + 1] = 0;
assign iserdes_dout[4*i + 0] = 0;
end
end // input_
endgenerate // iserdes_dq_
localparam OSERDES_DQ_DATA_RATE_OQ = OSERDES_DATA_RATE;
localparam OSERDES_DQ_DATA_RATE_TQ = OSERDES_DQ_DATA_RATE_OQ;
localparam OSERDES_DQ_DATA_WIDTH = OSERDES_DATA_WIDTH;
localparam OSERDES_DQ_INIT_OQ = 1'b1;
localparam OSERDES_DQ_INIT_TQ = 1'b1;
localparam OSERDES_DQ_INTERFACE_TYPE = "DEFAULT";
localparam OSERDES_DQ_ODELAY_USED = 0;
localparam OSERDES_DQ_SERDES_MODE = "MASTER";
localparam OSERDES_DQ_SRVAL_OQ = 1'b1;
localparam OSERDES_DQ_SRVAL_TQ = 1'b1;
// note: obuf used in control path case, no ts input so width irrelevant
localparam OSERDES_DQ_TRISTATE_WIDTH = (OSERDES_DQ_DATA_RATE_OQ == "DDR") ? 4 : 1;
localparam OSERDES_DQS_DATA_RATE_OQ = "DDR";
localparam OSERDES_DQS_DATA_RATE_TQ = "DDR";
localparam OSERDES_DQS_TRISTATE_WIDTH = 4; // this is always ddr
localparam OSERDES_DQS_DATA_WIDTH = 4;
localparam ODDR_CLK_EDGE = "SAME_EDGE";
localparam OSERDES_TBYTE_CTL = "TRUE";
generate
localparam NUM_BITLANES = PO_DATA_CTL == "TRUE" ? 10 : BUS_WIDTH;
if ( PO_DATA_CTL == "TRUE" ) begin : slave_ts
OSERDESE2 #(
.DATA_RATE_OQ (OSERDES_DQ_DATA_RATE_OQ),
.DATA_RATE_TQ (OSERDES_DQ_DATA_RATE_TQ),
.DATA_WIDTH (OSERDES_DQ_DATA_WIDTH),
.INIT_OQ (OSERDES_DQ_INIT_OQ),
.INIT_TQ (OSERDES_DQ_INIT_TQ),
.SERDES_MODE (OSERDES_DQ_SERDES_MODE),
.SRVAL_OQ (OSERDES_DQ_SRVAL_OQ),
.SRVAL_TQ (OSERDES_DQ_SRVAL_TQ),
.TRISTATE_WIDTH (OSERDES_DQ_TRISTATE_WIDTH),
.TBYTE_CTL ("TRUE"),
.TBYTE_SRC ("TRUE")
)
oserdes_slave_ts
(
.OFB (),
.OQ (),
.SHIFTOUT1 (), // not extended
.SHIFTOUT2 (), // not extended
.TFB (),
.TQ (),
.CLK (oserdes_clk),
.CLKDIV (oserdes_clkdiv),
.D1 (),
.D2 (),
.D3 (),
.D4 (),
.D5 (),
.D6 (),
.OCE (1'b1),
.RST (oserdes_rst),
.SHIFTIN1 (), // not extended
.SHIFTIN2 (), // not extended
.T1 (oserdes_dqts[0]),
.T2 (oserdes_dqts[0]),
.T3 (oserdes_dqts[1]),
.T4 (oserdes_dqts[1]),
.TCE (1'b1),
.TBYTEOUT (tbyte_out),
.TBYTEIN (tbyte_out)
);
end // slave_ts
for (i = 0; i != NUM_BITLANES; i=i+1) begin : output_
if ( BITLANES[i]) begin : oserdes_dq_
if ( PO_DATA_CTL == "TRUE" ) begin : ddr
OSERDESE2 #(
.DATA_RATE_OQ (OSERDES_DQ_DATA_RATE_OQ),
.DATA_RATE_TQ (OSERDES_DQ_DATA_RATE_TQ),
.DATA_WIDTH (OSERDES_DQ_DATA_WIDTH),
.INIT_OQ (OSERDES_DQ_INIT_OQ),
.INIT_TQ (OSERDES_DQ_INIT_TQ),
.SERDES_MODE (OSERDES_DQ_SERDES_MODE),
.SRVAL_OQ (OSERDES_DQ_SRVAL_OQ),
.SRVAL_TQ (OSERDES_DQ_SRVAL_TQ),
.TRISTATE_WIDTH (OSERDES_DQ_TRISTATE_WIDTH),
.TBYTE_CTL (OSERDES_TBYTE_CTL),
.TBYTE_SRC ("FALSE")
)
oserdes_dq_i
(
.OFB (),
.OQ (oserdes_dq_buf[i]),
.SHIFTOUT1 (), // not extended
.SHIFTOUT2 (), // not extended
.TFB (),
.TQ (oserdes_dqts_buf[i]),
.CLK (oserdes_clk),
.CLKDIV (oserdes_clkdiv),
.D1 (oserdes_dq[4 * i + 0]),
.D2 (oserdes_dq[4 * i + 1]),
.D3 (oserdes_dq[4 * i + 2]),
.D4 (oserdes_dq[4 * i + 3]),
.D5 (),
.D6 (),
.OCE (1'b1),
.RST (oserdes_rst),
.SHIFTIN1 (), // not extended
.SHIFTIN2 (), // not extended
.T1 (/*oserdes_dqts[0]*/),
.T2 (/*oserdes_dqts[0]*/),
.T3 (/*oserdes_dqts[1]*/),
.T4 (/*oserdes_dqts[1]*/),
.TCE (1'b1),
.TBYTEIN (tbyte_out)
);
end
else begin : sdr
OSERDESE2 #(
.DATA_RATE_OQ (OSERDES_DQ_DATA_RATE_OQ),
.DATA_RATE_TQ (OSERDES_DQ_DATA_RATE_TQ),
.DATA_WIDTH (OSERDES_DQ_DATA_WIDTH),
.INIT_OQ (1'b0 /*OSERDES_DQ_INIT_OQ*/),
.INIT_TQ (OSERDES_DQ_INIT_TQ),
.SERDES_MODE (OSERDES_DQ_SERDES_MODE),
.SRVAL_OQ (1'b0 /*OSERDES_DQ_SRVAL_OQ*/),
.SRVAL_TQ (OSERDES_DQ_SRVAL_TQ),
.TRISTATE_WIDTH (OSERDES_DQ_TRISTATE_WIDTH)
)
oserdes_dq_i
(
.OFB (),
.OQ (oserdes_dq_buf[i]),
.SHIFTOUT1 (), // not extended
.SHIFTOUT2 (), // not extended
.TFB (),
.TQ (),
.CLK (oserdes_clk),
.CLKDIV (oserdes_clkdiv),
.D1 (oserdes_dq[4 * i + 0]),
.D2 (oserdes_dq[4 * i + 1]),
.D3 (oserdes_dq[4 * i + 2]),
.D4 (oserdes_dq[4 * i + 3]),
.D5 (),
.D6 (),
.OCE (1'b1),
.RST (oserdes_rst),
.SHIFTIN1 (), // not extended
.SHIFTIN2 (), // not extended
.T1 (),
.T2 (),
.T3 (),
.T4 (),
.TCE (1'b1)
);
end // ddr
end // oserdes_dq_
end // output_
endgenerate
generate
if ( PO_DATA_CTL == "TRUE" ) begin : dqs_gen
ODDR
#(.DDR_CLK_EDGE (ODDR_CLK_EDGE))
oddr_dqs
(
.Q (oserdes_dqs_buf),
.D1 (oserdes_dqs[0]),
.D2 (oserdes_dqs[1]),
.C (oserdes_clk_delayed),
.R (1'b0),
.S (),
.CE (1'b1)
);
ODDR
#(.DDR_CLK_EDGE (ODDR_CLK_EDGE))
oddr_dqsts
( .Q (oserdes_dqsts_buf),
.D1 (oserdes_dqsts[0]),
.D2 (oserdes_dqsts[0]),
.C (oserdes_clk_delayed),
.R (),
.S (1'b0),
.CE (1'b1)
);
end // sdr rate
else begin:null_dqs
end
endgenerate
endmodule // byte_group_io
|
/*****************************************************************
-- (c) Copyright 2011 - 2013 Xilinx, Inc. All rights reserved.
--
-- This file contains confidential and proprietary information
-- of Xilinx, Inc. and is protected under U.S. and
-- international copyright and other intellectual property
-- laws.
--
-- DISCLAIMER
-- This disclaimer is not a license and does not grant any
-- rights to the materials distributed herewith. Except as
-- otherwise provided in a valid license issued to you by
-- Xilinx, and to the maximum extent permitted by applicable
-- law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND
-- WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES
-- AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
-- BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-
-- INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and
-- (2) Xilinx shall not be liable (whether in contract or tort,
-- including negligence, or under any other theory of
-- liability) for any loss or damage of any kind or nature
-- related to, arising under or in connection with these
-- materials, including for any direct, or any indirect,
-- special, incidental, or consequential loss or damage
-- (including loss of data, profits, goodwill, or any type of
-- loss or damage suffered as a result of any action brought
-- by a third party) even if such damage or loss was
-- reasonably foreseeable or Xilinx had been advised of the
-- possibility of the same.
--
-- CRITICAL APPLICATIONS
-- Xilinx products are not designed or intended to be fail-
-- safe, or for use in any application requiring fail-safe
-- performance, such as life-support or safety devices or
-- systems, Class III medical devices, nuclear facilities,
-- applications related to the deployment of airbags, or any
-- other applications that could lead to death, personal
-- injury, or severe property or environmental damage
-- (individually and collectively, "Critical
-- Applications"). A Customer assumes the sole risk and
-- liability of any use of Xilinx products in Critical
-- Applications, subject only to applicable laws and
-- regulations governing limitations on product liability.
--
-- THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS
-- PART OF THIS FILE AT ALL TIMES.
//
//
// Owner: Gary Martin
// Revision: $Id: //depot/icm/proj/common/head/rtl/v32_cmt/rtl/phy/byte_group_io.v#4 $
// $Author: $
// $DateTime: $
// $Change: $
// Description:
// This verilog file is a paramertizable I/O termination for
// the single byte lane.
// to create a N byte-lane wide phy.
//
// History:
// Date Engineer Description
// 04/01/2010 G. Martin Initial Checkin.
//
//////////////////////////////////////////////////////////////////
*****************************************************************/
`timescale 1ps/1ps
module mig_7series_v1_9_ddr_byte_group_io #(
// bit lane existance
parameter BITLANES = 12'b1111_1111_1111,
parameter BITLANES_OUTONLY = 12'b0000_0000_0000,
parameter PO_DATA_CTL = "FALSE",
parameter OSERDES_DATA_RATE = "DDR",
parameter OSERDES_DATA_WIDTH = 4,
parameter IDELAYE2_IDELAY_TYPE = "VARIABLE",
parameter IDELAYE2_IDELAY_VALUE = 00,
parameter IODELAY_GRP = "IODELAY_MIG",
// local usage only, don't pass down
parameter BUS_WIDTH = 12,
parameter SYNTHESIS = "FALSE"
)
(
input [9:0] mem_dq_in,
output [BUS_WIDTH-1:0] mem_dq_out,
output [BUS_WIDTH-1:0] mem_dq_ts,
input mem_dqs_in,
output mem_dqs_out,
output mem_dqs_ts,
output [(4*10)-1:0] iserdes_dout, // 2 extra 12-bit lanes not used
output dqs_to_phaser,
input iserdes_clk,
input iserdes_clkb,
input iserdes_clkdiv,
input phy_clk,
input rst,
input oserdes_rst,
input iserdes_rst,
input [1:0] oserdes_dqs,
input [1:0] oserdes_dqsts,
input [(4*BUS_WIDTH)-1:0] oserdes_dq,
input [1:0] oserdes_dqts,
input oserdes_clk,
input oserdes_clk_delayed,
input oserdes_clkdiv,
input idelay_inc,
input idelay_ce,
input idelay_ld,
input idelayctrl_refclk
);
/// INSTANCES
localparam ISERDES_DQ_DATA_RATE = "DDR";
localparam ISERDES_DQ_DATA_WIDTH = 4;
localparam ISERDES_DQ_DYN_CLKDIV_INV_EN = "FALSE";
localparam ISERDES_DQ_DYN_CLK_INV_EN = "FALSE";
localparam ISERDES_DQ_INIT_Q1 = 1'b0;
localparam ISERDES_DQ_INIT_Q2 = 1'b0;
localparam ISERDES_DQ_INIT_Q3 = 1'b0;
localparam ISERDES_DQ_INIT_Q4 = 1'b0;
localparam ISERDES_DQ_INTERFACE_TYPE = "MEMORY_DDR3";
localparam ISERDES_NUM_CE = 2;
localparam ISERDES_DQ_IOBDELAY = "IFD";
localparam ISERDES_DQ_OFB_USED = "FALSE";
localparam ISERDES_DQ_SERDES_MODE = "MASTER";
localparam ISERDES_DQ_SRVAL_Q1 = 1'b0;
localparam ISERDES_DQ_SRVAL_Q2 = 1'b0;
localparam ISERDES_DQ_SRVAL_Q3 = 1'b0;
localparam ISERDES_DQ_SRVAL_Q4 = 1'b0;
wire [BUS_WIDTH-1:0] data_in_dly;
wire [BUS_WIDTH-1:0] oserdes_dq_buf;
wire [BUS_WIDTH-1:0] oserdes_dqts_buf;
wire oserdes_dqs_buf;
wire oserdes_dqsts_buf;
wire [9:0] data_in;
wire tbyte_out;
assign mem_dq_out = oserdes_dq_buf;
assign mem_dq_ts = oserdes_dqts_buf;
assign data_in = mem_dq_in;
assign mem_dqs_out = oserdes_dqs_buf;
assign mem_dqs_ts = oserdes_dqsts_buf;
assign dqs_to_phaser = mem_dqs_in;
reg iserdes_clk_d;
always @(*)
iserdes_clk_d <= #(025) iserdes_clk;
reg idelay_ld_rst;
reg rst_r1;
reg rst_r2;
reg rst_r3;
reg rst_r4;
always @(posedge phy_clk) begin
rst_r1 <= #1 rst;
rst_r2 <= #1 rst_r1;
rst_r3 <= #1 rst_r2;
rst_r4 <= #1 rst_r3;
end
always @(posedge phy_clk) begin
if (rst)
idelay_ld_rst <= #1 1'b1;
else if (rst_r4)
idelay_ld_rst <= #1 1'b0;
end
genvar i;
generate
for ( i = 0; i != 10 && PO_DATA_CTL == "TRUE" ; i=i+1) begin : input_
if ( BITLANES[i] && !BITLANES_OUTONLY[i]) begin : iserdes_dq_
ISERDESE2 #(
.DATA_RATE ( ISERDES_DQ_DATA_RATE),
.DATA_WIDTH ( ISERDES_DQ_DATA_WIDTH),
.DYN_CLKDIV_INV_EN ( ISERDES_DQ_DYN_CLKDIV_INV_EN),
.DYN_CLK_INV_EN ( ISERDES_DQ_DYN_CLK_INV_EN),
.INIT_Q1 ( ISERDES_DQ_INIT_Q1),
.INIT_Q2 ( ISERDES_DQ_INIT_Q2),
.INIT_Q3 ( ISERDES_DQ_INIT_Q3),
.INIT_Q4 ( ISERDES_DQ_INIT_Q4),
.INTERFACE_TYPE ( ISERDES_DQ_INTERFACE_TYPE),
.NUM_CE ( ISERDES_NUM_CE),
.IOBDELAY ( ISERDES_DQ_IOBDELAY),
.OFB_USED ( ISERDES_DQ_OFB_USED),
.SERDES_MODE ( ISERDES_DQ_SERDES_MODE),
.SRVAL_Q1 ( ISERDES_DQ_SRVAL_Q1),
.SRVAL_Q2 ( ISERDES_DQ_SRVAL_Q2),
.SRVAL_Q3 ( ISERDES_DQ_SRVAL_Q3),
.SRVAL_Q4 ( ISERDES_DQ_SRVAL_Q4)
)
iserdesdq
(
.O (),
.Q1 (iserdes_dout[4*i + 3]),
.Q2 (iserdes_dout[4*i + 2]),
.Q3 (iserdes_dout[4*i + 1]),
.Q4 (iserdes_dout[4*i + 0]),
.Q5 (),
.Q6 (),
.SHIFTOUT1 (),
.SHIFTOUT2 (),
.BITSLIP (1'b0),
.CE1 (1'b1),
.CE2 (1'b1),
.CLK (iserdes_clk_d),
.CLKB (!iserdes_clk_d),
.CLKDIVP (iserdes_clkdiv),
.CLKDIV (),
.DDLY (data_in_dly[i]),
.D (data_in[i]), // dedicated route to iob for debugging
// or as needed, select with IOBDELAY
.DYNCLKDIVSEL (1'b0),
.DYNCLKSEL (1'b0),
// NOTE: OCLK is not used in this design, but is required to meet
// a design rule check in map and bitgen. Do not disconnect it.
.OCLK (oserdes_clk),
.OFB (),
.RST (1'b0),
// .RST (iserdes_rst),
.SHIFTIN1 (1'b0),
.SHIFTIN2 (1'b0)
);
localparam IDELAYE2_CINVCTRL_SEL = "FALSE";
localparam IDELAYE2_DELAY_SRC = "IDATAIN";
localparam IDELAYE2_HIGH_PERFORMANCE_MODE = "TRUE";
localparam IDELAYE2_PIPE_SEL = "FALSE";
localparam IDELAYE2_ODELAY_TYPE = "FIXED";
localparam IDELAYE2_REFCLK_FREQUENCY = 200.0;
localparam IDELAYE2_SIGNAL_PATTERN = "DATA";
(* IODELAY_GROUP = IODELAY_GRP *)
IDELAYE2 #(
.CINVCTRL_SEL ( IDELAYE2_CINVCTRL_SEL),
.DELAY_SRC ( IDELAYE2_DELAY_SRC),
.HIGH_PERFORMANCE_MODE ( IDELAYE2_HIGH_PERFORMANCE_MODE),
.IDELAY_TYPE ( IDELAYE2_IDELAY_TYPE),
.IDELAY_VALUE ( IDELAYE2_IDELAY_VALUE),
.PIPE_SEL ( IDELAYE2_PIPE_SEL),
.REFCLK_FREQUENCY ( IDELAYE2_REFCLK_FREQUENCY ),
.SIGNAL_PATTERN ( IDELAYE2_SIGNAL_PATTERN)
)
idelaye2
(
.CNTVALUEOUT (),
.DATAOUT (data_in_dly[i]),
.C (phy_clk), // automatically wired by ISE
.CE (idelay_ce),
.CINVCTRL (),
.CNTVALUEIN (5'b00000),
.DATAIN (1'b0),
.IDATAIN (data_in[i]),
.INC (idelay_inc),
.LD (idelay_ld | idelay_ld_rst),
.LDPIPEEN (1'b0),
.REGRST (rst)
);
end // iserdes_dq
else begin
assign iserdes_dout[4*i + 3] = 0;
assign iserdes_dout[4*i + 2] = 0;
assign iserdes_dout[4*i + 1] = 0;
assign iserdes_dout[4*i + 0] = 0;
end
end // input_
endgenerate // iserdes_dq_
localparam OSERDES_DQ_DATA_RATE_OQ = OSERDES_DATA_RATE;
localparam OSERDES_DQ_DATA_RATE_TQ = OSERDES_DQ_DATA_RATE_OQ;
localparam OSERDES_DQ_DATA_WIDTH = OSERDES_DATA_WIDTH;
localparam OSERDES_DQ_INIT_OQ = 1'b1;
localparam OSERDES_DQ_INIT_TQ = 1'b1;
localparam OSERDES_DQ_INTERFACE_TYPE = "DEFAULT";
localparam OSERDES_DQ_ODELAY_USED = 0;
localparam OSERDES_DQ_SERDES_MODE = "MASTER";
localparam OSERDES_DQ_SRVAL_OQ = 1'b1;
localparam OSERDES_DQ_SRVAL_TQ = 1'b1;
// note: obuf used in control path case, no ts input so width irrelevant
localparam OSERDES_DQ_TRISTATE_WIDTH = (OSERDES_DQ_DATA_RATE_OQ == "DDR") ? 4 : 1;
localparam OSERDES_DQS_DATA_RATE_OQ = "DDR";
localparam OSERDES_DQS_DATA_RATE_TQ = "DDR";
localparam OSERDES_DQS_TRISTATE_WIDTH = 4; // this is always ddr
localparam OSERDES_DQS_DATA_WIDTH = 4;
localparam ODDR_CLK_EDGE = "SAME_EDGE";
localparam OSERDES_TBYTE_CTL = "TRUE";
generate
localparam NUM_BITLANES = PO_DATA_CTL == "TRUE" ? 10 : BUS_WIDTH;
if ( PO_DATA_CTL == "TRUE" ) begin : slave_ts
OSERDESE2 #(
.DATA_RATE_OQ (OSERDES_DQ_DATA_RATE_OQ),
.DATA_RATE_TQ (OSERDES_DQ_DATA_RATE_TQ),
.DATA_WIDTH (OSERDES_DQ_DATA_WIDTH),
.INIT_OQ (OSERDES_DQ_INIT_OQ),
.INIT_TQ (OSERDES_DQ_INIT_TQ),
.SERDES_MODE (OSERDES_DQ_SERDES_MODE),
.SRVAL_OQ (OSERDES_DQ_SRVAL_OQ),
.SRVAL_TQ (OSERDES_DQ_SRVAL_TQ),
.TRISTATE_WIDTH (OSERDES_DQ_TRISTATE_WIDTH),
.TBYTE_CTL ("TRUE"),
.TBYTE_SRC ("TRUE")
)
oserdes_slave_ts
(
.OFB (),
.OQ (),
.SHIFTOUT1 (), // not extended
.SHIFTOUT2 (), // not extended
.TFB (),
.TQ (),
.CLK (oserdes_clk),
.CLKDIV (oserdes_clkdiv),
.D1 (),
.D2 (),
.D3 (),
.D4 (),
.D5 (),
.D6 (),
.OCE (1'b1),
.RST (oserdes_rst),
.SHIFTIN1 (), // not extended
.SHIFTIN2 (), // not extended
.T1 (oserdes_dqts[0]),
.T2 (oserdes_dqts[0]),
.T3 (oserdes_dqts[1]),
.T4 (oserdes_dqts[1]),
.TCE (1'b1),
.TBYTEOUT (tbyte_out),
.TBYTEIN (tbyte_out)
);
end // slave_ts
for (i = 0; i != NUM_BITLANES; i=i+1) begin : output_
if ( BITLANES[i]) begin : oserdes_dq_
if ( PO_DATA_CTL == "TRUE" ) begin : ddr
OSERDESE2 #(
.DATA_RATE_OQ (OSERDES_DQ_DATA_RATE_OQ),
.DATA_RATE_TQ (OSERDES_DQ_DATA_RATE_TQ),
.DATA_WIDTH (OSERDES_DQ_DATA_WIDTH),
.INIT_OQ (OSERDES_DQ_INIT_OQ),
.INIT_TQ (OSERDES_DQ_INIT_TQ),
.SERDES_MODE (OSERDES_DQ_SERDES_MODE),
.SRVAL_OQ (OSERDES_DQ_SRVAL_OQ),
.SRVAL_TQ (OSERDES_DQ_SRVAL_TQ),
.TRISTATE_WIDTH (OSERDES_DQ_TRISTATE_WIDTH),
.TBYTE_CTL (OSERDES_TBYTE_CTL),
.TBYTE_SRC ("FALSE")
)
oserdes_dq_i
(
.OFB (),
.OQ (oserdes_dq_buf[i]),
.SHIFTOUT1 (), // not extended
.SHIFTOUT2 (), // not extended
.TFB (),
.TQ (oserdes_dqts_buf[i]),
.CLK (oserdes_clk),
.CLKDIV (oserdes_clkdiv),
.D1 (oserdes_dq[4 * i + 0]),
.D2 (oserdes_dq[4 * i + 1]),
.D3 (oserdes_dq[4 * i + 2]),
.D4 (oserdes_dq[4 * i + 3]),
.D5 (),
.D6 (),
.OCE (1'b1),
.RST (oserdes_rst),
.SHIFTIN1 (), // not extended
.SHIFTIN2 (), // not extended
.T1 (/*oserdes_dqts[0]*/),
.T2 (/*oserdes_dqts[0]*/),
.T3 (/*oserdes_dqts[1]*/),
.T4 (/*oserdes_dqts[1]*/),
.TCE (1'b1),
.TBYTEIN (tbyte_out)
);
end
else begin : sdr
OSERDESE2 #(
.DATA_RATE_OQ (OSERDES_DQ_DATA_RATE_OQ),
.DATA_RATE_TQ (OSERDES_DQ_DATA_RATE_TQ),
.DATA_WIDTH (OSERDES_DQ_DATA_WIDTH),
.INIT_OQ (1'b0 /*OSERDES_DQ_INIT_OQ*/),
.INIT_TQ (OSERDES_DQ_INIT_TQ),
.SERDES_MODE (OSERDES_DQ_SERDES_MODE),
.SRVAL_OQ (1'b0 /*OSERDES_DQ_SRVAL_OQ*/),
.SRVAL_TQ (OSERDES_DQ_SRVAL_TQ),
.TRISTATE_WIDTH (OSERDES_DQ_TRISTATE_WIDTH)
)
oserdes_dq_i
(
.OFB (),
.OQ (oserdes_dq_buf[i]),
.SHIFTOUT1 (), // not extended
.SHIFTOUT2 (), // not extended
.TFB (),
.TQ (),
.CLK (oserdes_clk),
.CLKDIV (oserdes_clkdiv),
.D1 (oserdes_dq[4 * i + 0]),
.D2 (oserdes_dq[4 * i + 1]),
.D3 (oserdes_dq[4 * i + 2]),
.D4 (oserdes_dq[4 * i + 3]),
.D5 (),
.D6 (),
.OCE (1'b1),
.RST (oserdes_rst),
.SHIFTIN1 (), // not extended
.SHIFTIN2 (), // not extended
.T1 (),
.T2 (),
.T3 (),
.T4 (),
.TCE (1'b1)
);
end // ddr
end // oserdes_dq_
end // output_
endgenerate
generate
if ( PO_DATA_CTL == "TRUE" ) begin : dqs_gen
ODDR
#(.DDR_CLK_EDGE (ODDR_CLK_EDGE))
oddr_dqs
(
.Q (oserdes_dqs_buf),
.D1 (oserdes_dqs[0]),
.D2 (oserdes_dqs[1]),
.C (oserdes_clk_delayed),
.R (1'b0),
.S (),
.CE (1'b1)
);
ODDR
#(.DDR_CLK_EDGE (ODDR_CLK_EDGE))
oddr_dqsts
( .Q (oserdes_dqsts_buf),
.D1 (oserdes_dqsts[0]),
.D2 (oserdes_dqsts[0]),
.C (oserdes_clk_delayed),
.R (),
.S (1'b0),
.CE (1'b1)
);
end // sdr rate
else begin:null_dqs
end
endgenerate
endmodule // byte_group_io
|
/*****************************************************************
-- (c) Copyright 2011 - 2013 Xilinx, Inc. All rights reserved.
--
-- This file contains confidential and proprietary information
-- of Xilinx, Inc. and is protected under U.S. and
-- international copyright and other intellectual property
-- laws.
--
-- DISCLAIMER
-- This disclaimer is not a license and does not grant any
-- rights to the materials distributed herewith. Except as
-- otherwise provided in a valid license issued to you by
-- Xilinx, and to the maximum extent permitted by applicable
-- law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND
-- WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES
-- AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
-- BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-
-- INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and
-- (2) Xilinx shall not be liable (whether in contract or tort,
-- including negligence, or under any other theory of
-- liability) for any loss or damage of any kind or nature
-- related to, arising under or in connection with these
-- materials, including for any direct, or any indirect,
-- special, incidental, or consequential loss or damage
-- (including loss of data, profits, goodwill, or any type of
-- loss or damage suffered as a result of any action brought
-- by a third party) even if such damage or loss was
-- reasonably foreseeable or Xilinx had been advised of the
-- possibility of the same.
--
-- CRITICAL APPLICATIONS
-- Xilinx products are not designed or intended to be fail-
-- safe, or for use in any application requiring fail-safe
-- performance, such as life-support or safety devices or
-- systems, Class III medical devices, nuclear facilities,
-- applications related to the deployment of airbags, or any
-- other applications that could lead to death, personal
-- injury, or severe property or environmental damage
-- (individually and collectively, "Critical
-- Applications"). A Customer assumes the sole risk and
-- liability of any use of Xilinx products in Critical
-- Applications, subject only to applicable laws and
-- regulations governing limitations on product liability.
--
-- THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS
-- PART OF THIS FILE AT ALL TIMES.
//
//
// Owner: Gary Martin
// Revision: $Id: //depot/icm/proj/common/head/rtl/v32_cmt/rtl/phy/byte_group_io.v#4 $
// $Author: $
// $DateTime: $
// $Change: $
// Description:
// This verilog file is a paramertizable I/O termination for
// the single byte lane.
// to create a N byte-lane wide phy.
//
// History:
// Date Engineer Description
// 04/01/2010 G. Martin Initial Checkin.
//
//////////////////////////////////////////////////////////////////
*****************************************************************/
`timescale 1ps/1ps
module mig_7series_v1_9_ddr_byte_group_io #(
// bit lane existance
parameter BITLANES = 12'b1111_1111_1111,
parameter BITLANES_OUTONLY = 12'b0000_0000_0000,
parameter PO_DATA_CTL = "FALSE",
parameter OSERDES_DATA_RATE = "DDR",
parameter OSERDES_DATA_WIDTH = 4,
parameter IDELAYE2_IDELAY_TYPE = "VARIABLE",
parameter IDELAYE2_IDELAY_VALUE = 00,
parameter IODELAY_GRP = "IODELAY_MIG",
// local usage only, don't pass down
parameter BUS_WIDTH = 12,
parameter SYNTHESIS = "FALSE"
)
(
input [9:0] mem_dq_in,
output [BUS_WIDTH-1:0] mem_dq_out,
output [BUS_WIDTH-1:0] mem_dq_ts,
input mem_dqs_in,
output mem_dqs_out,
output mem_dqs_ts,
output [(4*10)-1:0] iserdes_dout, // 2 extra 12-bit lanes not used
output dqs_to_phaser,
input iserdes_clk,
input iserdes_clkb,
input iserdes_clkdiv,
input phy_clk,
input rst,
input oserdes_rst,
input iserdes_rst,
input [1:0] oserdes_dqs,
input [1:0] oserdes_dqsts,
input [(4*BUS_WIDTH)-1:0] oserdes_dq,
input [1:0] oserdes_dqts,
input oserdes_clk,
input oserdes_clk_delayed,
input oserdes_clkdiv,
input idelay_inc,
input idelay_ce,
input idelay_ld,
input idelayctrl_refclk
);
/// INSTANCES
localparam ISERDES_DQ_DATA_RATE = "DDR";
localparam ISERDES_DQ_DATA_WIDTH = 4;
localparam ISERDES_DQ_DYN_CLKDIV_INV_EN = "FALSE";
localparam ISERDES_DQ_DYN_CLK_INV_EN = "FALSE";
localparam ISERDES_DQ_INIT_Q1 = 1'b0;
localparam ISERDES_DQ_INIT_Q2 = 1'b0;
localparam ISERDES_DQ_INIT_Q3 = 1'b0;
localparam ISERDES_DQ_INIT_Q4 = 1'b0;
localparam ISERDES_DQ_INTERFACE_TYPE = "MEMORY_DDR3";
localparam ISERDES_NUM_CE = 2;
localparam ISERDES_DQ_IOBDELAY = "IFD";
localparam ISERDES_DQ_OFB_USED = "FALSE";
localparam ISERDES_DQ_SERDES_MODE = "MASTER";
localparam ISERDES_DQ_SRVAL_Q1 = 1'b0;
localparam ISERDES_DQ_SRVAL_Q2 = 1'b0;
localparam ISERDES_DQ_SRVAL_Q3 = 1'b0;
localparam ISERDES_DQ_SRVAL_Q4 = 1'b0;
wire [BUS_WIDTH-1:0] data_in_dly;
wire [BUS_WIDTH-1:0] oserdes_dq_buf;
wire [BUS_WIDTH-1:0] oserdes_dqts_buf;
wire oserdes_dqs_buf;
wire oserdes_dqsts_buf;
wire [9:0] data_in;
wire tbyte_out;
assign mem_dq_out = oserdes_dq_buf;
assign mem_dq_ts = oserdes_dqts_buf;
assign data_in = mem_dq_in;
assign mem_dqs_out = oserdes_dqs_buf;
assign mem_dqs_ts = oserdes_dqsts_buf;
assign dqs_to_phaser = mem_dqs_in;
reg iserdes_clk_d;
always @(*)
iserdes_clk_d <= #(025) iserdes_clk;
reg idelay_ld_rst;
reg rst_r1;
reg rst_r2;
reg rst_r3;
reg rst_r4;
always @(posedge phy_clk) begin
rst_r1 <= #1 rst;
rst_r2 <= #1 rst_r1;
rst_r3 <= #1 rst_r2;
rst_r4 <= #1 rst_r3;
end
always @(posedge phy_clk) begin
if (rst)
idelay_ld_rst <= #1 1'b1;
else if (rst_r4)
idelay_ld_rst <= #1 1'b0;
end
genvar i;
generate
for ( i = 0; i != 10 && PO_DATA_CTL == "TRUE" ; i=i+1) begin : input_
if ( BITLANES[i] && !BITLANES_OUTONLY[i]) begin : iserdes_dq_
ISERDESE2 #(
.DATA_RATE ( ISERDES_DQ_DATA_RATE),
.DATA_WIDTH ( ISERDES_DQ_DATA_WIDTH),
.DYN_CLKDIV_INV_EN ( ISERDES_DQ_DYN_CLKDIV_INV_EN),
.DYN_CLK_INV_EN ( ISERDES_DQ_DYN_CLK_INV_EN),
.INIT_Q1 ( ISERDES_DQ_INIT_Q1),
.INIT_Q2 ( ISERDES_DQ_INIT_Q2),
.INIT_Q3 ( ISERDES_DQ_INIT_Q3),
.INIT_Q4 ( ISERDES_DQ_INIT_Q4),
.INTERFACE_TYPE ( ISERDES_DQ_INTERFACE_TYPE),
.NUM_CE ( ISERDES_NUM_CE),
.IOBDELAY ( ISERDES_DQ_IOBDELAY),
.OFB_USED ( ISERDES_DQ_OFB_USED),
.SERDES_MODE ( ISERDES_DQ_SERDES_MODE),
.SRVAL_Q1 ( ISERDES_DQ_SRVAL_Q1),
.SRVAL_Q2 ( ISERDES_DQ_SRVAL_Q2),
.SRVAL_Q3 ( ISERDES_DQ_SRVAL_Q3),
.SRVAL_Q4 ( ISERDES_DQ_SRVAL_Q4)
)
iserdesdq
(
.O (),
.Q1 (iserdes_dout[4*i + 3]),
.Q2 (iserdes_dout[4*i + 2]),
.Q3 (iserdes_dout[4*i + 1]),
.Q4 (iserdes_dout[4*i + 0]),
.Q5 (),
.Q6 (),
.SHIFTOUT1 (),
.SHIFTOUT2 (),
.BITSLIP (1'b0),
.CE1 (1'b1),
.CE2 (1'b1),
.CLK (iserdes_clk_d),
.CLKB (!iserdes_clk_d),
.CLKDIVP (iserdes_clkdiv),
.CLKDIV (),
.DDLY (data_in_dly[i]),
.D (data_in[i]), // dedicated route to iob for debugging
// or as needed, select with IOBDELAY
.DYNCLKDIVSEL (1'b0),
.DYNCLKSEL (1'b0),
// NOTE: OCLK is not used in this design, but is required to meet
// a design rule check in map and bitgen. Do not disconnect it.
.OCLK (oserdes_clk),
.OFB (),
.RST (1'b0),
// .RST (iserdes_rst),
.SHIFTIN1 (1'b0),
.SHIFTIN2 (1'b0)
);
localparam IDELAYE2_CINVCTRL_SEL = "FALSE";
localparam IDELAYE2_DELAY_SRC = "IDATAIN";
localparam IDELAYE2_HIGH_PERFORMANCE_MODE = "TRUE";
localparam IDELAYE2_PIPE_SEL = "FALSE";
localparam IDELAYE2_ODELAY_TYPE = "FIXED";
localparam IDELAYE2_REFCLK_FREQUENCY = 200.0;
localparam IDELAYE2_SIGNAL_PATTERN = "DATA";
(* IODELAY_GROUP = IODELAY_GRP *)
IDELAYE2 #(
.CINVCTRL_SEL ( IDELAYE2_CINVCTRL_SEL),
.DELAY_SRC ( IDELAYE2_DELAY_SRC),
.HIGH_PERFORMANCE_MODE ( IDELAYE2_HIGH_PERFORMANCE_MODE),
.IDELAY_TYPE ( IDELAYE2_IDELAY_TYPE),
.IDELAY_VALUE ( IDELAYE2_IDELAY_VALUE),
.PIPE_SEL ( IDELAYE2_PIPE_SEL),
.REFCLK_FREQUENCY ( IDELAYE2_REFCLK_FREQUENCY ),
.SIGNAL_PATTERN ( IDELAYE2_SIGNAL_PATTERN)
)
idelaye2
(
.CNTVALUEOUT (),
.DATAOUT (data_in_dly[i]),
.C (phy_clk), // automatically wired by ISE
.CE (idelay_ce),
.CINVCTRL (),
.CNTVALUEIN (5'b00000),
.DATAIN (1'b0),
.IDATAIN (data_in[i]),
.INC (idelay_inc),
.LD (idelay_ld | idelay_ld_rst),
.LDPIPEEN (1'b0),
.REGRST (rst)
);
end // iserdes_dq
else begin
assign iserdes_dout[4*i + 3] = 0;
assign iserdes_dout[4*i + 2] = 0;
assign iserdes_dout[4*i + 1] = 0;
assign iserdes_dout[4*i + 0] = 0;
end
end // input_
endgenerate // iserdes_dq_
localparam OSERDES_DQ_DATA_RATE_OQ = OSERDES_DATA_RATE;
localparam OSERDES_DQ_DATA_RATE_TQ = OSERDES_DQ_DATA_RATE_OQ;
localparam OSERDES_DQ_DATA_WIDTH = OSERDES_DATA_WIDTH;
localparam OSERDES_DQ_INIT_OQ = 1'b1;
localparam OSERDES_DQ_INIT_TQ = 1'b1;
localparam OSERDES_DQ_INTERFACE_TYPE = "DEFAULT";
localparam OSERDES_DQ_ODELAY_USED = 0;
localparam OSERDES_DQ_SERDES_MODE = "MASTER";
localparam OSERDES_DQ_SRVAL_OQ = 1'b1;
localparam OSERDES_DQ_SRVAL_TQ = 1'b1;
// note: obuf used in control path case, no ts input so width irrelevant
localparam OSERDES_DQ_TRISTATE_WIDTH = (OSERDES_DQ_DATA_RATE_OQ == "DDR") ? 4 : 1;
localparam OSERDES_DQS_DATA_RATE_OQ = "DDR";
localparam OSERDES_DQS_DATA_RATE_TQ = "DDR";
localparam OSERDES_DQS_TRISTATE_WIDTH = 4; // this is always ddr
localparam OSERDES_DQS_DATA_WIDTH = 4;
localparam ODDR_CLK_EDGE = "SAME_EDGE";
localparam OSERDES_TBYTE_CTL = "TRUE";
generate
localparam NUM_BITLANES = PO_DATA_CTL == "TRUE" ? 10 : BUS_WIDTH;
if ( PO_DATA_CTL == "TRUE" ) begin : slave_ts
OSERDESE2 #(
.DATA_RATE_OQ (OSERDES_DQ_DATA_RATE_OQ),
.DATA_RATE_TQ (OSERDES_DQ_DATA_RATE_TQ),
.DATA_WIDTH (OSERDES_DQ_DATA_WIDTH),
.INIT_OQ (OSERDES_DQ_INIT_OQ),
.INIT_TQ (OSERDES_DQ_INIT_TQ),
.SERDES_MODE (OSERDES_DQ_SERDES_MODE),
.SRVAL_OQ (OSERDES_DQ_SRVAL_OQ),
.SRVAL_TQ (OSERDES_DQ_SRVAL_TQ),
.TRISTATE_WIDTH (OSERDES_DQ_TRISTATE_WIDTH),
.TBYTE_CTL ("TRUE"),
.TBYTE_SRC ("TRUE")
)
oserdes_slave_ts
(
.OFB (),
.OQ (),
.SHIFTOUT1 (), // not extended
.SHIFTOUT2 (), // not extended
.TFB (),
.TQ (),
.CLK (oserdes_clk),
.CLKDIV (oserdes_clkdiv),
.D1 (),
.D2 (),
.D3 (),
.D4 (),
.D5 (),
.D6 (),
.OCE (1'b1),
.RST (oserdes_rst),
.SHIFTIN1 (), // not extended
.SHIFTIN2 (), // not extended
.T1 (oserdes_dqts[0]),
.T2 (oserdes_dqts[0]),
.T3 (oserdes_dqts[1]),
.T4 (oserdes_dqts[1]),
.TCE (1'b1),
.TBYTEOUT (tbyte_out),
.TBYTEIN (tbyte_out)
);
end // slave_ts
for (i = 0; i != NUM_BITLANES; i=i+1) begin : output_
if ( BITLANES[i]) begin : oserdes_dq_
if ( PO_DATA_CTL == "TRUE" ) begin : ddr
OSERDESE2 #(
.DATA_RATE_OQ (OSERDES_DQ_DATA_RATE_OQ),
.DATA_RATE_TQ (OSERDES_DQ_DATA_RATE_TQ),
.DATA_WIDTH (OSERDES_DQ_DATA_WIDTH),
.INIT_OQ (OSERDES_DQ_INIT_OQ),
.INIT_TQ (OSERDES_DQ_INIT_TQ),
.SERDES_MODE (OSERDES_DQ_SERDES_MODE),
.SRVAL_OQ (OSERDES_DQ_SRVAL_OQ),
.SRVAL_TQ (OSERDES_DQ_SRVAL_TQ),
.TRISTATE_WIDTH (OSERDES_DQ_TRISTATE_WIDTH),
.TBYTE_CTL (OSERDES_TBYTE_CTL),
.TBYTE_SRC ("FALSE")
)
oserdes_dq_i
(
.OFB (),
.OQ (oserdes_dq_buf[i]),
.SHIFTOUT1 (), // not extended
.SHIFTOUT2 (), // not extended
.TFB (),
.TQ (oserdes_dqts_buf[i]),
.CLK (oserdes_clk),
.CLKDIV (oserdes_clkdiv),
.D1 (oserdes_dq[4 * i + 0]),
.D2 (oserdes_dq[4 * i + 1]),
.D3 (oserdes_dq[4 * i + 2]),
.D4 (oserdes_dq[4 * i + 3]),
.D5 (),
.D6 (),
.OCE (1'b1),
.RST (oserdes_rst),
.SHIFTIN1 (), // not extended
.SHIFTIN2 (), // not extended
.T1 (/*oserdes_dqts[0]*/),
.T2 (/*oserdes_dqts[0]*/),
.T3 (/*oserdes_dqts[1]*/),
.T4 (/*oserdes_dqts[1]*/),
.TCE (1'b1),
.TBYTEIN (tbyte_out)
);
end
else begin : sdr
OSERDESE2 #(
.DATA_RATE_OQ (OSERDES_DQ_DATA_RATE_OQ),
.DATA_RATE_TQ (OSERDES_DQ_DATA_RATE_TQ),
.DATA_WIDTH (OSERDES_DQ_DATA_WIDTH),
.INIT_OQ (1'b0 /*OSERDES_DQ_INIT_OQ*/),
.INIT_TQ (OSERDES_DQ_INIT_TQ),
.SERDES_MODE (OSERDES_DQ_SERDES_MODE),
.SRVAL_OQ (1'b0 /*OSERDES_DQ_SRVAL_OQ*/),
.SRVAL_TQ (OSERDES_DQ_SRVAL_TQ),
.TRISTATE_WIDTH (OSERDES_DQ_TRISTATE_WIDTH)
)
oserdes_dq_i
(
.OFB (),
.OQ (oserdes_dq_buf[i]),
.SHIFTOUT1 (), // not extended
.SHIFTOUT2 (), // not extended
.TFB (),
.TQ (),
.CLK (oserdes_clk),
.CLKDIV (oserdes_clkdiv),
.D1 (oserdes_dq[4 * i + 0]),
.D2 (oserdes_dq[4 * i + 1]),
.D3 (oserdes_dq[4 * i + 2]),
.D4 (oserdes_dq[4 * i + 3]),
.D5 (),
.D6 (),
.OCE (1'b1),
.RST (oserdes_rst),
.SHIFTIN1 (), // not extended
.SHIFTIN2 (), // not extended
.T1 (),
.T2 (),
.T3 (),
.T4 (),
.TCE (1'b1)
);
end // ddr
end // oserdes_dq_
end // output_
endgenerate
generate
if ( PO_DATA_CTL == "TRUE" ) begin : dqs_gen
ODDR
#(.DDR_CLK_EDGE (ODDR_CLK_EDGE))
oddr_dqs
(
.Q (oserdes_dqs_buf),
.D1 (oserdes_dqs[0]),
.D2 (oserdes_dqs[1]),
.C (oserdes_clk_delayed),
.R (1'b0),
.S (),
.CE (1'b1)
);
ODDR
#(.DDR_CLK_EDGE (ODDR_CLK_EDGE))
oddr_dqsts
( .Q (oserdes_dqsts_buf),
.D1 (oserdes_dqsts[0]),
.D2 (oserdes_dqsts[0]),
.C (oserdes_clk_delayed),
.R (),
.S (1'b0),
.CE (1'b1)
);
end // sdr rate
else begin:null_dqs
end
endgenerate
endmodule // byte_group_io
|
/*****************************************************************
-- (c) Copyright 2011 - 2013 Xilinx, Inc. All rights reserved.
--
-- This file contains confidential and proprietary information
-- of Xilinx, Inc. and is protected under U.S. and
-- international copyright and other intellectual property
-- laws.
--
-- DISCLAIMER
-- This disclaimer is not a license and does not grant any
-- rights to the materials distributed herewith. Except as
-- otherwise provided in a valid license issued to you by
-- Xilinx, and to the maximum extent permitted by applicable
-- law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND
-- WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES
-- AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
-- BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-
-- INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and
-- (2) Xilinx shall not be liable (whether in contract or tort,
-- including negligence, or under any other theory of
-- liability) for any loss or damage of any kind or nature
-- related to, arising under or in connection with these
-- materials, including for any direct, or any indirect,
-- special, incidental, or consequential loss or damage
-- (including loss of data, profits, goodwill, or any type of
-- loss or damage suffered as a result of any action brought
-- by a third party) even if such damage or loss was
-- reasonably foreseeable or Xilinx had been advised of the
-- possibility of the same.
--
-- CRITICAL APPLICATIONS
-- Xilinx products are not designed or intended to be fail-
-- safe, or for use in any application requiring fail-safe
-- performance, such as life-support or safety devices or
-- systems, Class III medical devices, nuclear facilities,
-- applications related to the deployment of airbags, or any
-- other applications that could lead to death, personal
-- injury, or severe property or environmental damage
-- (individually and collectively, "Critical
-- Applications"). A Customer assumes the sole risk and
-- liability of any use of Xilinx products in Critical
-- Applications, subject only to applicable laws and
-- regulations governing limitations on product liability.
--
-- THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS
-- PART OF THIS FILE AT ALL TIMES.
//
//
// Owner: Gary Martin
// Revision: $Id: //depot/icm/proj/common/head/rtl/v32_cmt/rtl/phy/byte_group_io.v#4 $
// $Author: $
// $DateTime: $
// $Change: $
// Description:
// This verilog file is a paramertizable I/O termination for
// the single byte lane.
// to create a N byte-lane wide phy.
//
// History:
// Date Engineer Description
// 04/01/2010 G. Martin Initial Checkin.
//
//////////////////////////////////////////////////////////////////
*****************************************************************/
`timescale 1ps/1ps
module mig_7series_v1_9_ddr_byte_group_io #(
// bit lane existance
parameter BITLANES = 12'b1111_1111_1111,
parameter BITLANES_OUTONLY = 12'b0000_0000_0000,
parameter PO_DATA_CTL = "FALSE",
parameter OSERDES_DATA_RATE = "DDR",
parameter OSERDES_DATA_WIDTH = 4,
parameter IDELAYE2_IDELAY_TYPE = "VARIABLE",
parameter IDELAYE2_IDELAY_VALUE = 00,
parameter IODELAY_GRP = "IODELAY_MIG",
// local usage only, don't pass down
parameter BUS_WIDTH = 12,
parameter SYNTHESIS = "FALSE"
)
(
input [9:0] mem_dq_in,
output [BUS_WIDTH-1:0] mem_dq_out,
output [BUS_WIDTH-1:0] mem_dq_ts,
input mem_dqs_in,
output mem_dqs_out,
output mem_dqs_ts,
output [(4*10)-1:0] iserdes_dout, // 2 extra 12-bit lanes not used
output dqs_to_phaser,
input iserdes_clk,
input iserdes_clkb,
input iserdes_clkdiv,
input phy_clk,
input rst,
input oserdes_rst,
input iserdes_rst,
input [1:0] oserdes_dqs,
input [1:0] oserdes_dqsts,
input [(4*BUS_WIDTH)-1:0] oserdes_dq,
input [1:0] oserdes_dqts,
input oserdes_clk,
input oserdes_clk_delayed,
input oserdes_clkdiv,
input idelay_inc,
input idelay_ce,
input idelay_ld,
input idelayctrl_refclk
);
/// INSTANCES
localparam ISERDES_DQ_DATA_RATE = "DDR";
localparam ISERDES_DQ_DATA_WIDTH = 4;
localparam ISERDES_DQ_DYN_CLKDIV_INV_EN = "FALSE";
localparam ISERDES_DQ_DYN_CLK_INV_EN = "FALSE";
localparam ISERDES_DQ_INIT_Q1 = 1'b0;
localparam ISERDES_DQ_INIT_Q2 = 1'b0;
localparam ISERDES_DQ_INIT_Q3 = 1'b0;
localparam ISERDES_DQ_INIT_Q4 = 1'b0;
localparam ISERDES_DQ_INTERFACE_TYPE = "MEMORY_DDR3";
localparam ISERDES_NUM_CE = 2;
localparam ISERDES_DQ_IOBDELAY = "IFD";
localparam ISERDES_DQ_OFB_USED = "FALSE";
localparam ISERDES_DQ_SERDES_MODE = "MASTER";
localparam ISERDES_DQ_SRVAL_Q1 = 1'b0;
localparam ISERDES_DQ_SRVAL_Q2 = 1'b0;
localparam ISERDES_DQ_SRVAL_Q3 = 1'b0;
localparam ISERDES_DQ_SRVAL_Q4 = 1'b0;
wire [BUS_WIDTH-1:0] data_in_dly;
wire [BUS_WIDTH-1:0] oserdes_dq_buf;
wire [BUS_WIDTH-1:0] oserdes_dqts_buf;
wire oserdes_dqs_buf;
wire oserdes_dqsts_buf;
wire [9:0] data_in;
wire tbyte_out;
assign mem_dq_out = oserdes_dq_buf;
assign mem_dq_ts = oserdes_dqts_buf;
assign data_in = mem_dq_in;
assign mem_dqs_out = oserdes_dqs_buf;
assign mem_dqs_ts = oserdes_dqsts_buf;
assign dqs_to_phaser = mem_dqs_in;
reg iserdes_clk_d;
always @(*)
iserdes_clk_d <= #(025) iserdes_clk;
reg idelay_ld_rst;
reg rst_r1;
reg rst_r2;
reg rst_r3;
reg rst_r4;
always @(posedge phy_clk) begin
rst_r1 <= #1 rst;
rst_r2 <= #1 rst_r1;
rst_r3 <= #1 rst_r2;
rst_r4 <= #1 rst_r3;
end
always @(posedge phy_clk) begin
if (rst)
idelay_ld_rst <= #1 1'b1;
else if (rst_r4)
idelay_ld_rst <= #1 1'b0;
end
genvar i;
generate
for ( i = 0; i != 10 && PO_DATA_CTL == "TRUE" ; i=i+1) begin : input_
if ( BITLANES[i] && !BITLANES_OUTONLY[i]) begin : iserdes_dq_
ISERDESE2 #(
.DATA_RATE ( ISERDES_DQ_DATA_RATE),
.DATA_WIDTH ( ISERDES_DQ_DATA_WIDTH),
.DYN_CLKDIV_INV_EN ( ISERDES_DQ_DYN_CLKDIV_INV_EN),
.DYN_CLK_INV_EN ( ISERDES_DQ_DYN_CLK_INV_EN),
.INIT_Q1 ( ISERDES_DQ_INIT_Q1),
.INIT_Q2 ( ISERDES_DQ_INIT_Q2),
.INIT_Q3 ( ISERDES_DQ_INIT_Q3),
.INIT_Q4 ( ISERDES_DQ_INIT_Q4),
.INTERFACE_TYPE ( ISERDES_DQ_INTERFACE_TYPE),
.NUM_CE ( ISERDES_NUM_CE),
.IOBDELAY ( ISERDES_DQ_IOBDELAY),
.OFB_USED ( ISERDES_DQ_OFB_USED),
.SERDES_MODE ( ISERDES_DQ_SERDES_MODE),
.SRVAL_Q1 ( ISERDES_DQ_SRVAL_Q1),
.SRVAL_Q2 ( ISERDES_DQ_SRVAL_Q2),
.SRVAL_Q3 ( ISERDES_DQ_SRVAL_Q3),
.SRVAL_Q4 ( ISERDES_DQ_SRVAL_Q4)
)
iserdesdq
(
.O (),
.Q1 (iserdes_dout[4*i + 3]),
.Q2 (iserdes_dout[4*i + 2]),
.Q3 (iserdes_dout[4*i + 1]),
.Q4 (iserdes_dout[4*i + 0]),
.Q5 (),
.Q6 (),
.SHIFTOUT1 (),
.SHIFTOUT2 (),
.BITSLIP (1'b0),
.CE1 (1'b1),
.CE2 (1'b1),
.CLK (iserdes_clk_d),
.CLKB (!iserdes_clk_d),
.CLKDIVP (iserdes_clkdiv),
.CLKDIV (),
.DDLY (data_in_dly[i]),
.D (data_in[i]), // dedicated route to iob for debugging
// or as needed, select with IOBDELAY
.DYNCLKDIVSEL (1'b0),
.DYNCLKSEL (1'b0),
// NOTE: OCLK is not used in this design, but is required to meet
// a design rule check in map and bitgen. Do not disconnect it.
.OCLK (oserdes_clk),
.OFB (),
.RST (1'b0),
// .RST (iserdes_rst),
.SHIFTIN1 (1'b0),
.SHIFTIN2 (1'b0)
);
localparam IDELAYE2_CINVCTRL_SEL = "FALSE";
localparam IDELAYE2_DELAY_SRC = "IDATAIN";
localparam IDELAYE2_HIGH_PERFORMANCE_MODE = "TRUE";
localparam IDELAYE2_PIPE_SEL = "FALSE";
localparam IDELAYE2_ODELAY_TYPE = "FIXED";
localparam IDELAYE2_REFCLK_FREQUENCY = 200.0;
localparam IDELAYE2_SIGNAL_PATTERN = "DATA";
(* IODELAY_GROUP = IODELAY_GRP *)
IDELAYE2 #(
.CINVCTRL_SEL ( IDELAYE2_CINVCTRL_SEL),
.DELAY_SRC ( IDELAYE2_DELAY_SRC),
.HIGH_PERFORMANCE_MODE ( IDELAYE2_HIGH_PERFORMANCE_MODE),
.IDELAY_TYPE ( IDELAYE2_IDELAY_TYPE),
.IDELAY_VALUE ( IDELAYE2_IDELAY_VALUE),
.PIPE_SEL ( IDELAYE2_PIPE_SEL),
.REFCLK_FREQUENCY ( IDELAYE2_REFCLK_FREQUENCY ),
.SIGNAL_PATTERN ( IDELAYE2_SIGNAL_PATTERN)
)
idelaye2
(
.CNTVALUEOUT (),
.DATAOUT (data_in_dly[i]),
.C (phy_clk), // automatically wired by ISE
.CE (idelay_ce),
.CINVCTRL (),
.CNTVALUEIN (5'b00000),
.DATAIN (1'b0),
.IDATAIN (data_in[i]),
.INC (idelay_inc),
.LD (idelay_ld | idelay_ld_rst),
.LDPIPEEN (1'b0),
.REGRST (rst)
);
end // iserdes_dq
else begin
assign iserdes_dout[4*i + 3] = 0;
assign iserdes_dout[4*i + 2] = 0;
assign iserdes_dout[4*i + 1] = 0;
assign iserdes_dout[4*i + 0] = 0;
end
end // input_
endgenerate // iserdes_dq_
localparam OSERDES_DQ_DATA_RATE_OQ = OSERDES_DATA_RATE;
localparam OSERDES_DQ_DATA_RATE_TQ = OSERDES_DQ_DATA_RATE_OQ;
localparam OSERDES_DQ_DATA_WIDTH = OSERDES_DATA_WIDTH;
localparam OSERDES_DQ_INIT_OQ = 1'b1;
localparam OSERDES_DQ_INIT_TQ = 1'b1;
localparam OSERDES_DQ_INTERFACE_TYPE = "DEFAULT";
localparam OSERDES_DQ_ODELAY_USED = 0;
localparam OSERDES_DQ_SERDES_MODE = "MASTER";
localparam OSERDES_DQ_SRVAL_OQ = 1'b1;
localparam OSERDES_DQ_SRVAL_TQ = 1'b1;
// note: obuf used in control path case, no ts input so width irrelevant
localparam OSERDES_DQ_TRISTATE_WIDTH = (OSERDES_DQ_DATA_RATE_OQ == "DDR") ? 4 : 1;
localparam OSERDES_DQS_DATA_RATE_OQ = "DDR";
localparam OSERDES_DQS_DATA_RATE_TQ = "DDR";
localparam OSERDES_DQS_TRISTATE_WIDTH = 4; // this is always ddr
localparam OSERDES_DQS_DATA_WIDTH = 4;
localparam ODDR_CLK_EDGE = "SAME_EDGE";
localparam OSERDES_TBYTE_CTL = "TRUE";
generate
localparam NUM_BITLANES = PO_DATA_CTL == "TRUE" ? 10 : BUS_WIDTH;
if ( PO_DATA_CTL == "TRUE" ) begin : slave_ts
OSERDESE2 #(
.DATA_RATE_OQ (OSERDES_DQ_DATA_RATE_OQ),
.DATA_RATE_TQ (OSERDES_DQ_DATA_RATE_TQ),
.DATA_WIDTH (OSERDES_DQ_DATA_WIDTH),
.INIT_OQ (OSERDES_DQ_INIT_OQ),
.INIT_TQ (OSERDES_DQ_INIT_TQ),
.SERDES_MODE (OSERDES_DQ_SERDES_MODE),
.SRVAL_OQ (OSERDES_DQ_SRVAL_OQ),
.SRVAL_TQ (OSERDES_DQ_SRVAL_TQ),
.TRISTATE_WIDTH (OSERDES_DQ_TRISTATE_WIDTH),
.TBYTE_CTL ("TRUE"),
.TBYTE_SRC ("TRUE")
)
oserdes_slave_ts
(
.OFB (),
.OQ (),
.SHIFTOUT1 (), // not extended
.SHIFTOUT2 (), // not extended
.TFB (),
.TQ (),
.CLK (oserdes_clk),
.CLKDIV (oserdes_clkdiv),
.D1 (),
.D2 (),
.D3 (),
.D4 (),
.D5 (),
.D6 (),
.OCE (1'b1),
.RST (oserdes_rst),
.SHIFTIN1 (), // not extended
.SHIFTIN2 (), // not extended
.T1 (oserdes_dqts[0]),
.T2 (oserdes_dqts[0]),
.T3 (oserdes_dqts[1]),
.T4 (oserdes_dqts[1]),
.TCE (1'b1),
.TBYTEOUT (tbyte_out),
.TBYTEIN (tbyte_out)
);
end // slave_ts
for (i = 0; i != NUM_BITLANES; i=i+1) begin : output_
if ( BITLANES[i]) begin : oserdes_dq_
if ( PO_DATA_CTL == "TRUE" ) begin : ddr
OSERDESE2 #(
.DATA_RATE_OQ (OSERDES_DQ_DATA_RATE_OQ),
.DATA_RATE_TQ (OSERDES_DQ_DATA_RATE_TQ),
.DATA_WIDTH (OSERDES_DQ_DATA_WIDTH),
.INIT_OQ (OSERDES_DQ_INIT_OQ),
.INIT_TQ (OSERDES_DQ_INIT_TQ),
.SERDES_MODE (OSERDES_DQ_SERDES_MODE),
.SRVAL_OQ (OSERDES_DQ_SRVAL_OQ),
.SRVAL_TQ (OSERDES_DQ_SRVAL_TQ),
.TRISTATE_WIDTH (OSERDES_DQ_TRISTATE_WIDTH),
.TBYTE_CTL (OSERDES_TBYTE_CTL),
.TBYTE_SRC ("FALSE")
)
oserdes_dq_i
(
.OFB (),
.OQ (oserdes_dq_buf[i]),
.SHIFTOUT1 (), // not extended
.SHIFTOUT2 (), // not extended
.TFB (),
.TQ (oserdes_dqts_buf[i]),
.CLK (oserdes_clk),
.CLKDIV (oserdes_clkdiv),
.D1 (oserdes_dq[4 * i + 0]),
.D2 (oserdes_dq[4 * i + 1]),
.D3 (oserdes_dq[4 * i + 2]),
.D4 (oserdes_dq[4 * i + 3]),
.D5 (),
.D6 (),
.OCE (1'b1),
.RST (oserdes_rst),
.SHIFTIN1 (), // not extended
.SHIFTIN2 (), // not extended
.T1 (/*oserdes_dqts[0]*/),
.T2 (/*oserdes_dqts[0]*/),
.T3 (/*oserdes_dqts[1]*/),
.T4 (/*oserdes_dqts[1]*/),
.TCE (1'b1),
.TBYTEIN (tbyte_out)
);
end
else begin : sdr
OSERDESE2 #(
.DATA_RATE_OQ (OSERDES_DQ_DATA_RATE_OQ),
.DATA_RATE_TQ (OSERDES_DQ_DATA_RATE_TQ),
.DATA_WIDTH (OSERDES_DQ_DATA_WIDTH),
.INIT_OQ (1'b0 /*OSERDES_DQ_INIT_OQ*/),
.INIT_TQ (OSERDES_DQ_INIT_TQ),
.SERDES_MODE (OSERDES_DQ_SERDES_MODE),
.SRVAL_OQ (1'b0 /*OSERDES_DQ_SRVAL_OQ*/),
.SRVAL_TQ (OSERDES_DQ_SRVAL_TQ),
.TRISTATE_WIDTH (OSERDES_DQ_TRISTATE_WIDTH)
)
oserdes_dq_i
(
.OFB (),
.OQ (oserdes_dq_buf[i]),
.SHIFTOUT1 (), // not extended
.SHIFTOUT2 (), // not extended
.TFB (),
.TQ (),
.CLK (oserdes_clk),
.CLKDIV (oserdes_clkdiv),
.D1 (oserdes_dq[4 * i + 0]),
.D2 (oserdes_dq[4 * i + 1]),
.D3 (oserdes_dq[4 * i + 2]),
.D4 (oserdes_dq[4 * i + 3]),
.D5 (),
.D6 (),
.OCE (1'b1),
.RST (oserdes_rst),
.SHIFTIN1 (), // not extended
.SHIFTIN2 (), // not extended
.T1 (),
.T2 (),
.T3 (),
.T4 (),
.TCE (1'b1)
);
end // ddr
end // oserdes_dq_
end // output_
endgenerate
generate
if ( PO_DATA_CTL == "TRUE" ) begin : dqs_gen
ODDR
#(.DDR_CLK_EDGE (ODDR_CLK_EDGE))
oddr_dqs
(
.Q (oserdes_dqs_buf),
.D1 (oserdes_dqs[0]),
.D2 (oserdes_dqs[1]),
.C (oserdes_clk_delayed),
.R (1'b0),
.S (),
.CE (1'b1)
);
ODDR
#(.DDR_CLK_EDGE (ODDR_CLK_EDGE))
oddr_dqsts
( .Q (oserdes_dqsts_buf),
.D1 (oserdes_dqsts[0]),
.D2 (oserdes_dqsts[0]),
.C (oserdes_clk_delayed),
.R (),
.S (1'b0),
.CE (1'b1)
);
end // sdr rate
else begin:null_dqs
end
endgenerate
endmodule // byte_group_io
|
/**********************************************************
-- (c) Copyright 2011 - 2013 Xilinx, Inc. All rights reserved.
--
-- This file contains confidential and proprietary information
-- of Xilinx, Inc. and is protected under U.S. and
-- international copyright and other intellectual property
-- laws.
--
-- DISCLAIMER
-- This disclaimer is not a license and does not grant any
-- rights to the materials distributed herewith. Except as
-- otherwise provided in a valid license issued to you by
-- Xilinx, and to the maximum extent permitted by applicable
-- law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND
-- WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES
-- AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
-- BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-
-- INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and
-- (2) Xilinx shall not be liable (whether in contract or tort,
-- including negligence, or under any other theory of
-- liability) for any loss or damage of any kind or nature
-- related to, arising under or in connection with these
-- materials, including for any direct, or any indirect,
-- special, incidental, or consequential loss or damage
-- (including loss of data, profits, goodwill, or any type of
-- loss or damage suffered as a result of any action brought
-- by a third party) even if such damage or loss was
-- reasonably foreseeable or Xilinx had been advised of the
-- possibility of the same.
--
-- CRITICAL APPLICATIONS
-- Xilinx products are not designed or intended to be fail-
-- safe, or for use in any application requiring fail-safe
-- performance, such as life-support or safety devices or
-- systems, Class III medical devices, nuclear facilities,
-- applications related to the deployment of airbags, or any
-- other applications that could lead to death, personal
-- injury, or severe property or environmental damage
-- (individually and collectively, "Critical
-- Applications"). A Customer assumes the sole risk and
-- liability of any use of Xilinx products in Critical
-- Applications, subject only to applicable laws and
-- regulations governing limitations on product liability.
--
-- THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS
-- PART OF THIS FILE AT ALL TIMES.
//
// THIS NOTICE MUST BE RETAINED AS PART OF THIS FILE AT ALL TIMES.
//
//
// Owner: Gary Martin
// Revision: $Id: //depot/icm/proj/common/head/rtl/v32_cmt/rtl/phy/phy_4lanes.v#6 $
// $Author: gary $
// $DateTime: 2010/05/11 18:05:17 $
// $Change: 490882 $
// Description:
// This verilog file is the parameterizable 4-byte lane phy primitive top
// This module may be ganged to create an N-lane phy.
//
// History:
// Date Engineer Description
// 04/01/2010 G. Martin Initial Checkin.
//
///////////////////////////////////////////////////////////
**********************************************************/
`timescale 1ps/1ps
`define PC_DATA_OFFSET_RANGE 22:17
module mig_7series_v1_9_ddr_phy_4lanes #(
parameter GENERATE_IDELAYCTRL = "TRUE",
parameter IODELAY_GRP = "IODELAY_MIG",
parameter BANK_TYPE = "HP_IO", // # = "HP_IO", "HPL_IO", "HR_IO", "HRL_IO"
parameter BYTELANES_DDR_CK = 24'b0010_0010_0010_0010_0010_0010,
parameter NUM_DDR_CK = 1,
// next three parameter fields correspond to byte lanes for lane order DCBA
parameter BYTE_LANES = 4'b1111, // lane existence, one per lane
parameter DATA_CTL_N = 4'b1111, // data or control, per lane
parameter BITLANES = 48'hffff_ffff_ffff,
parameter BITLANES_OUTONLY = 48'h0000_0000_0000,
parameter LANE_REMAP = 16'h3210,// 4-bit index
// used to rewire to one of four
// input/output buss lanes
// example: 0321 remaps lanes as:
// D->A
// C->D
// B->C
// A->B
parameter LAST_BANK = "FALSE",
parameter USE_PRE_POST_FIFO = "FALSE",
parameter RCLK_SELECT_LANE = "B",
parameter real TCK = 0.00,
parameter SYNTHESIS = "FALSE",
parameter PO_CTL_COARSE_BYPASS = "FALSE",
parameter PO_FINE_DELAY = 0,
parameter PI_SEL_CLK_OFFSET = 0,
// phy_control paramter used in other paramsters
parameter PC_CLK_RATIO = 4,
//phaser_in parameters
parameter A_PI_FREQ_REF_DIV = "NONE",
parameter A_PI_CLKOUT_DIV = 2,
parameter A_PI_BURST_MODE = "TRUE",
parameter A_PI_OUTPUT_CLK_SRC = "DELAYED_REF" , //"DELAYED_REF",
parameter A_PI_FINE_DELAY = 60,
parameter A_PI_SYNC_IN_DIV_RST = "TRUE",
parameter B_PI_FREQ_REF_DIV = A_PI_FREQ_REF_DIV,
parameter B_PI_CLKOUT_DIV = A_PI_CLKOUT_DIV,
parameter B_PI_BURST_MODE = A_PI_BURST_MODE,
parameter B_PI_OUTPUT_CLK_SRC = A_PI_OUTPUT_CLK_SRC,
parameter B_PI_FINE_DELAY = A_PI_FINE_DELAY,
parameter B_PI_SYNC_IN_DIV_RST = A_PI_SYNC_IN_DIV_RST,
parameter C_PI_FREQ_REF_DIV = A_PI_FREQ_REF_DIV,
parameter C_PI_CLKOUT_DIV = A_PI_CLKOUT_DIV,
parameter C_PI_BURST_MODE = A_PI_BURST_MODE,
parameter C_PI_OUTPUT_CLK_SRC = A_PI_OUTPUT_CLK_SRC,
parameter C_PI_FINE_DELAY = 0,
parameter C_PI_SYNC_IN_DIV_RST = A_PI_SYNC_IN_DIV_RST,
parameter D_PI_FREQ_REF_DIV = A_PI_FREQ_REF_DIV,
parameter D_PI_CLKOUT_DIV = A_PI_CLKOUT_DIV,
parameter D_PI_BURST_MODE = A_PI_BURST_MODE,
parameter D_PI_OUTPUT_CLK_SRC = A_PI_OUTPUT_CLK_SRC,
parameter D_PI_FINE_DELAY = 0,
parameter D_PI_SYNC_IN_DIV_RST = A_PI_SYNC_IN_DIV_RST,
//phaser_out parameters
parameter A_PO_CLKOUT_DIV = (DATA_CTL_N[0] == 0) ? PC_CLK_RATIO : 2,
parameter A_PO_FINE_DELAY = PO_FINE_DELAY,
parameter A_PO_COARSE_DELAY = 0,
parameter A_PO_OCLK_DELAY = 0,
parameter A_PO_OCLKDELAY_INV = "FALSE",
parameter A_PO_OUTPUT_CLK_SRC = "DELAYED_REF",
parameter A_PO_SYNC_IN_DIV_RST = "TRUE",
//parameter A_PO_SYNC_IN_DIV_RST = "FALSE",
parameter B_PO_CLKOUT_DIV = (DATA_CTL_N[1] == 0) ? PC_CLK_RATIO : 2,
parameter B_PO_FINE_DELAY = PO_FINE_DELAY,
parameter B_PO_COARSE_DELAY = A_PO_COARSE_DELAY,
parameter B_PO_OCLK_DELAY = A_PO_OCLK_DELAY,
parameter B_PO_OCLKDELAY_INV = A_PO_OCLKDELAY_INV,
parameter B_PO_OUTPUT_CLK_SRC = A_PO_OUTPUT_CLK_SRC,
parameter B_PO_SYNC_IN_DIV_RST = A_PO_SYNC_IN_DIV_RST,
parameter C_PO_CLKOUT_DIV = (DATA_CTL_N[2] == 0) ? PC_CLK_RATIO : 2,
parameter C_PO_FINE_DELAY = PO_FINE_DELAY,
parameter C_PO_COARSE_DELAY = A_PO_COARSE_DELAY,
parameter C_PO_OCLK_DELAY = A_PO_OCLK_DELAY,
parameter C_PO_OCLKDELAY_INV = A_PO_OCLKDELAY_INV,
parameter C_PO_OUTPUT_CLK_SRC = A_PO_OUTPUT_CLK_SRC,
parameter C_PO_SYNC_IN_DIV_RST = A_PO_SYNC_IN_DIV_RST,
parameter D_PO_CLKOUT_DIV = (DATA_CTL_N[3] == 0) ? PC_CLK_RATIO : 2,
parameter D_PO_FINE_DELAY = PO_FINE_DELAY,
parameter D_PO_COARSE_DELAY = A_PO_COARSE_DELAY,
parameter D_PO_OCLK_DELAY = A_PO_OCLK_DELAY,
parameter D_PO_OCLKDELAY_INV = A_PO_OCLKDELAY_INV,
parameter D_PO_OUTPUT_CLK_SRC = A_PO_OUTPUT_CLK_SRC,
parameter D_PO_SYNC_IN_DIV_RST = A_PO_SYNC_IN_DIV_RST,
parameter A_IDELAYE2_IDELAY_TYPE = "VARIABLE",
parameter A_IDELAYE2_IDELAY_VALUE = 00,
parameter B_IDELAYE2_IDELAY_TYPE = A_IDELAYE2_IDELAY_TYPE,
parameter B_IDELAYE2_IDELAY_VALUE = A_IDELAYE2_IDELAY_VALUE,
parameter C_IDELAYE2_IDELAY_TYPE = A_IDELAYE2_IDELAY_TYPE,
parameter C_IDELAYE2_IDELAY_VALUE = A_IDELAYE2_IDELAY_VALUE,
parameter D_IDELAYE2_IDELAY_TYPE = A_IDELAYE2_IDELAY_TYPE,
parameter D_IDELAYE2_IDELAY_VALUE = A_IDELAYE2_IDELAY_VALUE,
// phy_control parameters
parameter PC_BURST_MODE = "TRUE",
parameter PC_DATA_CTL_N = DATA_CTL_N,
parameter PC_CMD_OFFSET = 0,
parameter PC_RD_CMD_OFFSET_0 = 0,
parameter PC_RD_CMD_OFFSET_1 = 0,
parameter PC_RD_CMD_OFFSET_2 = 0,
parameter PC_RD_CMD_OFFSET_3 = 0,
parameter PC_CO_DURATION = 1,
parameter PC_DI_DURATION = 1,
parameter PC_DO_DURATION = 1,
parameter PC_RD_DURATION_0 = 0,
parameter PC_RD_DURATION_1 = 0,
parameter PC_RD_DURATION_2 = 0,
parameter PC_RD_DURATION_3 = 0,
parameter PC_WR_CMD_OFFSET_0 = 5,
parameter PC_WR_CMD_OFFSET_1 = 5,
parameter PC_WR_CMD_OFFSET_2 = 5,
parameter PC_WR_CMD_OFFSET_3 = 5,
parameter PC_WR_DURATION_0 = 6,
parameter PC_WR_DURATION_1 = 6,
parameter PC_WR_DURATION_2 = 6,
parameter PC_WR_DURATION_3 = 6,
parameter PC_AO_WRLVL_EN = 0,
parameter PC_AO_TOGGLE = 4'b0101, // odd bits are toggle (CKE)
parameter PC_FOUR_WINDOW_CLOCKS = 63,
parameter PC_EVENTS_DELAY = 18,
parameter PC_PHY_COUNT_EN = "TRUE",
parameter PC_SYNC_MODE = "TRUE",
parameter PC_DISABLE_SEQ_MATCH = "TRUE",
parameter PC_MULTI_REGION = "FALSE",
// io fifo parameters
parameter A_OF_ARRAY_MODE = (DATA_CTL_N[0] == 1) ? "ARRAY_MODE_8_X_4" : "ARRAY_MODE_4_X_4",
parameter B_OF_ARRAY_MODE = (DATA_CTL_N[1] == 1) ? "ARRAY_MODE_8_X_4" : "ARRAY_MODE_4_X_4",
parameter C_OF_ARRAY_MODE = (DATA_CTL_N[2] == 1) ? "ARRAY_MODE_8_X_4" : "ARRAY_MODE_4_X_4",
parameter D_OF_ARRAY_MODE = (DATA_CTL_N[3] == 1) ? "ARRAY_MODE_8_X_4" : "ARRAY_MODE_4_X_4",
parameter OF_ALMOST_EMPTY_VALUE = 1,
parameter OF_ALMOST_FULL_VALUE = 1,
parameter OF_OUTPUT_DISABLE = "TRUE",
parameter OF_SYNCHRONOUS_MODE = PC_SYNC_MODE,
parameter A_OS_DATA_RATE = "DDR",
parameter A_OS_DATA_WIDTH = 4,
parameter B_OS_DATA_RATE = A_OS_DATA_RATE,
parameter B_OS_DATA_WIDTH = A_OS_DATA_WIDTH,
parameter C_OS_DATA_RATE = A_OS_DATA_RATE,
parameter C_OS_DATA_WIDTH = A_OS_DATA_WIDTH,
parameter D_OS_DATA_RATE = A_OS_DATA_RATE,
parameter D_OS_DATA_WIDTH = A_OS_DATA_WIDTH,
parameter A_IF_ARRAY_MODE = "ARRAY_MODE_4_X_8",
parameter B_IF_ARRAY_MODE = A_IF_ARRAY_MODE,
parameter C_IF_ARRAY_MODE = A_IF_ARRAY_MODE,
parameter D_IF_ARRAY_MODE = A_IF_ARRAY_MODE,
parameter IF_ALMOST_EMPTY_VALUE = 1,
parameter IF_ALMOST_FULL_VALUE = 1,
parameter IF_SYNCHRONOUS_MODE = PC_SYNC_MODE,
// this is used locally, not for external pushdown
// NOTE: the 0+ is needed in each to coerce to integer for addition.
// otherwise 4x 1'b values are added producing a 1'b value.
parameter HIGHEST_LANE = LAST_BANK == "FALSE" ? 4 : (BYTE_LANES[3] ? 4 : BYTE_LANES[2] ? 3 : BYTE_LANES[1] ? 2 : 1),
parameter N_CTL_LANES = ((0+(!DATA_CTL_N[0]) & BYTE_LANES[0]) + (0+(!DATA_CTL_N[1]) & BYTE_LANES[1]) + (0+(!DATA_CTL_N[2]) & BYTE_LANES[2]) + (0+(!DATA_CTL_N[3]) & BYTE_LANES[3])),
parameter N_BYTE_LANES = (0+BYTE_LANES[0]) + (0+BYTE_LANES[1]) + (0+BYTE_LANES[2]) + (0+BYTE_LANES[3]),
parameter N_DATA_LANES = N_BYTE_LANES - N_CTL_LANES,
// assume odt per rank + any declared cke's
parameter AUXOUT_WIDTH = 4,
parameter LP_DDR_CK_WIDTH = 2
,parameter CKE_ODT_AUX = "FALSE"
)
(
//`include "phy.vh"
input rst,
input phy_clk,
input phy_ctl_clk,
input freq_refclk,
input mem_refclk,
input mem_refclk_div4,
input pll_lock,
input sync_pulse,
input idelayctrl_refclk,
input [HIGHEST_LANE*80-1:0] phy_dout,
input phy_cmd_wr_en,
input phy_data_wr_en,
input phy_rd_en,
input phy_ctl_mstr_empty,
input [31:0] phy_ctl_wd,
input [`PC_DATA_OFFSET_RANGE] data_offset,
input phy_ctl_wr,
input if_empty_def,
input phyGo,
input input_sink,
output [(LP_DDR_CK_WIDTH*24)-1:0] ddr_clk, // to memory
output rclk,
output if_a_empty,
output if_empty,
output byte_rd_en,
output if_empty_or,
output if_empty_and,
output of_ctl_a_full,
output of_data_a_full,
output of_ctl_full,
output of_data_full,
output pre_data_a_full,
output [HIGHEST_LANE*80-1:0]phy_din, // assume input bus same size as output bus
output phy_ctl_empty,
output phy_ctl_a_full,
output phy_ctl_full,
output [HIGHEST_LANE*12-1:0]mem_dq_out,
output [HIGHEST_LANE*12-1:0]mem_dq_ts,
input [HIGHEST_LANE*10-1:0]mem_dq_in,
output [HIGHEST_LANE-1:0] mem_dqs_out,
output [HIGHEST_LANE-1:0] mem_dqs_ts,
input [HIGHEST_LANE-1:0] mem_dqs_in,
input [1:0] byte_rd_en_oth_banks,
output [AUXOUT_WIDTH-1:0] aux_out,
output reg rst_out = 0,
output reg mcGo=0,
output phy_ctl_ready,
output ref_dll_lock,
input if_rst,
input phy_read_calib,
input phy_write_calib,
input idelay_inc,
input idelay_ce,
input idelay_ld,
input [2:0] calib_sel,
input calib_zero_ctrl,
input [HIGHEST_LANE-1:0] calib_zero_lanes,
input calib_in_common,
input po_fine_enable,
input po_coarse_enable,
input po_fine_inc,
input po_coarse_inc,
input po_counter_load_en,
input po_counter_read_en,
input [8:0] po_counter_load_val,
input po_sel_fine_oclk_delay,
output reg po_coarse_overflow,
output reg po_fine_overflow,
output reg [8:0] po_counter_read_val,
input pi_rst_dqs_find,
input pi_fine_enable,
input pi_fine_inc,
input pi_counter_load_en,
input pi_counter_read_en,
input [5:0] pi_counter_load_val,
output reg pi_fine_overflow,
output reg [5:0] pi_counter_read_val,
output reg pi_dqs_found,
output pi_dqs_found_all,
output pi_dqs_found_any,
output [HIGHEST_LANE-1:0] pi_phase_locked_lanes,
output [HIGHEST_LANE-1:0] pi_dqs_found_lanes,
output reg pi_dqs_out_of_range,
output reg pi_phase_locked,
output pi_phase_locked_all
);
localparam DATA_CTL_A = (~DATA_CTL_N[0]);
localparam DATA_CTL_B = (~DATA_CTL_N[1]);
localparam DATA_CTL_C = (~DATA_CTL_N[2]);
localparam DATA_CTL_D = (~DATA_CTL_N[3]);
localparam PRESENT_CTL_A = BYTE_LANES[0] && ! DATA_CTL_N[0];
localparam PRESENT_CTL_B = BYTE_LANES[1] && ! DATA_CTL_N[1];
localparam PRESENT_CTL_C = BYTE_LANES[2] && ! DATA_CTL_N[2];
localparam PRESENT_CTL_D = BYTE_LANES[3] && ! DATA_CTL_N[3];
localparam PRESENT_DATA_A = BYTE_LANES[0] && DATA_CTL_N[0];
localparam PRESENT_DATA_B = BYTE_LANES[1] && DATA_CTL_N[1];
localparam PRESENT_DATA_C = BYTE_LANES[2] && DATA_CTL_N[2];
localparam PRESENT_DATA_D = BYTE_LANES[3] && DATA_CTL_N[3];
localparam PC_DATA_CTL_A = (DATA_CTL_A) ? "FALSE" : "TRUE";
localparam PC_DATA_CTL_B = (DATA_CTL_B) ? "FALSE" : "TRUE";
localparam PC_DATA_CTL_C = (DATA_CTL_C) ? "FALSE" : "TRUE";
localparam PC_DATA_CTL_D = (DATA_CTL_D) ? "FALSE" : "TRUE";
localparam A_PO_COARSE_BYPASS = (DATA_CTL_A) ? PO_CTL_COARSE_BYPASS : "FALSE";
localparam B_PO_COARSE_BYPASS = (DATA_CTL_B) ? PO_CTL_COARSE_BYPASS : "FALSE";
localparam C_PO_COARSE_BYPASS = (DATA_CTL_C) ? PO_CTL_COARSE_BYPASS : "FALSE";
localparam D_PO_COARSE_BYPASS = (DATA_CTL_D) ? PO_CTL_COARSE_BYPASS : "FALSE";
localparam IO_A_START = 41;
localparam IO_A_END = 40;
localparam IO_B_START = 43;
localparam IO_B_END = 42;
localparam IO_C_START = 45;
localparam IO_C_END = 44;
localparam IO_D_START = 47;
localparam IO_D_END = 46;
localparam IO_A_X_START = (HIGHEST_LANE * 10) + 1;
localparam IO_A_X_END = (IO_A_X_START-1);
localparam IO_B_X_START = (IO_A_X_START + 2);
localparam IO_B_X_END = (IO_B_X_START -1);
localparam IO_C_X_START = (IO_B_X_START + 2);
localparam IO_C_X_END = (IO_C_X_START -1);
localparam IO_D_X_START = (IO_C_X_START + 2);
localparam IO_D_X_END = (IO_D_X_START -1);
localparam MSB_BURST_PEND_PO = 3;
localparam MSB_BURST_PEND_PI = 7;
localparam MSB_RANK_SEL_I = MSB_BURST_PEND_PI + 8;
localparam PHASER_CTL_BUS_WIDTH = MSB_RANK_SEL_I + 1;
wire [1:0] oserdes_dqs;
wire [1:0] oserdes_dqs_ts;
wire [1:0] oserdes_dq_ts;
wire [PHASER_CTL_BUS_WIDTH-1:0] phaser_ctl_bus;
wire [7:0] in_rank;
wire [11:0] IO_A;
wire [11:0] IO_B;
wire [11:0] IO_C;
wire [11:0] IO_D;
wire [319:0] phy_din_remap;
reg A_po_counter_read_en;
wire [8:0] A_po_counter_read_val;
reg A_pi_counter_read_en;
wire [5:0] A_pi_counter_read_val;
wire A_pi_fine_overflow;
wire A_po_coarse_overflow;
wire A_po_fine_overflow;
wire A_pi_dqs_found;
wire A_pi_dqs_out_of_range;
wire A_pi_phase_locked;
wire A_pi_iserdes_rst;
reg A_pi_fine_enable;
reg A_pi_fine_inc;
reg A_pi_counter_load_en;
reg [5:0] A_pi_counter_load_val;
reg A_pi_rst_dqs_find;
reg A_po_fine_enable;
reg A_po_coarse_enable;
(* keep = "true", max_fanout = 3 *) reg A_po_fine_inc /* synthesis syn_maxfan = 3 */;
reg A_po_sel_fine_oclk_delay;
reg A_po_coarse_inc;
reg A_po_counter_load_en;
reg [8:0] A_po_counter_load_val;
wire A_rclk;
reg A_idelay_ce;
reg A_idelay_ld;
reg B_po_counter_read_en;
wire [8:0] B_po_counter_read_val;
reg B_pi_counter_read_en;
wire [5:0] B_pi_counter_read_val;
wire B_pi_fine_overflow;
wire B_po_coarse_overflow;
wire B_po_fine_overflow;
wire B_pi_phase_locked;
wire B_pi_iserdes_rst;
wire B_pi_dqs_found;
wire B_pi_dqs_out_of_range;
reg B_pi_fine_enable;
reg B_pi_fine_inc;
reg B_pi_counter_load_en;
reg [5:0] B_pi_counter_load_val;
reg B_pi_rst_dqs_find;
reg B_po_fine_enable;
reg B_po_coarse_enable;
(* keep = "true", max_fanout = 3 *) reg B_po_fine_inc /* synthesis syn_maxfan = 3 */;
reg B_po_coarse_inc;
reg B_po_sel_fine_oclk_delay;
reg B_po_counter_load_en;
reg [8:0] B_po_counter_load_val;
wire B_rclk;
reg B_idelay_ce;
reg B_idelay_ld;
reg C_pi_fine_inc;
reg D_pi_fine_inc;
reg C_pi_fine_enable;
reg D_pi_fine_enable;
reg C_po_counter_load_en;
reg D_po_counter_load_en;
reg C_po_coarse_inc;
reg D_po_coarse_inc;
(* keep = "true", max_fanout = 3 *) reg C_po_fine_inc /* synthesis syn_maxfan = 3 */;
(* keep = "true", max_fanout = 3 *) reg D_po_fine_inc /* synthesis syn_maxfan = 3 */;
reg C_po_sel_fine_oclk_delay;
reg D_po_sel_fine_oclk_delay;
reg [5:0] C_pi_counter_load_val;
reg [5:0] D_pi_counter_load_val;
reg [8:0] C_po_counter_load_val;
reg [8:0] D_po_counter_load_val;
reg C_po_coarse_enable;
reg D_po_coarse_enable;
reg C_po_fine_enable;
reg D_po_fine_enable;
wire C_po_coarse_overflow;
wire D_po_coarse_overflow;
wire C_po_fine_overflow;
wire D_po_fine_overflow;
wire [8:0] C_po_counter_read_val;
wire [8:0] D_po_counter_read_val;
reg C_po_counter_read_en;
reg D_po_counter_read_en;
wire C_pi_dqs_found;
wire D_pi_dqs_found;
wire C_pi_fine_overflow;
wire D_pi_fine_overflow;
reg C_pi_counter_read_en;
reg D_pi_counter_read_en;
reg C_pi_counter_load_en;
reg D_pi_counter_load_en;
wire C_pi_phase_locked;
wire C_pi_iserdes_rst;
wire D_pi_phase_locked;
wire D_pi_iserdes_rst;
wire C_pi_dqs_out_of_range;
wire D_pi_dqs_out_of_range;
wire [5:0] C_pi_counter_read_val;
wire [5:0] D_pi_counter_read_val;
wire C_rclk;
wire D_rclk;
reg C_idelay_ce;
reg D_idelay_ce;
reg C_idelay_ld;
reg D_idelay_ld;
reg C_pi_rst_dqs_find;
reg D_pi_rst_dqs_find;
wire pi_iserdes_rst;
wire A_if_empty;
wire B_if_empty;
wire C_if_empty;
wire D_if_empty;
wire A_byte_rd_en;
wire B_byte_rd_en;
wire C_byte_rd_en;
wire D_byte_rd_en;
wire A_if_a_empty;
wire B_if_a_empty;
wire C_if_a_empty;
wire D_if_a_empty;
wire A_if_full;
wire B_if_full;
wire C_if_full;
wire D_if_full;
wire A_of_empty;
wire B_of_empty;
wire C_of_empty;
wire D_of_empty;
wire A_of_full;
wire B_of_full;
wire C_of_full;
wire D_of_full;
wire A_of_ctl_full;
wire B_of_ctl_full;
wire C_of_ctl_full;
wire D_of_ctl_full;
wire A_of_data_full;
wire B_of_data_full;
wire C_of_data_full;
wire D_of_data_full;
wire A_of_a_full;
wire B_of_a_full;
wire C_of_a_full;
wire D_of_a_full;
wire A_pre_fifo_a_full;
wire B_pre_fifo_a_full;
wire C_pre_fifo_a_full;
wire D_pre_fifo_a_full;
wire A_of_ctl_a_full;
wire B_of_ctl_a_full;
wire C_of_ctl_a_full;
wire D_of_ctl_a_full;
wire A_of_data_a_full;
wire B_of_data_a_full;
wire C_of_data_a_full;
wire D_of_data_a_full;
wire A_pre_data_a_full;
wire B_pre_data_a_full;
wire C_pre_data_a_full;
wire D_pre_data_a_full;
wire [LP_DDR_CK_WIDTH*6-1:0] A_ddr_clk; // for generation
wire [LP_DDR_CK_WIDTH*6-1:0] B_ddr_clk; //
wire [LP_DDR_CK_WIDTH*6-1:0] C_ddr_clk; //
wire [LP_DDR_CK_WIDTH*6-1:0] D_ddr_clk; //
wire [3:0] dummy_data;
wire [31:0] _phy_ctl_wd;
wire [1:0] phy_encalib;
assign pi_dqs_found_all =
(! PRESENT_DATA_A | A_pi_dqs_found) &
(! PRESENT_DATA_B | B_pi_dqs_found) &
(! PRESENT_DATA_C | C_pi_dqs_found) &
(! PRESENT_DATA_D | D_pi_dqs_found) ;
assign pi_dqs_found_any =
( PRESENT_DATA_A & A_pi_dqs_found) |
( PRESENT_DATA_B & B_pi_dqs_found) |
( PRESENT_DATA_C & C_pi_dqs_found) |
( PRESENT_DATA_D & D_pi_dqs_found) ;
assign pi_phase_locked_all =
(! PRESENT_DATA_A | A_pi_phase_locked) &
(! PRESENT_DATA_B | B_pi_phase_locked) &
(! PRESENT_DATA_C | C_pi_phase_locked) &
(! PRESENT_DATA_D | D_pi_phase_locked);
wire dangling_inputs = (& dummy_data) & input_sink & 1'b0; // this reduces all constant 0 values to 1 signal
// which is combined into another signals such that
// the other signal isn't changed. The purpose
// is to fake the tools into ignoring dangling inputs.
// Because it is anded with 1'b0, the contributing signals
// are folded as constants or trimmed.
assign if_empty = !if_empty_def ? (A_if_empty | B_if_empty | C_if_empty | D_if_empty) : (A_if_empty & B_if_empty & C_if_empty & D_if_empty);
assign byte_rd_en = !if_empty_def ? (A_byte_rd_en & B_byte_rd_en & C_byte_rd_en & D_byte_rd_en) :
(A_byte_rd_en | B_byte_rd_en | C_byte_rd_en | D_byte_rd_en);
assign if_empty_or = (A_if_empty | B_if_empty | C_if_empty | D_if_empty);
assign if_empty_and = (A_if_empty & B_if_empty & C_if_empty & D_if_empty);
assign if_a_empty = A_if_a_empty | B_if_a_empty | C_if_a_empty | D_if_a_empty;
assign if_full = A_if_full | B_if_full | C_if_full | D_if_full ;
assign of_empty = A_of_empty & B_of_empty & C_of_empty & D_of_empty;
assign of_ctl_full = A_of_ctl_full | B_of_ctl_full | C_of_ctl_full | D_of_ctl_full ;
assign of_data_full = A_of_data_full | B_of_data_full | C_of_data_full | D_of_data_full ;
assign of_ctl_a_full = A_of_ctl_a_full | B_of_ctl_a_full | C_of_ctl_a_full | D_of_ctl_a_full ;
assign of_data_a_full = A_of_data_a_full | B_of_data_a_full | C_of_data_a_full | D_of_data_a_full | dangling_inputs ;
assign pre_data_a_full = A_pre_data_a_full | B_pre_data_a_full | C_pre_data_a_full | D_pre_data_a_full;
function [79:0] part_select_80;
input [319:0] vector;
input [1:0] select;
begin
case (select)
2'b00 : part_select_80[79:0] = vector[1*80-1:0*80];
2'b01 : part_select_80[79:0] = vector[2*80-1:1*80];
2'b10 : part_select_80[79:0] = vector[3*80-1:2*80];
2'b11 : part_select_80[79:0] = vector[4*80-1:3*80];
endcase
end
endfunction
wire [319:0] phy_dout_remap;
reg rst_out_trig = 1'b0;
reg [31:0] rclk_delay;
reg rst_edge1 = 1'b0;
reg rst_edge2 = 1'b0;
reg rst_edge3 = 1'b0;
reg rst_edge_detect = 1'b0;
wire rclk_;
reg rst_out_start = 1'b0 ;
reg rst_primitives=0;
reg A_rst_primitives=0;
reg B_rst_primitives=0;
reg C_rst_primitives=0;
reg D_rst_primitives=0;
`ifdef USE_PHY_CONTROL_TEST
wire [15:0] test_output;
wire [15:0] test_input;
wire [2:0] test_select=0;
wire scan_enable = 0;
`endif
generate
genvar i;
if (RCLK_SELECT_LANE == "A") begin
assign rclk_ = A_rclk;
assign pi_iserdes_rst = A_pi_iserdes_rst;
end
else if (RCLK_SELECT_LANE == "B") begin
assign rclk_ = B_rclk;
assign pi_iserdes_rst = B_pi_iserdes_rst;
end
else if (RCLK_SELECT_LANE == "C") begin
assign rclk_ = C_rclk;
assign pi_iserdes_rst = C_pi_iserdes_rst;
end
else if (RCLK_SELECT_LANE == "D") begin
assign rclk_ = D_rclk;
assign pi_iserdes_rst = D_pi_iserdes_rst;
end
else begin
assign rclk_ = B_rclk; // default
end
endgenerate
assign ddr_clk[LP_DDR_CK_WIDTH*6-1:0] = A_ddr_clk;
assign ddr_clk[LP_DDR_CK_WIDTH*12-1:LP_DDR_CK_WIDTH*6] = B_ddr_clk;
assign ddr_clk[LP_DDR_CK_WIDTH*18-1:LP_DDR_CK_WIDTH*12] = C_ddr_clk;
assign ddr_clk[LP_DDR_CK_WIDTH*24-1:LP_DDR_CK_WIDTH*18] = D_ddr_clk;
assign pi_phase_locked_lanes =
{(! PRESENT_DATA_A[0] | A_pi_phase_locked),
(! PRESENT_DATA_B[0] | B_pi_phase_locked) ,
(! PRESENT_DATA_C[0] | C_pi_phase_locked) ,
(! PRESENT_DATA_D[0] | D_pi_phase_locked)};
assign pi_dqs_found_lanes = {D_pi_dqs_found, C_pi_dqs_found, B_pi_dqs_found, A_pi_dqs_found};
// this block scrubs X from rclk_delay[11]
reg rclk_delay_11;
always @(rclk_delay[11]) begin : rclk_delay_11_blk
if ( rclk_delay[11])
rclk_delay_11 = 1;
else
rclk_delay_11 = 0;
end
always @(posedge phy_clk or posedge rst ) begin
// scrub 4-state values from rclk_delay[11]
if ( rst) begin
rst_out <= #1 0;
end
else begin
if ( rclk_delay_11)
rst_out <= #1 1;
end
end
always @(posedge phy_clk ) begin
// phy_ctl_ready drives reset of the system
rst_primitives <= !phy_ctl_ready ;
A_rst_primitives <= rst_primitives ;
B_rst_primitives <= rst_primitives ;
C_rst_primitives <= rst_primitives ;
D_rst_primitives <= rst_primitives ;
rclk_delay <= #1 (rclk_delay << 1) | (!rst_primitives && phyGo);
mcGo <= #1 rst_out ;
end
generate
if (BYTE_LANES[0]) begin
assign dummy_data[0] = 0;
end
else begin
assign dummy_data[0] = &phy_dout_remap[1*80-1:0*80];
end
if (BYTE_LANES[1]) begin
assign dummy_data[1] = 0;
end
else begin
assign dummy_data[1] = &phy_dout_remap[2*80-1:1*80];
end
if (BYTE_LANES[2]) begin
assign dummy_data[2] = 0;
end
else begin
assign dummy_data[2] = &phy_dout_remap[3*80-1:2*80];
end
if (BYTE_LANES[3]) begin
assign dummy_data[3] = 0;
end
else begin
assign dummy_data[3] = &phy_dout_remap[4*80-1:3*80];
end
if (PRESENT_DATA_A) begin
assign A_of_data_full = A_of_full;
assign A_of_ctl_full = 0;
assign A_of_data_a_full = A_of_a_full;
assign A_of_ctl_a_full = 0;
assign A_pre_data_a_full = A_pre_fifo_a_full;
end
else begin
assign A_of_ctl_full = A_of_full;
assign A_of_data_full = 0;
assign A_of_ctl_a_full = A_of_a_full;
assign A_of_data_a_full = 0;
assign A_pre_data_a_full = 0;
end
if (PRESENT_DATA_B) begin
assign B_of_data_full = B_of_full;
assign B_of_ctl_full = 0;
assign B_of_data_a_full = B_of_a_full;
assign B_of_ctl_a_full = 0;
assign B_pre_data_a_full = B_pre_fifo_a_full;
end
else begin
assign B_of_ctl_full = B_of_full;
assign B_of_data_full = 0;
assign B_of_ctl_a_full = B_of_a_full;
assign B_of_data_a_full = 0;
assign B_pre_data_a_full = 0;
end
if (PRESENT_DATA_C) begin
assign C_of_data_full = C_of_full;
assign C_of_ctl_full = 0;
assign C_of_data_a_full = C_of_a_full;
assign C_of_ctl_a_full = 0;
assign C_pre_data_a_full = C_pre_fifo_a_full;
end
else begin
assign C_of_ctl_full = C_of_full;
assign C_of_data_full = 0;
assign C_of_ctl_a_full = C_of_a_full;
assign C_of_data_a_full = 0;
assign C_pre_data_a_full = 0;
end
if (PRESENT_DATA_D) begin
assign D_of_data_full = D_of_full;
assign D_of_ctl_full = 0;
assign D_of_data_a_full = D_of_a_full;
assign D_of_ctl_a_full = 0;
assign D_pre_data_a_full = D_pre_fifo_a_full;
end
else begin
assign D_of_ctl_full = D_of_full;
assign D_of_data_full = 0;
assign D_of_ctl_a_full = D_of_a_full;
assign D_of_data_a_full = 0;
assign D_pre_data_a_full = 0;
end
// byte lane must exist and be data lane.
if (PRESENT_DATA_A )
case ( LANE_REMAP[1:0] )
2'b00 : assign phy_din[1*80-1:0] = phy_din_remap[79:0];
2'b01 : assign phy_din[2*80-1:80] = phy_din_remap[79:0];
2'b10 : assign phy_din[3*80-1:160] = phy_din_remap[79:0];
2'b11 : assign phy_din[4*80-1:240] = phy_din_remap[79:0];
endcase
else
case ( LANE_REMAP[1:0] )
2'b00 : assign phy_din[1*80-1:0] = 80'h0;
2'b01 : assign phy_din[2*80-1:80] = 80'h0;
2'b10 : assign phy_din[3*80-1:160] = 80'h0;
2'b11 : assign phy_din[4*80-1:240] = 80'h0;
endcase
if (PRESENT_DATA_B )
case ( LANE_REMAP[5:4] )
2'b00 : assign phy_din[1*80-1:0] = phy_din_remap[159:80];
2'b01 : assign phy_din[2*80-1:80] = phy_din_remap[159:80];
2'b10 : assign phy_din[3*80-1:160] = phy_din_remap[159:80];
2'b11 : assign phy_din[4*80-1:240] = phy_din_remap[159:80];
endcase
else
if (HIGHEST_LANE > 1)
case ( LANE_REMAP[5:4] )
2'b00 : assign phy_din[1*80-1:0] = 80'h0;
2'b01 : assign phy_din[2*80-1:80] = 80'h0;
2'b10 : assign phy_din[3*80-1:160] = 80'h0;
2'b11 : assign phy_din[4*80-1:240] = 80'h0;
endcase
if (PRESENT_DATA_C)
case ( LANE_REMAP[9:8] )
2'b00 : assign phy_din[1*80-1:0] = phy_din_remap[239:160];
2'b01 : assign phy_din[2*80-1:80] = phy_din_remap[239:160];
2'b10 : assign phy_din[3*80-1:160] = phy_din_remap[239:160];
2'b11 : assign phy_din[4*80-1:240] = phy_din_remap[239:160];
endcase
else
if (HIGHEST_LANE > 2)
case ( LANE_REMAP[9:8] )
2'b00 : assign phy_din[1*80-1:0] = 80'h0;
2'b01 : assign phy_din[2*80-1:80] = 80'h0;
2'b10 : assign phy_din[3*80-1:160] = 80'h0;
2'b11 : assign phy_din[4*80-1:240] = 80'h0;
endcase
if (PRESENT_DATA_D )
case ( LANE_REMAP[13:12] )
2'b00 : assign phy_din[1*80-1:0] = phy_din_remap[319:240];
2'b01 : assign phy_din[2*80-1:80] = phy_din_remap[319:240];
2'b10 : assign phy_din[3*80-1:160] = phy_din_remap[319:240];
2'b11 : assign phy_din[4*80-1:240] = phy_din_remap[319:240];
endcase
else
if (HIGHEST_LANE > 3)
case ( LANE_REMAP[13:12] )
2'b00 : assign phy_din[1*80-1:0] = 80'h0;
2'b01 : assign phy_din[2*80-1:80] = 80'h0;
2'b10 : assign phy_din[3*80-1:160] = 80'h0;
2'b11 : assign phy_din[4*80-1:240] = 80'h0;
endcase
if (HIGHEST_LANE > 1)
assign _phy_ctl_wd = {phy_ctl_wd[31:23], data_offset, phy_ctl_wd[16:0]};
if (HIGHEST_LANE == 1)
assign _phy_ctl_wd_ = phy_ctl_wd;
//BUFR #(.BUFR_DIVIDE ("1")) rclk_buf(.I(rclk_), .O(rclk), .CE (1'b1), .CLR (pi_iserdes_rst));
BUFIO rclk_buf(.I(rclk_), .O(rclk) );
if ( BYTE_LANES[0] ) begin : ddr_byte_lane_A
assign phy_dout_remap[79:0] = part_select_80(phy_dout, (LANE_REMAP[1:0]));
mig_7series_v1_9_ddr_byte_lane #
(
.ABCD ("A"),
.PO_DATA_CTL (PC_DATA_CTL_N[0] ? "TRUE" : "FALSE"),
.BITLANES (BITLANES[11:0]),
.BITLANES_OUTONLY (BITLANES_OUTONLY[11:0]),
.OF_ALMOST_EMPTY_VALUE (OF_ALMOST_EMPTY_VALUE),
.OF_ALMOST_FULL_VALUE (OF_ALMOST_FULL_VALUE),
.OF_SYNCHRONOUS_MODE (OF_SYNCHRONOUS_MODE),
//.OF_OUTPUT_DISABLE (OF_OUTPUT_DISABLE),
//.OF_ARRAY_MODE (A_OF_ARRAY_MODE),
//.IF_ARRAY_MODE (IF_ARRAY_MODE),
.IF_ALMOST_EMPTY_VALUE (IF_ALMOST_EMPTY_VALUE),
.IF_ALMOST_FULL_VALUE (IF_ALMOST_FULL_VALUE),
.IF_SYNCHRONOUS_MODE (IF_SYNCHRONOUS_MODE),
.IODELAY_GRP (IODELAY_GRP),
.BANK_TYPE (BANK_TYPE),
.BYTELANES_DDR_CK (BYTELANES_DDR_CK),
.RCLK_SELECT_LANE (RCLK_SELECT_LANE),
.USE_PRE_POST_FIFO (USE_PRE_POST_FIFO),
.SYNTHESIS (SYNTHESIS),
.TCK (TCK),
.PC_CLK_RATIO (PC_CLK_RATIO),
.PI_BURST_MODE (A_PI_BURST_MODE),
.PI_CLKOUT_DIV (A_PI_CLKOUT_DIV),
.PI_FREQ_REF_DIV (A_PI_FREQ_REF_DIV),
.PI_FINE_DELAY (A_PI_FINE_DELAY),
.PI_OUTPUT_CLK_SRC (A_PI_OUTPUT_CLK_SRC),
.PI_SYNC_IN_DIV_RST (A_PI_SYNC_IN_DIV_RST),
.PI_SEL_CLK_OFFSET (PI_SEL_CLK_OFFSET),
.PO_CLKOUT_DIV (A_PO_CLKOUT_DIV),
.PO_FINE_DELAY (A_PO_FINE_DELAY),
.PO_COARSE_BYPASS (A_PO_COARSE_BYPASS),
.PO_COARSE_DELAY (A_PO_COARSE_DELAY),
.PO_OCLK_DELAY (A_PO_OCLK_DELAY),
.PO_OCLKDELAY_INV (A_PO_OCLKDELAY_INV),
.PO_OUTPUT_CLK_SRC (A_PO_OUTPUT_CLK_SRC),
.PO_SYNC_IN_DIV_RST (A_PO_SYNC_IN_DIV_RST),
.OSERDES_DATA_RATE (A_OS_DATA_RATE),
.OSERDES_DATA_WIDTH (A_OS_DATA_WIDTH),
.IDELAYE2_IDELAY_TYPE (A_IDELAYE2_IDELAY_TYPE),
.IDELAYE2_IDELAY_VALUE (A_IDELAYE2_IDELAY_VALUE)
,.CKE_ODT_AUX (CKE_ODT_AUX)
)
ddr_byte_lane_A(
.mem_dq_out (mem_dq_out[11:0]),
.mem_dq_ts (mem_dq_ts[11:0]),
.mem_dq_in (mem_dq_in[9:0]),
.mem_dqs_out (mem_dqs_out[0]),
.mem_dqs_ts (mem_dqs_ts[0]),
.mem_dqs_in (mem_dqs_in[0]),
.rst (A_rst_primitives),
.phy_clk (phy_clk),
.freq_refclk (freq_refclk),
.mem_refclk (mem_refclk),
.idelayctrl_refclk (idelayctrl_refclk),
.sync_pulse (sync_pulse),
.ddr_ck_out (A_ddr_clk),
.rclk (A_rclk),
.pi_dqs_found (A_pi_dqs_found),
.dqs_out_of_range (A_pi_dqs_out_of_range),
.if_empty_def (if_empty_def),
.if_a_empty (A_if_a_empty),
.if_empty (A_if_empty),
.if_a_full (if_a_full),
.if_full (A_if_full),
.of_a_empty (of_a_empty),
.of_empty (A_of_empty),
.of_a_full (A_of_a_full),
.of_full (A_of_full),
.pre_fifo_a_full (A_pre_fifo_a_full),
.phy_din (phy_din_remap[79:0]),
.phy_dout (phy_dout_remap[79:0]),
.phy_cmd_wr_en (phy_cmd_wr_en),
.phy_data_wr_en (phy_data_wr_en),
.phy_rd_en (phy_rd_en),
.phaser_ctl_bus (phaser_ctl_bus),
.if_rst (if_rst),
.byte_rd_en_oth_lanes ({B_byte_rd_en,C_byte_rd_en,D_byte_rd_en}),
.byte_rd_en_oth_banks (byte_rd_en_oth_banks),
.byte_rd_en (A_byte_rd_en),
// calibration signals
.idelay_inc (idelay_inc),
.idelay_ce (A_idelay_ce),
.idelay_ld (A_idelay_ld),
.pi_rst_dqs_find (A_pi_rst_dqs_find),
.po_en_calib (phy_encalib),
.po_fine_enable (A_po_fine_enable),
.po_coarse_enable (A_po_coarse_enable),
.po_fine_inc (A_po_fine_inc),
.po_coarse_inc (A_po_coarse_inc),
.po_counter_load_en (A_po_counter_load_en),
.po_counter_read_en (A_po_counter_read_en),
.po_counter_load_val (A_po_counter_load_val),
.po_coarse_overflow (A_po_coarse_overflow),
.po_fine_overflow (A_po_fine_overflow),
.po_counter_read_val (A_po_counter_read_val),
.po_sel_fine_oclk_delay(A_po_sel_fine_oclk_delay),
.pi_en_calib (phy_encalib),
.pi_fine_enable (A_pi_fine_enable),
.pi_fine_inc (A_pi_fine_inc),
.pi_counter_load_en (A_pi_counter_load_en),
.pi_counter_read_en (A_pi_counter_read_en),
.pi_counter_load_val (A_pi_counter_load_val),
.pi_fine_overflow (A_pi_fine_overflow),
.pi_counter_read_val (A_pi_counter_read_val),
.pi_iserdes_rst (A_pi_iserdes_rst),
.pi_phase_locked (A_pi_phase_locked)
);
end
else begin : no_ddr_byte_lane_A
assign A_of_a_full = 1'b0;
assign A_of_full = 1'b0;
assign A_pre_fifo_a_full = 1'b0;
assign A_if_empty = 1'b0;
assign A_byte_rd_en = 1'b1;
assign A_if_a_empty = 1'b0;
assign A_pi_phase_locked = 1;
assign A_pi_dqs_found = 1;
assign A_rclk = 0;
assign A_ddr_clk = {LP_DDR_CK_WIDTH*6{1'b0}};
assign A_pi_counter_read_val = 0;
assign A_po_counter_read_val = 0;
assign A_pi_fine_overflow = 0;
assign A_po_coarse_overflow = 0;
assign A_po_fine_overflow = 0;
end
if ( BYTE_LANES[1] ) begin : ddr_byte_lane_B
assign phy_dout_remap[159:80] = part_select_80(phy_dout, (LANE_REMAP[5:4]));
mig_7series_v1_9_ddr_byte_lane #
(
.ABCD ("B"),
.PO_DATA_CTL (PC_DATA_CTL_N[1] ? "TRUE" : "FALSE"),
.BITLANES (BITLANES[23:12]),
.BITLANES_OUTONLY (BITLANES_OUTONLY[23:12]),
.OF_ALMOST_EMPTY_VALUE (OF_ALMOST_EMPTY_VALUE),
.OF_ALMOST_FULL_VALUE (OF_ALMOST_FULL_VALUE),
.OF_SYNCHRONOUS_MODE (OF_SYNCHRONOUS_MODE),
//.OF_OUTPUT_DISABLE (OF_OUTPUT_DISABLE),
//.OF_ARRAY_MODE (B_OF_ARRAY_MODE),
//.IF_ARRAY_MODE (IF_ARRAY_MODE),
.IF_ALMOST_EMPTY_VALUE (IF_ALMOST_EMPTY_VALUE),
.IF_ALMOST_FULL_VALUE (IF_ALMOST_FULL_VALUE),
.IF_SYNCHRONOUS_MODE (IF_SYNCHRONOUS_MODE),
.IODELAY_GRP (IODELAY_GRP),
.BANK_TYPE (BANK_TYPE),
.BYTELANES_DDR_CK (BYTELANES_DDR_CK),
.RCLK_SELECT_LANE (RCLK_SELECT_LANE),
.USE_PRE_POST_FIFO (USE_PRE_POST_FIFO),
.SYNTHESIS (SYNTHESIS),
.TCK (TCK),
.PC_CLK_RATIO (PC_CLK_RATIO),
.PI_BURST_MODE (B_PI_BURST_MODE),
.PI_CLKOUT_DIV (B_PI_CLKOUT_DIV),
.PI_FREQ_REF_DIV (B_PI_FREQ_REF_DIV),
.PI_FINE_DELAY (B_PI_FINE_DELAY),
.PI_OUTPUT_CLK_SRC (B_PI_OUTPUT_CLK_SRC),
.PI_SYNC_IN_DIV_RST (B_PI_SYNC_IN_DIV_RST),
.PI_SEL_CLK_OFFSET (PI_SEL_CLK_OFFSET),
.PO_CLKOUT_DIV (B_PO_CLKOUT_DIV),
.PO_FINE_DELAY (B_PO_FINE_DELAY),
.PO_COARSE_BYPASS (B_PO_COARSE_BYPASS),
.PO_COARSE_DELAY (B_PO_COARSE_DELAY),
.PO_OCLK_DELAY (B_PO_OCLK_DELAY),
.PO_OCLKDELAY_INV (B_PO_OCLKDELAY_INV),
.PO_OUTPUT_CLK_SRC (B_PO_OUTPUT_CLK_SRC),
.PO_SYNC_IN_DIV_RST (B_PO_SYNC_IN_DIV_RST),
.OSERDES_DATA_RATE (B_OS_DATA_RATE),
.OSERDES_DATA_WIDTH (B_OS_DATA_WIDTH),
.IDELAYE2_IDELAY_TYPE (B_IDELAYE2_IDELAY_TYPE),
.IDELAYE2_IDELAY_VALUE (B_IDELAYE2_IDELAY_VALUE)
,.CKE_ODT_AUX (CKE_ODT_AUX)
)
ddr_byte_lane_B(
.mem_dq_out (mem_dq_out[23:12]),
.mem_dq_ts (mem_dq_ts[23:12]),
.mem_dq_in (mem_dq_in[19:10]),
.mem_dqs_out (mem_dqs_out[1]),
.mem_dqs_ts (mem_dqs_ts[1]),
.mem_dqs_in (mem_dqs_in[1]),
.rst (B_rst_primitives),
.phy_clk (phy_clk),
.freq_refclk (freq_refclk),
.mem_refclk (mem_refclk),
.idelayctrl_refclk (idelayctrl_refclk),
.sync_pulse (sync_pulse),
.ddr_ck_out (B_ddr_clk),
.rclk (B_rclk),
.pi_dqs_found (B_pi_dqs_found),
.dqs_out_of_range (B_pi_dqs_out_of_range),
.if_empty_def (if_empty_def),
.if_a_empty (B_if_a_empty),
.if_empty (B_if_empty),
.if_a_full (/*if_a_full*/),
.if_full (B_if_full),
.of_a_empty (/*of_a_empty*/),
.of_empty (B_of_empty),
.of_a_full (B_of_a_full),
.of_full (B_of_full),
.pre_fifo_a_full (B_pre_fifo_a_full),
.phy_din (phy_din_remap[159:80]),
.phy_dout (phy_dout_remap[159:80]),
.phy_cmd_wr_en (phy_cmd_wr_en),
.phy_data_wr_en (phy_data_wr_en),
.phy_rd_en (phy_rd_en),
.phaser_ctl_bus (phaser_ctl_bus),
.if_rst (if_rst),
.byte_rd_en_oth_lanes ({A_byte_rd_en,C_byte_rd_en,D_byte_rd_en}),
.byte_rd_en_oth_banks (byte_rd_en_oth_banks),
.byte_rd_en (B_byte_rd_en),
// calibration signals
.idelay_inc (idelay_inc),
.idelay_ce (B_idelay_ce),
.idelay_ld (B_idelay_ld),
.pi_rst_dqs_find (B_pi_rst_dqs_find),
.po_en_calib (phy_encalib),
.po_fine_enable (B_po_fine_enable),
.po_coarse_enable (B_po_coarse_enable),
.po_fine_inc (B_po_fine_inc),
.po_coarse_inc (B_po_coarse_inc),
.po_counter_load_en (B_po_counter_load_en),
.po_counter_read_en (B_po_counter_read_en),
.po_counter_load_val (B_po_counter_load_val),
.po_coarse_overflow (B_po_coarse_overflow),
.po_fine_overflow (B_po_fine_overflow),
.po_counter_read_val (B_po_counter_read_val),
.po_sel_fine_oclk_delay(B_po_sel_fine_oclk_delay),
.pi_en_calib (phy_encalib),
.pi_fine_enable (B_pi_fine_enable),
.pi_fine_inc (B_pi_fine_inc),
.pi_counter_load_en (B_pi_counter_load_en),
.pi_counter_read_en (B_pi_counter_read_en),
.pi_counter_load_val (B_pi_counter_load_val),
.pi_fine_overflow (B_pi_fine_overflow),
.pi_counter_read_val (B_pi_counter_read_val),
.pi_iserdes_rst (B_pi_iserdes_rst),
.pi_phase_locked (B_pi_phase_locked)
);
end
else begin : no_ddr_byte_lane_B
assign B_of_a_full = 1'b0;
assign B_of_full = 1'b0;
assign B_pre_fifo_a_full = 1'b0;
assign B_if_empty = 1'b0;
assign B_if_a_empty = 1'b0;
assign B_byte_rd_en = 1'b1;
assign B_pi_phase_locked = 1;
assign B_pi_dqs_found = 1;
assign B_rclk = 0;
assign B_ddr_clk = {LP_DDR_CK_WIDTH*6{1'b0}};
assign B_pi_counter_read_val = 0;
assign B_po_counter_read_val = 0;
assign B_pi_fine_overflow = 0;
assign B_po_coarse_overflow = 0;
assign B_po_fine_overflow = 0;
end
if ( BYTE_LANES[2] ) begin : ddr_byte_lane_C
assign phy_dout_remap[239:160] = part_select_80(phy_dout, (LANE_REMAP[9:8]));
mig_7series_v1_9_ddr_byte_lane #
(
.ABCD ("C"),
.PO_DATA_CTL (PC_DATA_CTL_N[2] ? "TRUE" : "FALSE"),
.BITLANES (BITLANES[35:24]),
.BITLANES_OUTONLY (BITLANES_OUTONLY[35:24]),
.OF_ALMOST_EMPTY_VALUE (OF_ALMOST_EMPTY_VALUE),
.OF_ALMOST_FULL_VALUE (OF_ALMOST_FULL_VALUE),
.OF_SYNCHRONOUS_MODE (OF_SYNCHRONOUS_MODE),
//.OF_OUTPUT_DISABLE (OF_OUTPUT_DISABLE),
//.OF_ARRAY_MODE (C_OF_ARRAY_MODE),
//.IF_ARRAY_MODE (IF_ARRAY_MODE),
.IF_ALMOST_EMPTY_VALUE (IF_ALMOST_EMPTY_VALUE),
.IF_ALMOST_FULL_VALUE (IF_ALMOST_FULL_VALUE),
.IF_SYNCHRONOUS_MODE (IF_SYNCHRONOUS_MODE),
.IODELAY_GRP (IODELAY_GRP),
.BANK_TYPE (BANK_TYPE),
.BYTELANES_DDR_CK (BYTELANES_DDR_CK),
.RCLK_SELECT_LANE (RCLK_SELECT_LANE),
.USE_PRE_POST_FIFO (USE_PRE_POST_FIFO),
.SYNTHESIS (SYNTHESIS),
.TCK (TCK),
.PC_CLK_RATIO (PC_CLK_RATIO),
.PI_BURST_MODE (C_PI_BURST_MODE),
.PI_CLKOUT_DIV (C_PI_CLKOUT_DIV),
.PI_FREQ_REF_DIV (C_PI_FREQ_REF_DIV),
.PI_FINE_DELAY (C_PI_FINE_DELAY),
.PI_OUTPUT_CLK_SRC (C_PI_OUTPUT_CLK_SRC),
.PI_SYNC_IN_DIV_RST (C_PI_SYNC_IN_DIV_RST),
.PI_SEL_CLK_OFFSET (PI_SEL_CLK_OFFSET),
.PO_CLKOUT_DIV (C_PO_CLKOUT_DIV),
.PO_FINE_DELAY (C_PO_FINE_DELAY),
.PO_COARSE_BYPASS (C_PO_COARSE_BYPASS),
.PO_COARSE_DELAY (C_PO_COARSE_DELAY),
.PO_OCLK_DELAY (C_PO_OCLK_DELAY),
.PO_OCLKDELAY_INV (C_PO_OCLKDELAY_INV),
.PO_OUTPUT_CLK_SRC (C_PO_OUTPUT_CLK_SRC),
.PO_SYNC_IN_DIV_RST (C_PO_SYNC_IN_DIV_RST),
.OSERDES_DATA_RATE (C_OS_DATA_RATE),
.OSERDES_DATA_WIDTH (C_OS_DATA_WIDTH),
.IDELAYE2_IDELAY_TYPE (C_IDELAYE2_IDELAY_TYPE),
.IDELAYE2_IDELAY_VALUE (C_IDELAYE2_IDELAY_VALUE)
,.CKE_ODT_AUX (CKE_ODT_AUX)
)
ddr_byte_lane_C(
.mem_dq_out (mem_dq_out[35:24]),
.mem_dq_ts (mem_dq_ts[35:24]),
.mem_dq_in (mem_dq_in[29:20]),
.mem_dqs_out (mem_dqs_out[2]),
.mem_dqs_ts (mem_dqs_ts[2]),
.mem_dqs_in (mem_dqs_in[2]),
.rst (C_rst_primitives),
.phy_clk (phy_clk),
.freq_refclk (freq_refclk),
.mem_refclk (mem_refclk),
.idelayctrl_refclk (idelayctrl_refclk),
.sync_pulse (sync_pulse),
.ddr_ck_out (C_ddr_clk),
.rclk (C_rclk),
.pi_dqs_found (C_pi_dqs_found),
.dqs_out_of_range (C_pi_dqs_out_of_range),
.if_empty_def (if_empty_def),
.if_a_empty (C_if_a_empty),
.if_empty (C_if_empty),
.if_a_full (/*if_a_full*/),
.if_full (C_if_full),
.of_a_empty (/*of_a_empty*/),
.of_empty (C_of_empty),
.of_a_full (C_of_a_full),
.of_full (C_of_full),
.pre_fifo_a_full (C_pre_fifo_a_full),
.phy_din (phy_din_remap[239:160]),
.phy_dout (phy_dout_remap[239:160]),
.phy_cmd_wr_en (phy_cmd_wr_en),
.phy_data_wr_en (phy_data_wr_en),
.phy_rd_en (phy_rd_en),
.phaser_ctl_bus (phaser_ctl_bus),
.if_rst (if_rst),
.byte_rd_en_oth_lanes ({A_byte_rd_en,B_byte_rd_en,D_byte_rd_en}),
.byte_rd_en_oth_banks (byte_rd_en_oth_banks),
.byte_rd_en (C_byte_rd_en),
// calibration signals
.idelay_inc (idelay_inc),
.idelay_ce (C_idelay_ce),
.idelay_ld (C_idelay_ld),
.pi_rst_dqs_find (C_pi_rst_dqs_find),
.po_en_calib (phy_encalib),
.po_fine_enable (C_po_fine_enable),
.po_coarse_enable (C_po_coarse_enable),
.po_fine_inc (C_po_fine_inc),
.po_coarse_inc (C_po_coarse_inc),
.po_counter_load_en (C_po_counter_load_en),
.po_counter_read_en (C_po_counter_read_en),
.po_counter_load_val (C_po_counter_load_val),
.po_coarse_overflow (C_po_coarse_overflow),
.po_fine_overflow (C_po_fine_overflow),
.po_counter_read_val (C_po_counter_read_val),
.po_sel_fine_oclk_delay(C_po_sel_fine_oclk_delay),
.pi_en_calib (phy_encalib),
.pi_fine_enable (C_pi_fine_enable),
.pi_fine_inc (C_pi_fine_inc),
.pi_counter_load_en (C_pi_counter_load_en),
.pi_counter_read_en (C_pi_counter_read_en),
.pi_counter_load_val (C_pi_counter_load_val),
.pi_fine_overflow (C_pi_fine_overflow),
.pi_counter_read_val (C_pi_counter_read_val),
.pi_iserdes_rst (C_pi_iserdes_rst),
.pi_phase_locked (C_pi_phase_locked)
);
end
else begin : no_ddr_byte_lane_C
assign C_of_a_full = 1'b0;
assign C_of_full = 1'b0;
assign C_pre_fifo_a_full = 1'b0;
assign C_if_empty = 1'b0;
assign C_byte_rd_en = 1'b1;
assign C_if_a_empty = 1'b0;
assign C_pi_phase_locked = 1;
assign C_pi_dqs_found = 1;
assign C_rclk = 0;
assign C_ddr_clk = {LP_DDR_CK_WIDTH*6{1'b0}};
assign C_pi_counter_read_val = 0;
assign C_po_counter_read_val = 0;
assign C_pi_fine_overflow = 0;
assign C_po_coarse_overflow = 0;
assign C_po_fine_overflow = 0;
end
if ( BYTE_LANES[3] ) begin : ddr_byte_lane_D
assign phy_dout_remap[319:240] = part_select_80(phy_dout, (LANE_REMAP[13:12]));
mig_7series_v1_9_ddr_byte_lane #
(
.ABCD ("D"),
.PO_DATA_CTL (PC_DATA_CTL_N[3] ? "TRUE" : "FALSE"),
.BITLANES (BITLANES[47:36]),
.BITLANES_OUTONLY (BITLANES_OUTONLY[47:36]),
.OF_ALMOST_EMPTY_VALUE (OF_ALMOST_EMPTY_VALUE),
.OF_ALMOST_FULL_VALUE (OF_ALMOST_FULL_VALUE),
.OF_SYNCHRONOUS_MODE (OF_SYNCHRONOUS_MODE),
//.OF_OUTPUT_DISABLE (OF_OUTPUT_DISABLE),
//.OF_ARRAY_MODE (D_OF_ARRAY_MODE),
//.IF_ARRAY_MODE (IF_ARRAY_MODE),
.IF_ALMOST_EMPTY_VALUE (IF_ALMOST_EMPTY_VALUE),
.IF_ALMOST_FULL_VALUE (IF_ALMOST_FULL_VALUE),
.IF_SYNCHRONOUS_MODE (IF_SYNCHRONOUS_MODE),
.IODELAY_GRP (IODELAY_GRP),
.BANK_TYPE (BANK_TYPE),
.BYTELANES_DDR_CK (BYTELANES_DDR_CK),
.RCLK_SELECT_LANE (RCLK_SELECT_LANE),
.USE_PRE_POST_FIFO (USE_PRE_POST_FIFO),
.SYNTHESIS (SYNTHESIS),
.TCK (TCK),
.PC_CLK_RATIO (PC_CLK_RATIO),
.PI_BURST_MODE (D_PI_BURST_MODE),
.PI_CLKOUT_DIV (D_PI_CLKOUT_DIV),
.PI_FREQ_REF_DIV (D_PI_FREQ_REF_DIV),
.PI_FINE_DELAY (D_PI_FINE_DELAY),
.PI_OUTPUT_CLK_SRC (D_PI_OUTPUT_CLK_SRC),
.PI_SYNC_IN_DIV_RST (D_PI_SYNC_IN_DIV_RST),
.PI_SEL_CLK_OFFSET (PI_SEL_CLK_OFFSET),
.PO_CLKOUT_DIV (D_PO_CLKOUT_DIV),
.PO_FINE_DELAY (D_PO_FINE_DELAY),
.PO_COARSE_BYPASS (D_PO_COARSE_BYPASS),
.PO_COARSE_DELAY (D_PO_COARSE_DELAY),
.PO_OCLK_DELAY (D_PO_OCLK_DELAY),
.PO_OCLKDELAY_INV (D_PO_OCLKDELAY_INV),
.PO_OUTPUT_CLK_SRC (D_PO_OUTPUT_CLK_SRC),
.PO_SYNC_IN_DIV_RST (D_PO_SYNC_IN_DIV_RST),
.OSERDES_DATA_RATE (D_OS_DATA_RATE),
.OSERDES_DATA_WIDTH (D_OS_DATA_WIDTH),
.IDELAYE2_IDELAY_TYPE (D_IDELAYE2_IDELAY_TYPE),
.IDELAYE2_IDELAY_VALUE (D_IDELAYE2_IDELAY_VALUE)
,.CKE_ODT_AUX (CKE_ODT_AUX)
)
ddr_byte_lane_D(
.mem_dq_out (mem_dq_out[47:36]),
.mem_dq_ts (mem_dq_ts[47:36]),
.mem_dq_in (mem_dq_in[39:30]),
.mem_dqs_out (mem_dqs_out[3]),
.mem_dqs_ts (mem_dqs_ts[3]),
.mem_dqs_in (mem_dqs_in[3]),
.rst (D_rst_primitives),
.phy_clk (phy_clk),
.freq_refclk (freq_refclk),
.mem_refclk (mem_refclk),
.idelayctrl_refclk (idelayctrl_refclk),
.sync_pulse (sync_pulse),
.ddr_ck_out (D_ddr_clk),
.rclk (D_rclk),
.pi_dqs_found (D_pi_dqs_found),
.dqs_out_of_range (D_pi_dqs_out_of_range),
.if_empty_def (if_empty_def),
.if_a_empty (D_if_a_empty),
.if_empty (D_if_empty),
.if_a_full (/*if_a_full*/),
.if_full (D_if_full),
.of_a_empty (/*of_a_empty*/),
.of_empty (D_of_empty),
.of_a_full (D_of_a_full),
.of_full (D_of_full),
.pre_fifo_a_full (D_pre_fifo_a_full),
.phy_din (phy_din_remap[319:240]),
.phy_dout (phy_dout_remap[319:240]),
.phy_cmd_wr_en (phy_cmd_wr_en),
.phy_data_wr_en (phy_data_wr_en),
.phy_rd_en (phy_rd_en),
.phaser_ctl_bus (phaser_ctl_bus),
.idelay_inc (idelay_inc),
.idelay_ce (D_idelay_ce),
.idelay_ld (D_idelay_ld),
.if_rst (if_rst),
.byte_rd_en_oth_lanes ({A_byte_rd_en,B_byte_rd_en,C_byte_rd_en}),
.byte_rd_en_oth_banks (byte_rd_en_oth_banks),
.byte_rd_en (D_byte_rd_en),
// calibration signals
.pi_rst_dqs_find (D_pi_rst_dqs_find),
.po_en_calib (phy_encalib),
.po_fine_enable (D_po_fine_enable),
.po_coarse_enable (D_po_coarse_enable),
.po_fine_inc (D_po_fine_inc),
.po_coarse_inc (D_po_coarse_inc),
.po_counter_load_en (D_po_counter_load_en),
.po_counter_read_en (D_po_counter_read_en),
.po_counter_load_val (D_po_counter_load_val),
.po_coarse_overflow (D_po_coarse_overflow),
.po_fine_overflow (D_po_fine_overflow),
.po_counter_read_val (D_po_counter_read_val),
.po_sel_fine_oclk_delay(D_po_sel_fine_oclk_delay),
.pi_en_calib (phy_encalib),
.pi_fine_enable (D_pi_fine_enable),
.pi_fine_inc (D_pi_fine_inc),
.pi_counter_load_en (D_pi_counter_load_en),
.pi_counter_read_en (D_pi_counter_read_en),
.pi_counter_load_val (D_pi_counter_load_val),
.pi_fine_overflow (D_pi_fine_overflow),
.pi_counter_read_val (D_pi_counter_read_val),
.pi_iserdes_rst (D_pi_iserdes_rst),
.pi_phase_locked (D_pi_phase_locked)
);
end
else begin : no_ddr_byte_lane_D
assign D_of_a_full = 1'b0;
assign D_of_full = 1'b0;
assign D_pre_fifo_a_full = 1'b0;
assign D_if_empty = 1'b0;
assign D_byte_rd_en = 1'b1;
assign D_if_a_empty = 1'b0;
assign D_rclk = 0;
assign D_ddr_clk = {LP_DDR_CK_WIDTH*6{1'b0}};
assign D_pi_dqs_found = 1;
assign D_pi_phase_locked = 1;
assign D_pi_counter_read_val = 0;
assign D_po_counter_read_val = 0;
assign D_pi_fine_overflow = 0;
assign D_po_coarse_overflow = 0;
assign D_po_fine_overflow = 0;
end
endgenerate
assign phaser_ctl_bus[MSB_RANK_SEL_I : MSB_RANK_SEL_I - 7] = in_rank;
PHY_CONTROL #(
.AO_WRLVL_EN ( PC_AO_WRLVL_EN),
.AO_TOGGLE ( PC_AO_TOGGLE),
.BURST_MODE ( PC_BURST_MODE),
.CO_DURATION ( PC_CO_DURATION ),
.CLK_RATIO ( PC_CLK_RATIO),
.DATA_CTL_A_N ( PC_DATA_CTL_A),
.DATA_CTL_B_N ( PC_DATA_CTL_B),
.DATA_CTL_C_N ( PC_DATA_CTL_C),
.DATA_CTL_D_N ( PC_DATA_CTL_D),
.DI_DURATION ( PC_DI_DURATION ),
.DO_DURATION ( PC_DO_DURATION ),
.EVENTS_DELAY ( PC_EVENTS_DELAY),
.FOUR_WINDOW_CLOCKS ( PC_FOUR_WINDOW_CLOCKS),
.MULTI_REGION ( PC_MULTI_REGION ),
.PHY_COUNT_ENABLE ( PC_PHY_COUNT_EN),
.DISABLE_SEQ_MATCH ( PC_DISABLE_SEQ_MATCH),
.SYNC_MODE ( PC_SYNC_MODE),
.CMD_OFFSET ( PC_CMD_OFFSET),
.RD_CMD_OFFSET_0 ( PC_RD_CMD_OFFSET_0),
.RD_CMD_OFFSET_1 ( PC_RD_CMD_OFFSET_1),
.RD_CMD_OFFSET_2 ( PC_RD_CMD_OFFSET_2),
.RD_CMD_OFFSET_3 ( PC_RD_CMD_OFFSET_3),
.RD_DURATION_0 ( PC_RD_DURATION_0),
.RD_DURATION_1 ( PC_RD_DURATION_1),
.RD_DURATION_2 ( PC_RD_DURATION_2),
.RD_DURATION_3 ( PC_RD_DURATION_3),
.WR_CMD_OFFSET_0 ( PC_WR_CMD_OFFSET_0),
.WR_CMD_OFFSET_1 ( PC_WR_CMD_OFFSET_1),
.WR_CMD_OFFSET_2 ( PC_WR_CMD_OFFSET_2),
.WR_CMD_OFFSET_3 ( PC_WR_CMD_OFFSET_3),
.WR_DURATION_0 ( PC_WR_DURATION_0),
.WR_DURATION_1 ( PC_WR_DURATION_1),
.WR_DURATION_2 ( PC_WR_DURATION_2),
.WR_DURATION_3 ( PC_WR_DURATION_3)
) phy_control_i (
.AUXOUTPUT (aux_out),
.INBURSTPENDING (phaser_ctl_bus[MSB_BURST_PEND_PI:MSB_BURST_PEND_PI-3]),
.INRANKA (in_rank[1:0]),
.INRANKB (in_rank[3:2]),
.INRANKC (in_rank[5:4]),
.INRANKD (in_rank[7:6]),
.OUTBURSTPENDING (phaser_ctl_bus[MSB_BURST_PEND_PO:MSB_BURST_PEND_PO-3]),
.PCENABLECALIB (phy_encalib),
.PHYCTLALMOSTFULL (phy_ctl_a_full),
.PHYCTLEMPTY (phy_ctl_empty),
.PHYCTLFULL (phy_ctl_full),
.PHYCTLREADY (phy_ctl_ready),
.MEMREFCLK (mem_refclk),
.PHYCLK (phy_ctl_clk),
.PHYCTLMSTREMPTY (phy_ctl_mstr_empty),
.PHYCTLWD (_phy_ctl_wd),
.PHYCTLWRENABLE (phy_ctl_wr),
.PLLLOCK (pll_lock),
.REFDLLLOCK (ref_dll_lock), // is reset while !locked
.RESET (rst),
.SYNCIN (sync_pulse),
.READCALIBENABLE (phy_read_calib),
.WRITECALIBENABLE (phy_write_calib)
`ifdef USE_PHY_CONTROL_TEST
, .TESTINPUT (16'b0),
.TESTOUTPUT (test_output),
.TESTSELECT (test_select),
.SCANENABLEN (scan_enable)
`endif
);
// register outputs to give extra slack in timing
always @(posedge phy_clk ) begin
case (calib_sel[1:0])
2'h0: begin
po_coarse_overflow <= #1 A_po_coarse_overflow;
po_fine_overflow <= #1 A_po_fine_overflow;
po_counter_read_val <= #1 A_po_counter_read_val;
pi_fine_overflow <= #1 A_pi_fine_overflow;
pi_counter_read_val<= #1 A_pi_counter_read_val;
pi_phase_locked <= #1 A_pi_phase_locked;
if ( calib_in_common)
pi_dqs_found <= #1 pi_dqs_found_any;
else
pi_dqs_found <= #1 A_pi_dqs_found;
pi_dqs_out_of_range <= #1 A_pi_dqs_out_of_range;
end
2'h1: begin
po_coarse_overflow <= #1 B_po_coarse_overflow;
po_fine_overflow <= #1 B_po_fine_overflow;
po_counter_read_val <= #1 B_po_counter_read_val;
pi_fine_overflow <= #1 B_pi_fine_overflow;
pi_counter_read_val <= #1 B_pi_counter_read_val;
pi_phase_locked <= #1 B_pi_phase_locked;
if ( calib_in_common)
pi_dqs_found <= #1 pi_dqs_found_any;
else
pi_dqs_found <= #1 B_pi_dqs_found;
pi_dqs_out_of_range <= #1 B_pi_dqs_out_of_range;
end
2'h2: begin
po_coarse_overflow <= #1 C_po_coarse_overflow;
po_fine_overflow <= #1 C_po_fine_overflow;
po_counter_read_val <= #1 C_po_counter_read_val;
pi_fine_overflow <= #1 C_pi_fine_overflow;
pi_counter_read_val <= #1 C_pi_counter_read_val;
pi_phase_locked <= #1 C_pi_phase_locked;
if ( calib_in_common)
pi_dqs_found <= #1 pi_dqs_found_any;
else
pi_dqs_found <= #1 C_pi_dqs_found;
pi_dqs_out_of_range <= #1 C_pi_dqs_out_of_range;
end
2'h3: begin
po_coarse_overflow <= #1 D_po_coarse_overflow;
po_fine_overflow <= #1 D_po_fine_overflow;
po_counter_read_val <= #1 D_po_counter_read_val;
pi_fine_overflow <= #1 D_pi_fine_overflow;
pi_counter_read_val <= #1 D_pi_counter_read_val;
pi_phase_locked <= #1 D_pi_phase_locked;
if ( calib_in_common)
pi_dqs_found <= #1 pi_dqs_found_any;
else
pi_dqs_found <= #1 D_pi_dqs_found;
pi_dqs_out_of_range <= #1 D_pi_dqs_out_of_range;
end
default: begin
po_coarse_overflow <= po_coarse_overflow;
end
endcase
end
wire B_mux_ctrl;
wire C_mux_ctrl;
wire D_mux_ctrl;
generate
if (HIGHEST_LANE > 1)
assign B_mux_ctrl = ( !calib_zero_lanes[1] && ( ! calib_zero_ctrl || DATA_CTL_N[1]));
else
assign B_mux_ctrl = 0;
if (HIGHEST_LANE > 2)
assign C_mux_ctrl = ( !calib_zero_lanes[2] && (! calib_zero_ctrl || DATA_CTL_N[2]));
else
assign C_mux_ctrl = 0;
if (HIGHEST_LANE > 3)
assign D_mux_ctrl = ( !calib_zero_lanes[3] && ( ! calib_zero_ctrl || DATA_CTL_N[3]));
else
assign D_mux_ctrl = 0;
endgenerate
always @(*) begin
A_pi_fine_enable = 0;
A_pi_fine_inc = 0;
A_pi_counter_load_en = 0;
A_pi_counter_read_en = 0;
A_pi_counter_load_val = 0;
A_pi_rst_dqs_find = 0;
A_po_fine_enable = 0;
A_po_coarse_enable = 0;
A_po_fine_inc = 0;
A_po_coarse_inc = 0;
A_po_counter_load_en = 0;
A_po_counter_read_en = 0;
A_po_counter_load_val = 0;
A_po_sel_fine_oclk_delay = 0;
A_idelay_ce = 0;
A_idelay_ld = 0;
B_pi_fine_enable = 0;
B_pi_fine_inc = 0;
B_pi_counter_load_en = 0;
B_pi_counter_read_en = 0;
B_pi_counter_load_val = 0;
B_pi_rst_dqs_find = 0;
B_po_fine_enable = 0;
B_po_coarse_enable = 0;
B_po_fine_inc = 0;
B_po_coarse_inc = 0;
B_po_counter_load_en = 0;
B_po_counter_read_en = 0;
B_po_counter_load_val = 0;
B_po_sel_fine_oclk_delay = 0;
B_idelay_ce = 0;
B_idelay_ld = 0;
C_pi_fine_enable = 0;
C_pi_fine_inc = 0;
C_pi_counter_load_en = 0;
C_pi_counter_read_en = 0;
C_pi_counter_load_val = 0;
C_pi_rst_dqs_find = 0;
C_po_fine_enable = 0;
C_po_coarse_enable = 0;
C_po_fine_inc = 0;
C_po_coarse_inc = 0;
C_po_counter_load_en = 0;
C_po_counter_read_en = 0;
C_po_counter_load_val = 0;
C_po_sel_fine_oclk_delay = 0;
C_idelay_ce = 0;
C_idelay_ld = 0;
D_pi_fine_enable = 0;
D_pi_fine_inc = 0;
D_pi_counter_load_en = 0;
D_pi_counter_read_en = 0;
D_pi_counter_load_val = 0;
D_pi_rst_dqs_find = 0;
D_po_fine_enable = 0;
D_po_coarse_enable = 0;
D_po_fine_inc = 0;
D_po_coarse_inc = 0;
D_po_counter_load_en = 0;
D_po_counter_read_en = 0;
D_po_counter_load_val = 0;
D_po_sel_fine_oclk_delay = 0;
D_idelay_ce = 0;
D_idelay_ld = 0;
if ( calib_sel[2]) begin
// if this is asserted, all calib signals are deasserted
A_pi_fine_enable = 0;
A_pi_fine_inc = 0;
A_pi_counter_load_en = 0;
A_pi_counter_read_en = 0;
A_pi_counter_load_val = 0;
A_pi_rst_dqs_find = 0;
A_po_fine_enable = 0;
A_po_coarse_enable = 0;
A_po_fine_inc = 0;
A_po_coarse_inc = 0;
A_po_counter_load_en = 0;
A_po_counter_read_en = 0;
A_po_counter_load_val = 0;
A_po_sel_fine_oclk_delay = 0;
A_idelay_ce = 0;
A_idelay_ld = 0;
B_pi_fine_enable = 0;
B_pi_fine_inc = 0;
B_pi_counter_load_en = 0;
B_pi_counter_read_en = 0;
B_pi_counter_load_val = 0;
B_pi_rst_dqs_find = 0;
B_po_fine_enable = 0;
B_po_coarse_enable = 0;
B_po_fine_inc = 0;
B_po_coarse_inc = 0;
B_po_counter_load_en = 0;
B_po_counter_read_en = 0;
B_po_counter_load_val = 0;
B_po_sel_fine_oclk_delay = 0;
B_idelay_ce = 0;
B_idelay_ld = 0;
C_pi_fine_enable = 0;
C_pi_fine_inc = 0;
C_pi_counter_load_en = 0;
C_pi_counter_read_en = 0;
C_pi_counter_load_val = 0;
C_pi_rst_dqs_find = 0;
C_po_fine_enable = 0;
C_po_coarse_enable = 0;
C_po_fine_inc = 0;
C_po_coarse_inc = 0;
C_po_counter_load_en = 0;
C_po_counter_read_en = 0;
C_po_counter_load_val = 0;
C_po_sel_fine_oclk_delay = 0;
C_idelay_ce = 0;
C_idelay_ld = 0;
D_pi_fine_enable = 0;
D_pi_fine_inc = 0;
D_pi_counter_load_en = 0;
D_pi_counter_read_en = 0;
D_pi_counter_load_val = 0;
D_pi_rst_dqs_find = 0;
D_po_fine_enable = 0;
D_po_coarse_enable = 0;
D_po_fine_inc = 0;
D_po_coarse_inc = 0;
D_po_counter_load_en = 0;
D_po_counter_read_en = 0;
D_po_counter_load_val = 0;
D_po_sel_fine_oclk_delay = 0;
D_idelay_ce = 0;
D_idelay_ld = 0;
end else
if (calib_in_common) begin
// if this is asserted, each signal is broadcast to all phasers
// in common
if ( !calib_zero_lanes[0] && (! calib_zero_ctrl || DATA_CTL_N[0])) begin
A_pi_fine_enable = pi_fine_enable;
A_pi_fine_inc = pi_fine_inc;
A_pi_counter_load_en = pi_counter_load_en;
A_pi_counter_read_en = pi_counter_read_en;
A_pi_counter_load_val = pi_counter_load_val;
A_pi_rst_dqs_find = pi_rst_dqs_find;
A_po_fine_enable = po_fine_enable;
A_po_coarse_enable = po_coarse_enable;
A_po_fine_inc = po_fine_inc;
A_po_coarse_inc = po_coarse_inc;
A_po_counter_load_en = po_counter_load_en;
A_po_counter_read_en = po_counter_read_en;
A_po_counter_load_val = po_counter_load_val;
A_po_sel_fine_oclk_delay = po_sel_fine_oclk_delay;
A_idelay_ce = idelay_ce;
A_idelay_ld = idelay_ld;
end
if ( B_mux_ctrl) begin
B_pi_fine_enable = pi_fine_enable;
B_pi_fine_inc = pi_fine_inc;
B_pi_counter_load_en = pi_counter_load_en;
B_pi_counter_read_en = pi_counter_read_en;
B_pi_counter_load_val = pi_counter_load_val;
B_pi_rst_dqs_find = pi_rst_dqs_find;
B_po_fine_enable = po_fine_enable;
B_po_coarse_enable = po_coarse_enable;
B_po_fine_inc = po_fine_inc;
B_po_coarse_inc = po_coarse_inc;
B_po_counter_load_en = po_counter_load_en;
B_po_counter_read_en = po_counter_read_en;
B_po_counter_load_val = po_counter_load_val;
B_po_sel_fine_oclk_delay = po_sel_fine_oclk_delay;
B_idelay_ce = idelay_ce;
B_idelay_ld = idelay_ld;
end
if ( C_mux_ctrl) begin
C_pi_fine_enable = pi_fine_enable;
C_pi_fine_inc = pi_fine_inc;
C_pi_counter_load_en = pi_counter_load_en;
C_pi_counter_read_en = pi_counter_read_en;
C_pi_counter_load_val = pi_counter_load_val;
C_pi_rst_dqs_find = pi_rst_dqs_find;
C_po_fine_enable = po_fine_enable;
C_po_coarse_enable = po_coarse_enable;
C_po_fine_inc = po_fine_inc;
C_po_coarse_inc = po_coarse_inc;
C_po_counter_load_en = po_counter_load_en;
C_po_counter_read_en = po_counter_read_en;
C_po_counter_load_val = po_counter_load_val;
C_po_sel_fine_oclk_delay = po_sel_fine_oclk_delay;
C_idelay_ce = idelay_ce;
C_idelay_ld = idelay_ld;
end
if ( D_mux_ctrl) begin
D_pi_fine_enable = pi_fine_enable;
D_pi_fine_inc = pi_fine_inc;
D_pi_counter_load_en = pi_counter_load_en;
D_pi_counter_read_en = pi_counter_read_en;
D_pi_counter_load_val = pi_counter_load_val;
D_pi_rst_dqs_find = pi_rst_dqs_find;
D_po_fine_enable = po_fine_enable;
D_po_coarse_enable = po_coarse_enable;
D_po_fine_inc = po_fine_inc;
D_po_coarse_inc = po_coarse_inc;
D_po_counter_load_en = po_counter_load_en;
D_po_counter_read_en = po_counter_read_en;
D_po_counter_load_val = po_counter_load_val;
D_po_sel_fine_oclk_delay = po_sel_fine_oclk_delay;
D_idelay_ce = idelay_ce;
D_idelay_ld = idelay_ld;
end
end
else begin
// otherwise, only a single phaser is selected
case (calib_sel[1:0])
0: begin
A_pi_fine_enable = pi_fine_enable;
A_pi_fine_inc = pi_fine_inc;
A_pi_counter_load_en = pi_counter_load_en;
A_pi_counter_read_en = pi_counter_read_en;
A_pi_counter_load_val = pi_counter_load_val;
A_pi_rst_dqs_find = pi_rst_dqs_find;
A_po_fine_enable = po_fine_enable;
A_po_coarse_enable = po_coarse_enable;
A_po_fine_inc = po_fine_inc;
A_po_coarse_inc = po_coarse_inc;
A_po_counter_load_en = po_counter_load_en;
A_po_counter_read_en = po_counter_read_en;
A_po_counter_load_val = po_counter_load_val;
A_po_sel_fine_oclk_delay = po_sel_fine_oclk_delay;
A_idelay_ce = idelay_ce;
A_idelay_ld = idelay_ld;
end
1: begin
B_pi_fine_enable = pi_fine_enable;
B_pi_fine_inc = pi_fine_inc;
B_pi_counter_load_en = pi_counter_load_en;
B_pi_counter_read_en = pi_counter_read_en;
B_pi_counter_load_val = pi_counter_load_val;
B_pi_rst_dqs_find = pi_rst_dqs_find;
B_po_fine_enable = po_fine_enable;
B_po_coarse_enable = po_coarse_enable;
B_po_fine_inc = po_fine_inc;
B_po_coarse_inc = po_coarse_inc;
B_po_counter_load_en = po_counter_load_en;
B_po_counter_read_en = po_counter_read_en;
B_po_counter_load_val = po_counter_load_val;
B_po_sel_fine_oclk_delay = po_sel_fine_oclk_delay;
B_idelay_ce = idelay_ce;
B_idelay_ld = idelay_ld;
end
2: begin
C_pi_fine_enable = pi_fine_enable;
C_pi_fine_inc = pi_fine_inc;
C_pi_counter_load_en = pi_counter_load_en;
C_pi_counter_read_en = pi_counter_read_en;
C_pi_counter_load_val = pi_counter_load_val;
C_pi_rst_dqs_find = pi_rst_dqs_find;
C_po_fine_enable = po_fine_enable;
C_po_coarse_enable = po_coarse_enable;
C_po_fine_inc = po_fine_inc;
C_po_coarse_inc = po_coarse_inc;
C_po_counter_load_en = po_counter_load_en;
C_po_counter_read_en = po_counter_read_en;
C_po_counter_load_val = po_counter_load_val;
C_po_sel_fine_oclk_delay = po_sel_fine_oclk_delay;
C_idelay_ce = idelay_ce;
C_idelay_ld = idelay_ld;
end
3: begin
D_pi_fine_enable = pi_fine_enable;
D_pi_fine_inc = pi_fine_inc;
D_pi_counter_load_en = pi_counter_load_en;
D_pi_counter_read_en = pi_counter_read_en;
D_pi_counter_load_val = pi_counter_load_val;
D_pi_rst_dqs_find = pi_rst_dqs_find;
D_po_fine_enable = po_fine_enable;
D_po_coarse_enable = po_coarse_enable;
D_po_fine_inc = po_fine_inc;
D_po_coarse_inc = po_coarse_inc;
D_po_counter_load_en = po_counter_load_en;
D_po_counter_load_val = po_counter_load_val;
D_po_counter_read_en = po_counter_read_en;
D_po_sel_fine_oclk_delay = po_sel_fine_oclk_delay;
D_idelay_ce = idelay_ce;
D_idelay_ld = idelay_ld;
end
endcase
end
end
//obligatory phaser-ref
PHASER_REF phaser_ref_i(
.LOCKED (ref_dll_lock),
.CLKIN (freq_refclk),
.PWRDWN (1'b0),
.RST ( ! pll_lock)
);
// optional idelay_ctrl
generate
if ( GENERATE_IDELAYCTRL == "TRUE")
IDELAYCTRL idelayctrl (
.RDY (/*idelayctrl_rdy*/),
.REFCLK (idelayctrl_refclk),
.RST (rst)
);
endgenerate
endmodule
|
//*****************************************************************************
// (c) Copyright 2009 - 2013 Xilinx, Inc. All rights reserved.
//
// This file contains confidential and proprietary information
// of Xilinx, Inc. and is protected under U.S. and
// international copyright and other intellectual property
// laws.
//
// DISCLAIMER
// This disclaimer is not a license and does not grant any
// rights to the materials distributed herewith. Except as
// otherwise provided in a valid license issued to you by
// Xilinx, and to the maximum extent permitted by applicable
// law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND
// WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES
// AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
// BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-
// INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and
// (2) Xilinx shall not be liable (whether in contract or tort,
// including negligence, or under any other theory of
// liability) for any loss or damage of any kind or nature
// related to, arising under or in connection with these
// materials, including for any direct, or any indirect,
// special, incidental, or consequential loss or damage
// (including loss of data, profits, goodwill, or any type of
// loss or damage suffered as a result of any action brought
// by a third party) even if such damage or loss was
// reasonably foreseeable or Xilinx had been advised of the
// possibility of the same.
//
// CRITICAL APPLICATIONS
// Xilinx products are not designed or intended to be fail-
// safe, or for use in any application requiring fail-safe
// performance, such as life-support or safety devices or
// systems, Class III medical devices, nuclear facilities,
// applications related to the deployment of airbags, or any
// other applications that could lead to death, personal
// injury, or severe property or environmental damage
// (individually and collectively, "Critical
// Applications"). Customer assumes the sole risk and
// liability of any use of Xilinx products in Critical
// Applications, subject only to applicable laws and
// regulations governing limitations on product liability.
//
// THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS
// PART OF THIS FILE AT ALL TIMES.
//
//*****************************************************************************
// ____ ____
// / /\/ /
// /___/ \ / Vendor: Xilinx
// \ \ \/ Version:
// \ \ Application: MIG
// / / Filename: ddr_phy_rdlvl.v
// /___/ /\ Date Last Modified: $Date: 2011/06/24 14:49:00 $
// \ \ / \ Date Created:
// \___\/\___\
//
//Device: 7 Series
//Design Name: DDR3 SDRAM
//Purpose:
// Read leveling Stage1 calibration logic
// NOTES:
// 1. Window detection with PRBS pattern.
//Reference:
//Revision History:
//*****************************************************************************
/******************************************************************************
**$Id: ddr_phy_rdlvl.v,v 1.2 2011/06/24 14:49:00 mgeorge Exp $
**$Date: 2011/06/24 14:49:00 $
**$Author: mgeorge $
**$Revision: 1.2 $
**$Source: /devl/xcs/repo/env/Databases/ip/src2/O/mig_7series_v1_3/data/dlib/7series/ddr3_sdram/verilog/rtl/phy/ddr_phy_rdlvl.v,v $
******************************************************************************/
`timescale 1ps/1ps
(* use_dsp48 = "no" *)
module mig_7series_v1_9_ddr_phy_rdlvl #
(
parameter TCQ = 100, // clk->out delay (sim only)
parameter nCK_PER_CLK = 2, // # of memory clocks per CLK
parameter CLK_PERIOD = 3333, // Internal clock period (in ps)
parameter DQ_WIDTH = 64, // # of DQ (data)
parameter DQS_CNT_WIDTH = 3, // = ceil(log2(DQS_WIDTH))
parameter DQS_WIDTH = 8, // # of DQS (strobe)
parameter DRAM_WIDTH = 8, // # of DQ per DQS
parameter RANKS = 1, // # of DRAM ranks
parameter PER_BIT_DESKEW = "ON", // Enable per-bit DQ deskew
parameter SIM_CAL_OPTION = "NONE", // Skip various calibration steps
parameter DEBUG_PORT = "OFF", // Enable debug port
parameter DRAM_TYPE = "DDR3", // Memory I/F type: "DDR3", "DDR2"
parameter OCAL_EN = "ON"
)
(
input clk,
input rst,
// Calibration status, control signals
input mpr_rdlvl_start,
output mpr_rdlvl_done,
output reg mpr_last_byte_done,
output mpr_rnk_done,
input rdlvl_stg1_start,
(* keep = "true", max_fanout = 30 *) output reg rdlvl_stg1_done /* synthesis syn_maxfan = 30 */,
output rdlvl_stg1_rnk_done,
output reg rdlvl_stg1_err,
output mpr_rdlvl_err,
output rdlvl_err,
output reg rdlvl_prech_req,
output reg rdlvl_last_byte_done,
output reg rdlvl_assrt_common,
input prech_done,
input phy_if_empty,
input [4:0] idelaye2_init_val,
// Captured data in fabric clock domain
input [2*nCK_PER_CLK*DQ_WIDTH-1:0] rd_data,
// Decrement initial Phaser_IN Fine tap delay
input dqs_po_dec_done,
input [5:0] pi_counter_read_val,
// Stage 1 calibration outputs
output reg pi_fine_dly_dec_done,
output reg pi_en_stg2_f,
output reg pi_stg2_f_incdec,
output reg pi_stg2_load,
output reg [5:0] pi_stg2_reg_l,
output [DQS_CNT_WIDTH:0] pi_stg2_rdlvl_cnt,
// To DQ IDELAY required to find left edge of
// valid window
output idelay_ce,
output idelay_inc,
input idelay_ld,
input [DQS_CNT_WIDTH:0] wrcal_cnt,
// Only output if Per-bit de-skew enabled
output reg [5*RANKS*DQ_WIDTH-1:0] dlyval_dq,
// Debug Port
output [6*DQS_WIDTH*RANKS-1:0] dbg_cpt_first_edge_cnt,
output [6*DQS_WIDTH*RANKS-1:0] dbg_cpt_second_edge_cnt,
output [6*DQS_WIDTH*RANKS-1:0] dbg_cpt_tap_cnt,
output [5*DQS_WIDTH*RANKS-1:0] dbg_dq_idelay_tap_cnt,
input dbg_idel_up_all,
input dbg_idel_down_all,
input dbg_idel_up_cpt,
input dbg_idel_down_cpt,
input [DQS_CNT_WIDTH-1:0] dbg_sel_idel_cpt,
input dbg_sel_all_idel_cpt,
output [255:0] dbg_phy_rdlvl
);
// minimum time (in IDELAY taps) for which capture data must be stable for
// algorithm to consider a valid data eye to be found. The read leveling
// logic will ignore any window found smaller than this value. Limitations
// on how small this number can be is determined by: (1) the algorithmic
// limitation of how many taps wide the data eye can be (3 taps), and (2)
// how wide regions of "instability" that occur around the edges of the
// read valid window can be (i.e. need to be able to filter out "false"
// windows that occur for a short # of taps around the edges of the true
// data window, although with multi-sampling during read leveling, this is
// not as much a concern) - the larger the value, the more protection
// against "false" windows
localparam MIN_EYE_SIZE = 16;
// Length of calibration sequence (in # of words)
localparam CAL_PAT_LEN = 8;
// Read data shift register length
localparam RD_SHIFT_LEN = CAL_PAT_LEN / (2*nCK_PER_CLK);
// # of cycles required to perform read data shift register compare
// This is defined as from the cycle the new data is loaded until
// signal found_edge_r is valid
localparam RD_SHIFT_COMP_DELAY = 5;
// worst-case # of cycles to wait to ensure that both the SR and
// PREV_SR shift registers have valid data, and that the comparison
// of the two shift register values is valid. The "+1" at the end of
// this equation is a fudge factor, I freely admit that
localparam SR_VALID_DELAY = (2 * RD_SHIFT_LEN) + RD_SHIFT_COMP_DELAY + 1;
// # of clock cycles to wait after changing tap value or read data MUX
// to allow: (1) tap chain to settle, (2) for delayed input to propagate
// thru ISERDES, (3) for the read data comparison logic to have time to
// output the comparison of two consecutive samples of the settled read data
// The minimum delay is 16 cycles, which should be good enough to handle all
// three of the above conditions for the simulation-only case with a short
// training pattern. For H/W (or for simulation with longer training
// pattern), it will take longer to store and compare two consecutive
// samples, and the value of this parameter will reflect that
localparam PIPE_WAIT_CNT = (SR_VALID_DELAY < 8) ? 16 : (SR_VALID_DELAY + 8);
// # of read data samples to examine when detecting whether an edge has
// occured during stage 1 calibration. Width of local param must be
// changed as appropriate. Note that there are two counters used, each
// counter can be changed independently of the other - they are used in
// cascade to create a larger counter
localparam [11:0] DETECT_EDGE_SAMPLE_CNT0 = 12'h001; //12'hFFF;
localparam [11:0] DETECT_EDGE_SAMPLE_CNT1 = 12'h001; // 12'h1FF Must be > 0
localparam [5:0] CAL1_IDLE = 6'h00;
localparam [5:0] CAL1_NEW_DQS_WAIT = 6'h01;
localparam [5:0] CAL1_STORE_FIRST_WAIT = 6'h02;
localparam [5:0] CAL1_PAT_DETECT = 6'h03;
localparam [5:0] CAL1_DQ_IDEL_TAP_INC = 6'h04;
localparam [5:0] CAL1_DQ_IDEL_TAP_INC_WAIT = 6'h05;
localparam [5:0] CAL1_DQ_IDEL_TAP_DEC = 6'h06;
localparam [5:0] CAL1_DQ_IDEL_TAP_DEC_WAIT = 6'h07;
localparam [5:0] CAL1_DETECT_EDGE = 6'h08;
localparam [5:0] CAL1_IDEL_INC_CPT = 6'h09;
localparam [5:0] CAL1_IDEL_INC_CPT_WAIT = 6'h0A;
localparam [5:0] CAL1_CALC_IDEL = 6'h0B;
localparam [5:0] CAL1_IDEL_DEC_CPT = 6'h0C;
localparam [5:0] CAL1_IDEL_DEC_CPT_WAIT = 6'h0D;
localparam [5:0] CAL1_NEXT_DQS = 6'h0E;
localparam [5:0] CAL1_DONE = 6'h0F;
localparam [5:0] CAL1_PB_STORE_FIRST_WAIT = 6'h10;
localparam [5:0] CAL1_PB_DETECT_EDGE = 6'h11;
localparam [5:0] CAL1_PB_INC_CPT = 6'h12;
localparam [5:0] CAL1_PB_INC_CPT_WAIT = 6'h13;
localparam [5:0] CAL1_PB_DEC_CPT_LEFT = 6'h14;
localparam [5:0] CAL1_PB_DEC_CPT_LEFT_WAIT = 6'h15;
localparam [5:0] CAL1_PB_DETECT_EDGE_DQ = 6'h16;
localparam [5:0] CAL1_PB_INC_DQ = 6'h17;
localparam [5:0] CAL1_PB_INC_DQ_WAIT = 6'h18;
localparam [5:0] CAL1_PB_DEC_CPT = 6'h19;
localparam [5:0] CAL1_PB_DEC_CPT_WAIT = 6'h1A;
localparam [5:0] CAL1_REGL_LOAD = 6'h1B;
localparam [5:0] CAL1_RDLVL_ERR = 6'h1C;
localparam [5:0] CAL1_MPR_NEW_DQS_WAIT = 6'h1D;
localparam [5:0] CAL1_VALID_WAIT = 6'h1E;
localparam [5:0] CAL1_MPR_PAT_DETECT = 6'h1F;
localparam [5:0] CAL1_NEW_DQS_PREWAIT = 6'h20;
integer a;
integer b;
integer d;
integer e;
integer f;
integer h;
integer g;
integer i;
integer j;
integer k;
integer l;
integer m;
integer n;
integer r;
integer p;
integer q;
integer s;
integer t;
integer u;
integer w;
integer ce_i;
integer ce_rnk_i;
integer aa;
integer bb;
integer cc;
integer dd;
genvar x;
genvar z;
reg [DQS_CNT_WIDTH:0] cal1_cnt_cpt_r;
wire [DQS_CNT_WIDTH+2:0]cal1_cnt_cpt_timing;
reg [DQS_CNT_WIDTH:0] cal1_cnt_cpt_timing_r;
reg cal1_dq_idel_ce;
reg cal1_dq_idel_inc;
reg cal1_dlyce_cpt_r;
reg cal1_dlyinc_cpt_r;
reg cal1_dlyce_dq_r;
reg cal1_dlyinc_dq_r;
reg cal1_wait_cnt_en_r;
reg [4:0] cal1_wait_cnt_r;
reg cal1_wait_r;
reg [DQ_WIDTH-1:0] dlyce_dq_r;
reg dlyinc_dq_r;
reg [4:0] dlyval_dq_reg_r [0:RANKS-1][0:DQ_WIDTH-1];
reg cal1_prech_req_r;
reg [5:0] cal1_state_r;
reg [5:0] cal1_state_r1;
reg [5:0] cnt_idel_dec_cpt_r;
reg [3:0] cnt_shift_r;
reg detect_edge_done_r;
reg [5:0] right_edge_taps_r;
reg [5:0] first_edge_taps_r;
reg found_edge_r;
reg found_first_edge_r;
reg found_second_edge_r;
reg found_stable_eye_r;
reg found_stable_eye_last_r;
reg found_edge_all_r;
reg [5:0] tap_cnt_cpt_r;
reg tap_limit_cpt_r;
reg [4:0] idel_tap_cnt_dq_pb_r;
reg idel_tap_limit_dq_pb_r;
reg [DRAM_WIDTH-1:0] mux_rd_fall0_r;
reg [DRAM_WIDTH-1:0] mux_rd_fall1_r;
reg [DRAM_WIDTH-1:0] mux_rd_rise0_r;
reg [DRAM_WIDTH-1:0] mux_rd_rise1_r;
reg [DRAM_WIDTH-1:0] mux_rd_fall2_r;
reg [DRAM_WIDTH-1:0] mux_rd_fall3_r;
reg [DRAM_WIDTH-1:0] mux_rd_rise2_r;
reg [DRAM_WIDTH-1:0] mux_rd_rise3_r;
reg mux_rd_valid_r;
reg new_cnt_cpt_r;
reg [RD_SHIFT_LEN-1:0] old_sr_fall0_r [DRAM_WIDTH-1:0];
reg [RD_SHIFT_LEN-1:0] old_sr_fall1_r [DRAM_WIDTH-1:0];
reg [RD_SHIFT_LEN-1:0] old_sr_rise0_r [DRAM_WIDTH-1:0];
reg [RD_SHIFT_LEN-1:0] old_sr_rise1_r [DRAM_WIDTH-1:0];
reg [RD_SHIFT_LEN-1:0] old_sr_fall2_r [DRAM_WIDTH-1:0];
reg [RD_SHIFT_LEN-1:0] old_sr_fall3_r [DRAM_WIDTH-1:0];
reg [RD_SHIFT_LEN-1:0] old_sr_rise2_r [DRAM_WIDTH-1:0];
reg [RD_SHIFT_LEN-1:0] old_sr_rise3_r [DRAM_WIDTH-1:0];
reg [DRAM_WIDTH-1:0] old_sr_match_fall0_r;
reg [DRAM_WIDTH-1:0] old_sr_match_fall1_r;
reg [DRAM_WIDTH-1:0] old_sr_match_rise0_r;
reg [DRAM_WIDTH-1:0] old_sr_match_rise1_r;
reg [DRAM_WIDTH-1:0] old_sr_match_fall2_r;
reg [DRAM_WIDTH-1:0] old_sr_match_fall3_r;
reg [DRAM_WIDTH-1:0] old_sr_match_rise2_r;
reg [DRAM_WIDTH-1:0] old_sr_match_rise3_r;
reg [4:0] pb_cnt_eye_size_r [DRAM_WIDTH-1:0];
reg [DRAM_WIDTH-1:0] pb_detect_edge_done_r;
reg [DRAM_WIDTH-1:0] pb_found_edge_last_r;
reg [DRAM_WIDTH-1:0] pb_found_edge_r;
reg [DRAM_WIDTH-1:0] pb_found_first_edge_r;
reg [DRAM_WIDTH-1:0] pb_found_stable_eye_r;
reg [DRAM_WIDTH-1:0] pb_last_tap_jitter_r;
reg pi_en_stg2_f_timing;
reg pi_stg2_f_incdec_timing;
reg pi_stg2_load_timing;
reg [5:0] pi_stg2_reg_l_timing;
reg [DRAM_WIDTH-1:0] prev_sr_diff_r;
reg [RD_SHIFT_LEN-1:0] prev_sr_fall0_r [DRAM_WIDTH-1:0];
reg [RD_SHIFT_LEN-1:0] prev_sr_fall1_r [DRAM_WIDTH-1:0];
reg [RD_SHIFT_LEN-1:0] prev_sr_rise0_r [DRAM_WIDTH-1:0];
reg [RD_SHIFT_LEN-1:0] prev_sr_rise1_r [DRAM_WIDTH-1:0];
reg [RD_SHIFT_LEN-1:0] prev_sr_fall2_r [DRAM_WIDTH-1:0];
reg [RD_SHIFT_LEN-1:0] prev_sr_fall3_r [DRAM_WIDTH-1:0];
reg [RD_SHIFT_LEN-1:0] prev_sr_rise2_r [DRAM_WIDTH-1:0];
reg [RD_SHIFT_LEN-1:0] prev_sr_rise3_r [DRAM_WIDTH-1:0];
reg [DRAM_WIDTH-1:0] prev_sr_match_cyc2_r;
reg [DRAM_WIDTH-1:0] prev_sr_match_fall0_r;
reg [DRAM_WIDTH-1:0] prev_sr_match_fall1_r;
reg [DRAM_WIDTH-1:0] prev_sr_match_rise0_r;
reg [DRAM_WIDTH-1:0] prev_sr_match_rise1_r;
reg [DRAM_WIDTH-1:0] prev_sr_match_fall2_r;
reg [DRAM_WIDTH-1:0] prev_sr_match_fall3_r;
reg [DRAM_WIDTH-1:0] prev_sr_match_rise2_r;
reg [DRAM_WIDTH-1:0] prev_sr_match_rise3_r;
wire [DQ_WIDTH-1:0] rd_data_rise0;
wire [DQ_WIDTH-1:0] rd_data_fall0;
wire [DQ_WIDTH-1:0] rd_data_rise1;
wire [DQ_WIDTH-1:0] rd_data_fall1;
wire [DQ_WIDTH-1:0] rd_data_rise2;
wire [DQ_WIDTH-1:0] rd_data_fall2;
wire [DQ_WIDTH-1:0] rd_data_rise3;
wire [DQ_WIDTH-1:0] rd_data_fall3;
reg samp_cnt_done_r;
reg samp_edge_cnt0_en_r;
reg [11:0] samp_edge_cnt0_r;
reg samp_edge_cnt1_en_r;
reg [11:0] samp_edge_cnt1_r;
reg [DQS_CNT_WIDTH:0] rd_mux_sel_r;
reg [5:0] second_edge_taps_r;
reg [RD_SHIFT_LEN-1:0] sr_fall0_r [DRAM_WIDTH-1:0];
reg [RD_SHIFT_LEN-1:0] sr_fall1_r [DRAM_WIDTH-1:0];
reg [RD_SHIFT_LEN-1:0] sr_rise0_r [DRAM_WIDTH-1:0];
reg [RD_SHIFT_LEN-1:0] sr_rise1_r [DRAM_WIDTH-1:0];
reg [RD_SHIFT_LEN-1:0] sr_fall2_r [DRAM_WIDTH-1:0];
reg [RD_SHIFT_LEN-1:0] sr_fall3_r [DRAM_WIDTH-1:0];
reg [RD_SHIFT_LEN-1:0] sr_rise2_r [DRAM_WIDTH-1:0];
reg [RD_SHIFT_LEN-1:0] sr_rise3_r [DRAM_WIDTH-1:0];
reg store_sr_r;
reg store_sr_req_pulsed_r;
reg store_sr_req_r;
reg sr_valid_r;
reg sr_valid_r1;
reg sr_valid_r2;
reg [DRAM_WIDTH-1:0] old_sr_diff_r;
reg [DRAM_WIDTH-1:0] old_sr_match_cyc2_r;
reg pat0_data_match_r;
reg pat1_data_match_r;
wire pat_data_match_r;
wire [RD_SHIFT_LEN-1:0] pat0_fall0 [3:0];
wire [RD_SHIFT_LEN-1:0] pat0_fall1 [3:0];
wire [RD_SHIFT_LEN-1:0] pat0_fall2 [3:0];
wire [RD_SHIFT_LEN-1:0] pat0_fall3 [3:0];
wire [RD_SHIFT_LEN-1:0] pat1_fall0 [3:0];
wire [RD_SHIFT_LEN-1:0] pat1_fall1 [3:0];
wire [RD_SHIFT_LEN-1:0] pat1_fall2 [3:0];
wire [RD_SHIFT_LEN-1:0] pat1_fall3 [3:0];
reg [DRAM_WIDTH-1:0] pat0_match_fall0_r;
reg pat0_match_fall0_and_r;
reg [DRAM_WIDTH-1:0] pat0_match_fall1_r;
reg pat0_match_fall1_and_r;
reg [DRAM_WIDTH-1:0] pat0_match_fall2_r;
reg pat0_match_fall2_and_r;
reg [DRAM_WIDTH-1:0] pat0_match_fall3_r;
reg pat0_match_fall3_and_r;
reg [DRAM_WIDTH-1:0] pat0_match_rise0_r;
reg pat0_match_rise0_and_r;
reg [DRAM_WIDTH-1:0] pat0_match_rise1_r;
reg pat0_match_rise1_and_r;
reg [DRAM_WIDTH-1:0] pat0_match_rise2_r;
reg pat0_match_rise2_and_r;
reg [DRAM_WIDTH-1:0] pat0_match_rise3_r;
reg pat0_match_rise3_and_r;
reg [DRAM_WIDTH-1:0] pat1_match_fall0_r;
reg pat1_match_fall0_and_r;
reg [DRAM_WIDTH-1:0] pat1_match_fall1_r;
reg pat1_match_fall1_and_r;
reg [DRAM_WIDTH-1:0] pat1_match_fall2_r;
reg pat1_match_fall2_and_r;
reg [DRAM_WIDTH-1:0] pat1_match_fall3_r;
reg pat1_match_fall3_and_r;
reg [DRAM_WIDTH-1:0] pat1_match_rise0_r;
reg pat1_match_rise0_and_r;
reg [DRAM_WIDTH-1:0] pat1_match_rise1_r;
reg pat1_match_rise1_and_r;
reg [DRAM_WIDTH-1:0] pat1_match_rise2_r;
reg pat1_match_rise2_and_r;
reg [DRAM_WIDTH-1:0] pat1_match_rise3_r;
reg pat1_match_rise3_and_r;
reg [4:0] idelay_tap_cnt_r [0:RANKS-1][0:DQS_WIDTH-1];
reg [5*DQS_WIDTH*RANKS-1:0] idelay_tap_cnt_w;
reg [4:0] idelay_tap_cnt_slice_r;
reg idelay_tap_limit_r;
wire [RD_SHIFT_LEN-1:0] pat0_rise0 [3:0];
wire [RD_SHIFT_LEN-1:0] pat0_rise1 [3:0];
wire [RD_SHIFT_LEN-1:0] pat0_rise2 [3:0];
wire [RD_SHIFT_LEN-1:0] pat0_rise3 [3:0];
wire [RD_SHIFT_LEN-1:0] pat1_rise0 [3:0];
wire [RD_SHIFT_LEN-1:0] pat1_rise1 [3:0];
wire [RD_SHIFT_LEN-1:0] pat1_rise2 [3:0];
wire [RD_SHIFT_LEN-1:0] pat1_rise3 [3:0];
wire [RD_SHIFT_LEN-1:0] idel_pat0_rise0 [3:0];
wire [RD_SHIFT_LEN-1:0] idel_pat0_fall0 [3:0];
wire [RD_SHIFT_LEN-1:0] idel_pat0_rise1 [3:0];
wire [RD_SHIFT_LEN-1:0] idel_pat0_fall1 [3:0];
wire [RD_SHIFT_LEN-1:0] idel_pat0_rise2 [3:0];
wire [RD_SHIFT_LEN-1:0] idel_pat0_fall2 [3:0];
wire [RD_SHIFT_LEN-1:0] idel_pat0_rise3 [3:0];
wire [RD_SHIFT_LEN-1:0] idel_pat0_fall3 [3:0];
wire [RD_SHIFT_LEN-1:0] idel_pat1_rise0 [3:0];
wire [RD_SHIFT_LEN-1:0] idel_pat1_fall0 [3:0];
wire [RD_SHIFT_LEN-1:0] idel_pat1_rise1 [3:0];
wire [RD_SHIFT_LEN-1:0] idel_pat1_fall1 [3:0];
wire [RD_SHIFT_LEN-1:0] idel_pat1_rise2 [3:0];
wire [RD_SHIFT_LEN-1:0] idel_pat1_fall2 [3:0];
wire [RD_SHIFT_LEN-1:0] idel_pat1_rise3 [3:0];
wire [RD_SHIFT_LEN-1:0] idel_pat1_fall3 [3:0];
reg [DRAM_WIDTH-1:0] idel_pat0_match_rise0_r;
reg [DRAM_WIDTH-1:0] idel_pat0_match_fall0_r;
reg [DRAM_WIDTH-1:0] idel_pat0_match_rise1_r;
reg [DRAM_WIDTH-1:0] idel_pat0_match_fall1_r;
reg [DRAM_WIDTH-1:0] idel_pat0_match_rise2_r;
reg [DRAM_WIDTH-1:0] idel_pat0_match_fall2_r;
reg [DRAM_WIDTH-1:0] idel_pat0_match_rise3_r;
reg [DRAM_WIDTH-1:0] idel_pat0_match_fall3_r;
reg [DRAM_WIDTH-1:0] idel_pat1_match_rise0_r;
reg [DRAM_WIDTH-1:0] idel_pat1_match_fall0_r;
reg [DRAM_WIDTH-1:0] idel_pat1_match_rise1_r;
reg [DRAM_WIDTH-1:0] idel_pat1_match_fall1_r;
reg [DRAM_WIDTH-1:0] idel_pat1_match_rise2_r;
reg [DRAM_WIDTH-1:0] idel_pat1_match_fall2_r;
reg [DRAM_WIDTH-1:0] idel_pat1_match_rise3_r;
reg [DRAM_WIDTH-1:0] idel_pat1_match_fall3_r;
reg idel_pat0_match_rise0_and_r;
reg idel_pat0_match_fall0_and_r;
reg idel_pat0_match_rise1_and_r;
reg idel_pat0_match_fall1_and_r;
reg idel_pat0_match_rise2_and_r;
reg idel_pat0_match_fall2_and_r;
reg idel_pat0_match_rise3_and_r;
reg idel_pat0_match_fall3_and_r;
reg idel_pat1_match_rise0_and_r;
reg idel_pat1_match_fall0_and_r;
reg idel_pat1_match_rise1_and_r;
reg idel_pat1_match_fall1_and_r;
reg idel_pat1_match_rise2_and_r;
reg idel_pat1_match_fall2_and_r;
reg idel_pat1_match_rise3_and_r;
reg idel_pat1_match_fall3_and_r;
reg idel_pat0_data_match_r;
reg idel_pat1_data_match_r;
reg idel_pat_data_match;
reg idel_pat_data_match_r;
reg [4:0] idel_dec_cnt;
reg [5:0] rdlvl_dqs_tap_cnt_r [0:RANKS-1][0:DQS_WIDTH-1];
reg [1:0] rnk_cnt_r;
reg rdlvl_rank_done_r;
reg [3:0] done_cnt;
reg [1:0] regl_rank_cnt;
reg [DQS_CNT_WIDTH:0] regl_dqs_cnt;
reg [DQS_CNT_WIDTH:0] regl_dqs_cnt_r;
wire [DQS_CNT_WIDTH+2:0]regl_dqs_cnt_timing;
reg regl_rank_done_r;
reg rdlvl_stg1_start_r;
reg dqs_po_dec_done_r1;
reg dqs_po_dec_done_r2;
reg fine_dly_dec_done_r1;
reg fine_dly_dec_done_r2;
reg [3:0] wait_cnt_r;
reg [5:0] pi_rdval_cnt;
reg pi_cnt_dec;
reg mpr_valid_r;
reg mpr_valid_r1;
reg mpr_valid_r2;
reg mpr_rd_rise0_prev_r;
reg mpr_rd_fall0_prev_r;
reg mpr_rd_rise1_prev_r;
reg mpr_rd_fall1_prev_r;
reg mpr_rd_rise2_prev_r;
reg mpr_rd_fall2_prev_r;
reg mpr_rd_rise3_prev_r;
reg mpr_rd_fall3_prev_r;
reg mpr_rdlvl_done_r;
reg mpr_rdlvl_done_r1;
reg mpr_rdlvl_done_r2;
reg mpr_rdlvl_start_r;
reg mpr_rank_done_r;
reg [2:0] stable_idel_cnt;
reg inhibit_edge_detect_r;
reg idel_pat_detect_valid_r;
reg idel_mpr_pat_detect_r;
reg mpr_pat_detect_r;
reg mpr_dec_cpt_r;
// Debug
reg [6*DQS_WIDTH*RANKS-1:0] dbg_cpt_first_edge_taps;
reg [6*DQS_WIDTH*RANKS-1:0] dbg_cpt_second_edge_taps;
reg [6*DQS_WIDTH*RANKS-1:0] dbg_cpt_tap_cnt_w;
//***************************************************************************
// Debug
//***************************************************************************
always @(*) begin
for (d = 0; d < RANKS; d = d + 1) begin
for (e = 0; e < DQS_WIDTH; e = e + 1) begin
idelay_tap_cnt_w[(5*e+5*DQS_WIDTH*d)+:5] <= #TCQ idelay_tap_cnt_r[d][e];
dbg_cpt_tap_cnt_w[(6*e+6*DQS_WIDTH*d)+:6] <= #TCQ rdlvl_dqs_tap_cnt_r[d][e];
end
end
end
assign mpr_rdlvl_err = rdlvl_stg1_err & (!mpr_rdlvl_done);
assign rdlvl_err = rdlvl_stg1_err & (mpr_rdlvl_done);
assign dbg_phy_rdlvl[0] = rdlvl_stg1_start;
assign dbg_phy_rdlvl[1] = pat_data_match_r;
assign dbg_phy_rdlvl[2] = mux_rd_valid_r;
assign dbg_phy_rdlvl[3] = idelay_tap_limit_r;
assign dbg_phy_rdlvl[8:4] = 'b0;
assign dbg_phy_rdlvl[14:9] = cal1_state_r[5:0];
assign dbg_phy_rdlvl[20:15] = cnt_idel_dec_cpt_r;
assign dbg_phy_rdlvl[21] = found_first_edge_r;
assign dbg_phy_rdlvl[22] = found_second_edge_r;
assign dbg_phy_rdlvl[23] = found_edge_r;
assign dbg_phy_rdlvl[24] = store_sr_r;
// [40:25] previously used for sr, old_sr shift registers. If connecting
// these signals again, don't forget to parameterize based on RD_SHIFT_LEN
assign dbg_phy_rdlvl[40:25] = 'b0;
assign dbg_phy_rdlvl[41] = sr_valid_r;
assign dbg_phy_rdlvl[42] = found_stable_eye_r;
assign dbg_phy_rdlvl[48:43] = tap_cnt_cpt_r;
assign dbg_phy_rdlvl[54:49] = first_edge_taps_r;
assign dbg_phy_rdlvl[60:55] = second_edge_taps_r;
assign dbg_phy_rdlvl[64:61] = cal1_cnt_cpt_timing_r;
assign dbg_phy_rdlvl[65] = cal1_dlyce_cpt_r;
assign dbg_phy_rdlvl[66] = cal1_dlyinc_cpt_r;
assign dbg_phy_rdlvl[67] = found_edge_r;
assign dbg_phy_rdlvl[68] = found_first_edge_r;
assign dbg_phy_rdlvl[73:69] = 'b0;
assign dbg_phy_rdlvl[74] = idel_pat_data_match;
assign dbg_phy_rdlvl[75] = idel_pat0_data_match_r;
assign dbg_phy_rdlvl[76] = idel_pat1_data_match_r;
assign dbg_phy_rdlvl[77] = pat0_data_match_r;
assign dbg_phy_rdlvl[78] = pat1_data_match_r;
assign dbg_phy_rdlvl[79+:5*DQS_WIDTH*RANKS] = idelay_tap_cnt_w;
assign dbg_phy_rdlvl[170+:8] = mux_rd_rise0_r;
assign dbg_phy_rdlvl[178+:8] = mux_rd_fall0_r;
assign dbg_phy_rdlvl[186+:8] = mux_rd_rise1_r;
assign dbg_phy_rdlvl[194+:8] = mux_rd_fall1_r;
assign dbg_phy_rdlvl[202+:8] = mux_rd_rise2_r;
assign dbg_phy_rdlvl[210+:8] = mux_rd_fall2_r;
assign dbg_phy_rdlvl[218+:8] = mux_rd_rise3_r;
assign dbg_phy_rdlvl[226+:8] = mux_rd_fall3_r;
//***************************************************************************
// Debug output
//***************************************************************************
// CPT taps
assign dbg_cpt_first_edge_cnt = dbg_cpt_first_edge_taps;
assign dbg_cpt_second_edge_cnt = dbg_cpt_second_edge_taps;
assign dbg_cpt_tap_cnt = dbg_cpt_tap_cnt_w;
assign dbg_dq_idelay_tap_cnt = idelay_tap_cnt_w;
// Record first and second edges found during CPT calibration
generate
always @(posedge clk)
if (rst) begin
dbg_cpt_first_edge_taps <= #TCQ 'b0;
dbg_cpt_second_edge_taps <= #TCQ 'b0;
end else if ((SIM_CAL_OPTION == "FAST_CAL") & (cal1_state_r1 == CAL1_CALC_IDEL)) begin
for (ce_rnk_i = 0; ce_rnk_i < RANKS; ce_rnk_i = ce_rnk_i + 1) begin: gen_dbg_cpt_rnk
for (ce_i = 0; ce_i < DQS_WIDTH; ce_i = ce_i + 1) begin: gen_dbg_cpt_edge
if (found_first_edge_r)
dbg_cpt_first_edge_taps[((6*ce_i)+(ce_rnk_i*DQS_WIDTH*6))+:6]
<= #TCQ first_edge_taps_r;
if (found_second_edge_r)
dbg_cpt_second_edge_taps[((6*ce_i)+(ce_rnk_i*DQS_WIDTH*6))+:6]
<= #TCQ second_edge_taps_r;
end
end
end else if (cal1_state_r == CAL1_CALC_IDEL) begin
// Record tap counts of first and second edge edges during
// CPT calibration for each DQS group. If neither edge has
// been found, then those taps will remain 0
if (found_first_edge_r)
dbg_cpt_first_edge_taps[(((cal1_cnt_cpt_timing <<2) + (cal1_cnt_cpt_timing <<1))
+(rnk_cnt_r*DQS_WIDTH*6))+:6]
<= #TCQ first_edge_taps_r;
if (found_second_edge_r)
dbg_cpt_second_edge_taps[(((cal1_cnt_cpt_timing <<2) + (cal1_cnt_cpt_timing <<1))
+(rnk_cnt_r*DQS_WIDTH*6))+:6]
<= #TCQ second_edge_taps_r;
end
endgenerate
assign rdlvl_stg1_rnk_done = rdlvl_rank_done_r;// || regl_rank_done_r;
assign mpr_rnk_done = mpr_rank_done_r;
assign mpr_rdlvl_done = ((DRAM_TYPE == "DDR3") && (OCAL_EN == "ON")) ? //&& (SIM_CAL_OPTION == "NONE")
mpr_rdlvl_done_r : 1'b1;
//**************************************************************************
// DQS count to hard PHY during write calibration using Phaser_OUT Stage2
// coarse delay
//**************************************************************************
assign pi_stg2_rdlvl_cnt = (cal1_state_r == CAL1_REGL_LOAD) ? regl_dqs_cnt_r : cal1_cnt_cpt_r;
assign idelay_ce = cal1_dq_idel_ce;
assign idelay_inc = cal1_dq_idel_inc;
//***************************************************************************
// Assert calib_in_common in FAST_CAL mode for IDELAY tap increments to all
// DQs simultaneously
//***************************************************************************
always @(posedge clk) begin
if (rst)
rdlvl_assrt_common <= #TCQ 1'b0;
else if ((SIM_CAL_OPTION == "FAST_CAL") & rdlvl_stg1_start &
!rdlvl_stg1_start_r)
rdlvl_assrt_common <= #TCQ 1'b1;
else if (!idel_pat_data_match_r & idel_pat_data_match)
rdlvl_assrt_common <= #TCQ 1'b0;
end
//***************************************************************************
// Data mux to route appropriate bit to calibration logic - i.e. calibration
// is done sequentially, one bit (or DQS group) at a time
//***************************************************************************
generate
if (nCK_PER_CLK == 4) begin: rd_data_div4_logic_clk
assign rd_data_rise0 = rd_data[DQ_WIDTH-1:0];
assign rd_data_fall0 = rd_data[2*DQ_WIDTH-1:DQ_WIDTH];
assign rd_data_rise1 = rd_data[3*DQ_WIDTH-1:2*DQ_WIDTH];
assign rd_data_fall1 = rd_data[4*DQ_WIDTH-1:3*DQ_WIDTH];
assign rd_data_rise2 = rd_data[5*DQ_WIDTH-1:4*DQ_WIDTH];
assign rd_data_fall2 = rd_data[6*DQ_WIDTH-1:5*DQ_WIDTH];
assign rd_data_rise3 = rd_data[7*DQ_WIDTH-1:6*DQ_WIDTH];
assign rd_data_fall3 = rd_data[8*DQ_WIDTH-1:7*DQ_WIDTH];
end else begin: rd_data_div2_logic_clk
assign rd_data_rise0 = rd_data[DQ_WIDTH-1:0];
assign rd_data_fall0 = rd_data[2*DQ_WIDTH-1:DQ_WIDTH];
assign rd_data_rise1 = rd_data[3*DQ_WIDTH-1:2*DQ_WIDTH];
assign rd_data_fall1 = rd_data[4*DQ_WIDTH-1:3*DQ_WIDTH];
end
endgenerate
always @(posedge clk) begin
rd_mux_sel_r <= #TCQ cal1_cnt_cpt_r;
end
// Register outputs for improved timing.
// NOTE: Will need to change when per-bit DQ deskew is supported.
// Currenly all bits in DQS group are checked in aggregate
generate
genvar mux_i;
for (mux_i = 0; mux_i < DRAM_WIDTH; mux_i = mux_i + 1) begin: gen_mux_rd
always @(posedge clk) begin
mux_rd_rise0_r[mux_i] <= #TCQ rd_data_rise0[DRAM_WIDTH*rd_mux_sel_r +
mux_i];
mux_rd_fall0_r[mux_i] <= #TCQ rd_data_fall0[DRAM_WIDTH*rd_mux_sel_r +
mux_i];
mux_rd_rise1_r[mux_i] <= #TCQ rd_data_rise1[DRAM_WIDTH*rd_mux_sel_r +
mux_i];
mux_rd_fall1_r[mux_i] <= #TCQ rd_data_fall1[DRAM_WIDTH*rd_mux_sel_r +
mux_i];
mux_rd_rise2_r[mux_i] <= #TCQ rd_data_rise2[DRAM_WIDTH*rd_mux_sel_r +
mux_i];
mux_rd_fall2_r[mux_i] <= #TCQ rd_data_fall2[DRAM_WIDTH*rd_mux_sel_r +
mux_i];
mux_rd_rise3_r[mux_i] <= #TCQ rd_data_rise3[DRAM_WIDTH*rd_mux_sel_r +
mux_i];
mux_rd_fall3_r[mux_i] <= #TCQ rd_data_fall3[DRAM_WIDTH*rd_mux_sel_r +
mux_i];
end
end
endgenerate
//***************************************************************************
// MPR Read Leveling
//***************************************************************************
// storing the previous read data for checking later. Only bit 0 is used
// since MPR contents (01010101) are available generally on DQ[0] per
// JEDEC spec.
always @(posedge clk)begin
if ((cal1_state_r == CAL1_MPR_NEW_DQS_WAIT) ||
((cal1_state_r == CAL1_MPR_PAT_DETECT) && (idel_pat_detect_valid_r)))begin
mpr_rd_rise0_prev_r <= #TCQ mux_rd_rise0_r[0];
mpr_rd_fall0_prev_r <= #TCQ mux_rd_fall0_r[0];
mpr_rd_rise1_prev_r <= #TCQ mux_rd_rise1_r[0];
mpr_rd_fall1_prev_r <= #TCQ mux_rd_fall1_r[0];
mpr_rd_rise2_prev_r <= #TCQ mux_rd_rise2_r[0];
mpr_rd_fall2_prev_r <= #TCQ mux_rd_fall2_r[0];
mpr_rd_rise3_prev_r <= #TCQ mux_rd_rise3_r[0];
mpr_rd_fall3_prev_r <= #TCQ mux_rd_fall3_r[0];
end
end
generate
if (nCK_PER_CLK == 4) begin: mpr_4to1
// changed stable count of 2 IDELAY taps at 78 ps resolution
always @(posedge clk) begin
if (rst | (cal1_state_r == CAL1_NEW_DQS_PREWAIT) |
//(cal1_state_r == CAL1_DETECT_EDGE) |
(mpr_rd_rise0_prev_r != mux_rd_rise0_r[0]) |
(mpr_rd_fall0_prev_r != mux_rd_fall0_r[0]) |
(mpr_rd_rise1_prev_r != mux_rd_rise1_r[0]) |
(mpr_rd_fall1_prev_r != mux_rd_fall1_r[0]) |
(mpr_rd_rise2_prev_r != mux_rd_rise2_r[0]) |
(mpr_rd_fall2_prev_r != mux_rd_fall2_r[0]) |
(mpr_rd_rise3_prev_r != mux_rd_rise3_r[0]) |
(mpr_rd_fall3_prev_r != mux_rd_fall3_r[0]))
stable_idel_cnt <= #TCQ 3'd0;
else if ((|idelay_tap_cnt_r[rnk_cnt_r][cal1_cnt_cpt_timing]) &
((cal1_state_r == CAL1_MPR_PAT_DETECT) &
(idel_pat_detect_valid_r))) begin
if ((mpr_rd_rise0_prev_r == mux_rd_rise0_r[0]) &
(mpr_rd_fall0_prev_r == mux_rd_fall0_r[0]) &
(mpr_rd_rise1_prev_r == mux_rd_rise1_r[0]) &
(mpr_rd_fall1_prev_r == mux_rd_fall1_r[0]) &
(mpr_rd_rise2_prev_r == mux_rd_rise2_r[0]) &
(mpr_rd_fall2_prev_r == mux_rd_fall2_r[0]) &
(mpr_rd_rise3_prev_r == mux_rd_rise3_r[0]) &
(mpr_rd_fall3_prev_r == mux_rd_fall3_r[0]) &
(stable_idel_cnt < 3'd2))
stable_idel_cnt <= #TCQ stable_idel_cnt + 1;
end
end
always @(posedge clk) begin
if (rst |
(mpr_rd_rise0_prev_r & ~mpr_rd_fall0_prev_r &
mpr_rd_rise1_prev_r & ~mpr_rd_fall1_prev_r &
mpr_rd_rise2_prev_r & ~mpr_rd_fall2_prev_r &
mpr_rd_rise3_prev_r & ~mpr_rd_fall3_prev_r))
inhibit_edge_detect_r <= 1'b1;
// Wait for settling time after idelay tap increment before
// de-asserting inhibit_edge_detect_r
else if ((cal1_state_r == CAL1_MPR_PAT_DETECT) &
(idelay_tap_cnt_r[rnk_cnt_r][cal1_cnt_cpt_timing] > 5'd1) &
(~mpr_rd_rise0_prev_r & mpr_rd_fall0_prev_r &
~mpr_rd_rise1_prev_r & mpr_rd_fall1_prev_r &
~mpr_rd_rise2_prev_r & mpr_rd_fall2_prev_r &
~mpr_rd_rise3_prev_r & mpr_rd_fall3_prev_r))
inhibit_edge_detect_r <= 1'b0;
end
//checking for transition from 01010101 to 10101010
always @(posedge clk)begin
if (rst | (cal1_state_r == CAL1_MPR_NEW_DQS_WAIT) |
inhibit_edge_detect_r)
idel_mpr_pat_detect_r <= #TCQ 1'b0;
// 10101010 is not the correct pattern
else if ((mpr_rd_rise0_prev_r & ~mpr_rd_fall0_prev_r &
mpr_rd_rise1_prev_r & ~mpr_rd_fall1_prev_r &
mpr_rd_rise2_prev_r & ~mpr_rd_fall2_prev_r &
mpr_rd_rise3_prev_r & ~mpr_rd_fall3_prev_r) ||
((stable_idel_cnt < 3'd2) & (cal1_state_r == CAL1_MPR_PAT_DETECT)
&& (idel_pat_detect_valid_r)))
//|| (idelay_tap_cnt_r[rnk_cnt_r][cal1_cnt_cpt_timing] < 5'd2))
idel_mpr_pat_detect_r <= #TCQ 1'b0;
// 01010101 to 10101010 is the correct transition
else if ((~mpr_rd_rise0_prev_r & mpr_rd_fall0_prev_r &
~mpr_rd_rise1_prev_r & mpr_rd_fall1_prev_r &
~mpr_rd_rise2_prev_r & mpr_rd_fall2_prev_r &
~mpr_rd_rise3_prev_r & mpr_rd_fall3_prev_r) &
(stable_idel_cnt == 3'd2) &
((mpr_rd_rise0_prev_r != mux_rd_rise0_r[0]) ||
(mpr_rd_fall0_prev_r != mux_rd_fall0_r[0]) ||
(mpr_rd_rise1_prev_r != mux_rd_rise1_r[0]) ||
(mpr_rd_fall1_prev_r != mux_rd_fall1_r[0]) ||
(mpr_rd_rise2_prev_r != mux_rd_rise2_r[0]) ||
(mpr_rd_fall2_prev_r != mux_rd_fall2_r[0]) ||
(mpr_rd_rise3_prev_r != mux_rd_rise3_r[0]) ||
(mpr_rd_fall3_prev_r != mux_rd_fall3_r[0])))
idel_mpr_pat_detect_r <= #TCQ 1'b1;
end
end else if (nCK_PER_CLK == 2) begin: mpr_2to1
// changed stable count of 2 IDELAY taps at 78 ps resolution
always @(posedge clk) begin
if (rst | (cal1_state_r == CAL1_MPR_NEW_DQS_WAIT) |
(mpr_rd_rise0_prev_r != mux_rd_rise0_r[0]) |
(mpr_rd_fall0_prev_r != mux_rd_fall0_r[0]) |
(mpr_rd_rise1_prev_r != mux_rd_rise1_r[0]) |
(mpr_rd_fall1_prev_r != mux_rd_fall1_r[0]))
stable_idel_cnt <= #TCQ 3'd0;
else if ((idelay_tap_cnt_r[rnk_cnt_r][cal1_cnt_cpt_timing] > 5'd0) &
((cal1_state_r == CAL1_MPR_PAT_DETECT) &
(idel_pat_detect_valid_r))) begin
if ((mpr_rd_rise0_prev_r == mux_rd_rise0_r[0]) &
(mpr_rd_fall0_prev_r == mux_rd_fall0_r[0]) &
(mpr_rd_rise1_prev_r == mux_rd_rise1_r[0]) &
(mpr_rd_fall1_prev_r == mux_rd_fall1_r[0]) &
(stable_idel_cnt < 3'd2))
stable_idel_cnt <= #TCQ stable_idel_cnt + 1;
end
end
always @(posedge clk) begin
if (rst |
(mpr_rd_rise0_prev_r & ~mpr_rd_fall0_prev_r &
mpr_rd_rise1_prev_r & ~mpr_rd_fall1_prev_r))
inhibit_edge_detect_r <= 1'b1;
else if ((cal1_state_r == CAL1_MPR_PAT_DETECT) &
(idelay_tap_cnt_r[rnk_cnt_r][cal1_cnt_cpt_timing] > 5'd1) &
(~mpr_rd_rise0_prev_r & mpr_rd_fall0_prev_r &
~mpr_rd_rise1_prev_r & mpr_rd_fall1_prev_r))
inhibit_edge_detect_r <= 1'b0;
end
//checking for transition from 01010101 to 10101010
always @(posedge clk)begin
if (rst | (cal1_state_r == CAL1_MPR_NEW_DQS_WAIT) |
inhibit_edge_detect_r)
idel_mpr_pat_detect_r <= #TCQ 1'b0;
// 1010 is not the correct pattern
else if ((mpr_rd_rise0_prev_r & ~mpr_rd_fall0_prev_r &
mpr_rd_rise1_prev_r & ~mpr_rd_fall1_prev_r) ||
((stable_idel_cnt < 3'd2) & (cal1_state_r == CAL1_MPR_PAT_DETECT)
& (idel_pat_detect_valid_r)))
// ||(idelay_tap_cnt_r[rnk_cnt_r][cal1_cnt_cpt_timing] < 5'd2))
idel_mpr_pat_detect_r <= #TCQ 1'b0;
// 0101 to 1010 is the correct transition
else if ((~mpr_rd_rise0_prev_r & mpr_rd_fall0_prev_r &
~mpr_rd_rise1_prev_r & mpr_rd_fall1_prev_r) &
(stable_idel_cnt == 3'd2) &
((mpr_rd_rise0_prev_r != mux_rd_rise0_r[0]) ||
(mpr_rd_fall0_prev_r != mux_rd_fall0_r[0]) ||
(mpr_rd_rise1_prev_r != mux_rd_rise1_r[0]) ||
(mpr_rd_fall1_prev_r != mux_rd_fall1_r[0])))
idel_mpr_pat_detect_r <= #TCQ 1'b1;
end
end
endgenerate
// Registered signal indicates when mux_rd_rise/fall_r is valid
always @(posedge clk)
mux_rd_valid_r <= #TCQ ~phy_if_empty;
//***************************************************************************
// Decrement initial Phaser_IN fine delay value before proceeding with
// read calibration
//***************************************************************************
always @(posedge clk) begin
dqs_po_dec_done_r1 <= #TCQ dqs_po_dec_done;
dqs_po_dec_done_r2 <= #TCQ dqs_po_dec_done_r1;
fine_dly_dec_done_r2 <= #TCQ fine_dly_dec_done_r1;
pi_fine_dly_dec_done <= #TCQ fine_dly_dec_done_r2;
end
always @(posedge clk) begin
if (rst || pi_cnt_dec)
wait_cnt_r <= #TCQ 'd8;
else if (dqs_po_dec_done_r2 && (wait_cnt_r > 'd0))
wait_cnt_r <= #TCQ wait_cnt_r - 1;
end
always @(posedge clk) begin
if (rst) begin
pi_rdval_cnt <= #TCQ 'd0;
end else if (dqs_po_dec_done_r1 && ~dqs_po_dec_done_r2) begin
pi_rdval_cnt <= #TCQ pi_counter_read_val;
end else if (pi_rdval_cnt > 'd0) begin
if (pi_cnt_dec)
pi_rdval_cnt <= #TCQ pi_rdval_cnt - 1;
else
pi_rdval_cnt <= #TCQ pi_rdval_cnt;
end else if (pi_rdval_cnt == 'd0) begin
pi_rdval_cnt <= #TCQ pi_rdval_cnt;
end
end
always @(posedge clk) begin
if (rst || (pi_rdval_cnt == 'd0))
pi_cnt_dec <= #TCQ 1'b0;
else if (dqs_po_dec_done_r2 && (pi_rdval_cnt > 'd0)
&& (wait_cnt_r == 'd1))
pi_cnt_dec <= #TCQ 1'b1;
else
pi_cnt_dec <= #TCQ 1'b0;
end
always @(posedge clk) begin
if (rst) begin
fine_dly_dec_done_r1 <= #TCQ 1'b0;
end else if (((pi_cnt_dec == 'd1) && (pi_rdval_cnt == 'd1)) ||
(dqs_po_dec_done_r2 && (pi_rdval_cnt == 'd0))) begin
fine_dly_dec_done_r1 <= #TCQ 1'b1;
end
end
//***************************************************************************
// Demultiplexor to control Phaser_IN delay values
//***************************************************************************
// Read DQS
always @(posedge clk) begin
if (rst) begin
pi_en_stg2_f_timing <= #TCQ 'b0;
pi_stg2_f_incdec_timing <= #TCQ 'b0;
end else if (pi_cnt_dec) begin
pi_en_stg2_f_timing <= #TCQ 'b1;
pi_stg2_f_incdec_timing <= #TCQ 'b0;
end else if (cal1_dlyce_cpt_r) begin
if ((SIM_CAL_OPTION == "NONE") ||
(SIM_CAL_OPTION == "FAST_WIN_DETECT")) begin
// Change only specified DQS
pi_en_stg2_f_timing <= #TCQ 1'b1;
pi_stg2_f_incdec_timing <= #TCQ cal1_dlyinc_cpt_r;
end else if (SIM_CAL_OPTION == "FAST_CAL") begin
// if simulating, and "shortcuts" for calibration enabled, apply
// results to all DQSs (i.e. assume same delay on all
// DQSs).
pi_en_stg2_f_timing <= #TCQ 1'b1;
pi_stg2_f_incdec_timing <= #TCQ cal1_dlyinc_cpt_r;
end
end else begin
pi_en_stg2_f_timing <= #TCQ 'b0;
pi_stg2_f_incdec_timing <= #TCQ 'b0;
end
end
// registered for timing
always @(posedge clk) begin
pi_en_stg2_f <= #TCQ pi_en_stg2_f_timing;
pi_stg2_f_incdec <= #TCQ pi_stg2_f_incdec_timing;
end
// This counter used to implement settling time between
// Phaser_IN rank register loads to different DQSs
always @(posedge clk) begin
if (rst)
done_cnt <= #TCQ 'b0;
else if (((cal1_state_r == CAL1_REGL_LOAD) &&
(cal1_state_r1 == CAL1_NEXT_DQS)) ||
((done_cnt == 4'd1) && (cal1_state_r != CAL1_DONE)))
done_cnt <= #TCQ 4'b1010;
else if (done_cnt > 'b0)
done_cnt <= #TCQ done_cnt - 1;
end
// During rank register loading the rank count must be sent to
// Phaser_IN via the phy_ctl_wd?? If so phy_init will have to
// issue NOPs during rank register loading with the appropriate
// rank count
always @(posedge clk) begin
if (rst || (regl_rank_done_r == 1'b1))
regl_rank_done_r <= #TCQ 1'b0;
else if ((regl_dqs_cnt == DQS_WIDTH-1) &&
(regl_rank_cnt != RANKS-1) &&
(done_cnt == 4'd1))
regl_rank_done_r <= #TCQ 1'b1;
end
// Temp wire for timing.
// The following in the always block below causes timing issues
// due to DSP block inference
// 6*regl_dqs_cnt.
// replacing this with two left shifts + 1 left shift to avoid
// DSP multiplier.
assign regl_dqs_cnt_timing = {2'd0, regl_dqs_cnt};
// Load Phaser_OUT rank register with rdlvl delay value
// for each DQS per rank.
always @(posedge clk) begin
if (rst || (done_cnt == 4'd0)) begin
pi_stg2_load_timing <= #TCQ 'b0;
pi_stg2_reg_l_timing <= #TCQ 'b0;
end else if ((cal1_state_r == CAL1_REGL_LOAD) &&
(regl_dqs_cnt <= DQS_WIDTH-1) && (done_cnt == 4'd1)) begin
pi_stg2_load_timing <= #TCQ 'b1;
pi_stg2_reg_l_timing <= #TCQ
rdlvl_dqs_tap_cnt_r[rnk_cnt_r][regl_dqs_cnt];
end else begin
pi_stg2_load_timing <= #TCQ 'b0;
pi_stg2_reg_l_timing <= #TCQ 'b0;
end
end
// registered for timing
always @(posedge clk) begin
pi_stg2_load <= #TCQ pi_stg2_load_timing;
pi_stg2_reg_l <= #TCQ pi_stg2_reg_l_timing;
end
always @(posedge clk) begin
if (rst || (done_cnt == 4'd0) ||
(mpr_rdlvl_done_r1 && ~mpr_rdlvl_done_r2))
regl_rank_cnt <= #TCQ 2'b00;
else if ((cal1_state_r == CAL1_REGL_LOAD) &&
(regl_dqs_cnt == DQS_WIDTH-1) && (done_cnt == 4'd1)) begin
if (regl_rank_cnt == RANKS-1)
regl_rank_cnt <= #TCQ regl_rank_cnt;
else
regl_rank_cnt <= #TCQ regl_rank_cnt + 1;
end
end
always @(posedge clk) begin
if (rst || (done_cnt == 4'd0) ||
(mpr_rdlvl_done_r1 && ~mpr_rdlvl_done_r2))
regl_dqs_cnt <= #TCQ {DQS_CNT_WIDTH+1{1'b0}};
else if ((cal1_state_r == CAL1_REGL_LOAD) &&
(regl_dqs_cnt == DQS_WIDTH-1) && (done_cnt == 4'd1)) begin
if (regl_rank_cnt == RANKS-1)
regl_dqs_cnt <= #TCQ regl_dqs_cnt;
else
regl_dqs_cnt <= #TCQ 'b0;
end else if ((cal1_state_r == CAL1_REGL_LOAD) && (regl_dqs_cnt != DQS_WIDTH-1)
&& (done_cnt == 4'd1))
regl_dqs_cnt <= #TCQ regl_dqs_cnt + 1;
else
regl_dqs_cnt <= #TCQ regl_dqs_cnt;
end
always @(posedge clk)
regl_dqs_cnt_r <= #TCQ regl_dqs_cnt;
//*****************************************************************
// DQ Stage 1 CALIBRATION INCREMENT/DECREMENT LOGIC:
// The actual IDELAY elements for each of the DQ bits is set via the
// DLYVAL parallel load port. However, the stage 1 calibration
// algorithm (well most of it) only needs to increment or decrement the DQ
// IDELAY value by 1 at any one time.
//*****************************************************************
// Chip-select generation for each of the individual counters tracking
// IDELAY tap values for each DQ
generate
for (z = 0; z < DQS_WIDTH; z = z + 1) begin: gen_dlyce_dq
always @(posedge clk)
if (rst)
dlyce_dq_r[DRAM_WIDTH*z+:DRAM_WIDTH] <= #TCQ 'b0;
else
if (SIM_CAL_OPTION == "SKIP_CAL")
// If skipping calibration altogether (only for simulation), no
// need to set DQ IODELAY values - they are hardcoded
dlyce_dq_r[DRAM_WIDTH*z+:DRAM_WIDTH] <= #TCQ 'b0;
else if (SIM_CAL_OPTION == "FAST_CAL") begin
// If fast calibration option (simulation only) selected, DQ
// IODELAYs across all bytes are updated simultaneously
// (although per-bit deskew within DQS[0] is still supported)
for (h = 0; h < DRAM_WIDTH; h = h + 1) begin
dlyce_dq_r[DRAM_WIDTH*z + h] <= #TCQ cal1_dlyce_dq_r;
end
end else if ((SIM_CAL_OPTION == "NONE") ||
(SIM_CAL_OPTION == "FAST_WIN_DETECT")) begin
if (cal1_cnt_cpt_r == z) begin
for (g = 0; g < DRAM_WIDTH; g = g + 1) begin
dlyce_dq_r[DRAM_WIDTH*z + g]
<= #TCQ cal1_dlyce_dq_r;
end
end else
dlyce_dq_r[DRAM_WIDTH*z+:DRAM_WIDTH] <= #TCQ 'b0;
end
end
endgenerate
// Also delay increment/decrement control to match delay on DLYCE
always @(posedge clk)
if (rst)
dlyinc_dq_r <= #TCQ 1'b0;
else
dlyinc_dq_r <= #TCQ cal1_dlyinc_dq_r;
// Each DQ has a counter associated with it to record current read-leveling
// delay value
always @(posedge clk)
// Reset or skipping calibration all together
if (rst | (SIM_CAL_OPTION == "SKIP_CAL")) begin
for (aa = 0; aa < RANKS; aa = aa + 1) begin: rst_dlyval_dq_reg_r
for (bb = 0; bb < DQ_WIDTH; bb = bb + 1)
dlyval_dq_reg_r[aa][bb] <= #TCQ 'b0;
end
end else if (SIM_CAL_OPTION == "FAST_CAL") begin
for (n = 0; n < RANKS; n = n + 1) begin: gen_dlyval_dq_reg_rnk
for (r = 0; r < DQ_WIDTH; r = r + 1) begin: gen_dlyval_dq_reg
if (dlyce_dq_r[r]) begin
if (dlyinc_dq_r)
dlyval_dq_reg_r[n][r] <= #TCQ dlyval_dq_reg_r[n][r] + 5'h01;
else
dlyval_dq_reg_r[n][r] <= #TCQ dlyval_dq_reg_r[n][r] - 5'h01;
end
end
end
end else begin
if (dlyce_dq_r[cal1_cnt_cpt_r]) begin
if (dlyinc_dq_r)
dlyval_dq_reg_r[rnk_cnt_r][cal1_cnt_cpt_r] <= #TCQ
dlyval_dq_reg_r[rnk_cnt_r][cal1_cnt_cpt_r] + 5'h01;
else
dlyval_dq_reg_r[rnk_cnt_r][cal1_cnt_cpt_r] <= #TCQ
dlyval_dq_reg_r[rnk_cnt_r][cal1_cnt_cpt_r] - 5'h01;
end
end
// Register for timing (help with logic placement)
always @(posedge clk) begin
for (cc = 0; cc < RANKS; cc = cc + 1) begin: dlyval_dq_assgn
for (dd = 0; dd < DQ_WIDTH; dd = dd + 1)
dlyval_dq[((5*dd)+(cc*DQ_WIDTH*5))+:5] <= #TCQ dlyval_dq_reg_r[cc][dd];
end
end
//***************************************************************************
// Generate signal used to delay calibration state machine - used when:
// (1) IDELAY value changed
// (2) RD_MUX_SEL value changed
// Use when a delay is necessary to give the change time to propagate
// through the data pipeline (through IDELAY and ISERDES, and fabric
// pipeline stages)
//***************************************************************************
// List all the stage 1 calibration wait states here.
always @(posedge clk)
if ((cal1_state_r == CAL1_NEW_DQS_WAIT) ||
(cal1_state_r == CAL1_MPR_NEW_DQS_WAIT) ||
(cal1_state_r == CAL1_NEW_DQS_PREWAIT) ||
(cal1_state_r == CAL1_VALID_WAIT) ||
(cal1_state_r == CAL1_PB_STORE_FIRST_WAIT) ||
(cal1_state_r == CAL1_PB_INC_CPT_WAIT) ||
(cal1_state_r == CAL1_PB_DEC_CPT_LEFT_WAIT) ||
(cal1_state_r == CAL1_PB_INC_DQ_WAIT) ||
(cal1_state_r == CAL1_PB_DEC_CPT_WAIT) ||
(cal1_state_r == CAL1_IDEL_INC_CPT_WAIT) ||
(cal1_state_r == CAL1_IDEL_DEC_CPT_WAIT) ||
(cal1_state_r == CAL1_STORE_FIRST_WAIT) ||
(cal1_state_r == CAL1_DQ_IDEL_TAP_INC_WAIT) ||
(cal1_state_r == CAL1_DQ_IDEL_TAP_DEC_WAIT))
cal1_wait_cnt_en_r <= #TCQ 1'b1;
else
cal1_wait_cnt_en_r <= #TCQ 1'b0;
always @(posedge clk)
if (!cal1_wait_cnt_en_r) begin
cal1_wait_cnt_r <= #TCQ 5'b00000;
cal1_wait_r <= #TCQ 1'b1;
end else begin
if (cal1_wait_cnt_r != PIPE_WAIT_CNT - 1) begin
cal1_wait_cnt_r <= #TCQ cal1_wait_cnt_r + 1;
cal1_wait_r <= #TCQ 1'b1;
end else begin
// Need to reset to 0 to handle the case when there are two
// different WAIT states back-to-back
cal1_wait_cnt_r <= #TCQ 5'b00000;
cal1_wait_r <= #TCQ 1'b0;
end
end
//***************************************************************************
// generate request to PHY_INIT logic to issue precharged. Required when
// calibration can take a long time (during which there are only constant
// reads present on this bus). In this case need to issue perioidic
// precharges to avoid tRAS violation. This signal must meet the following
// requirements: (1) only transition from 0->1 when prech is first needed,
// (2) stay at 1 and only transition 1->0 when RDLVL_PRECH_DONE asserted
//***************************************************************************
always @(posedge clk)
if (rst)
rdlvl_prech_req <= #TCQ 1'b0;
else
rdlvl_prech_req <= #TCQ cal1_prech_req_r;
//***************************************************************************
// Serial-to-parallel register to store last RDDATA_SHIFT_LEN cycles of
// data from ISERDES. The value of this register is also stored, so that
// previous and current values of the ISERDES data can be compared while
// varying the IODELAY taps to see if an "edge" of the data valid window
// has been encountered since the last IODELAY tap adjustment
//***************************************************************************
//***************************************************************************
// Shift register to store last RDDATA_SHIFT_LEN cycles of data from ISERDES
// NOTE: Written using discrete flops, but SRL can be used if the matching
// logic does the comparison sequentially, rather than parallel
//***************************************************************************
generate
genvar rd_i;
if (nCK_PER_CLK == 4) begin: gen_sr_div4
if (RD_SHIFT_LEN == 1) begin: gen_sr_len_eq1
for (rd_i = 0; rd_i < DRAM_WIDTH; rd_i = rd_i + 1) begin: gen_sr
always @(posedge clk) begin
if (mux_rd_valid_r) begin
sr_rise0_r[rd_i] <= #TCQ mux_rd_rise0_r[rd_i];
sr_fall0_r[rd_i] <= #TCQ mux_rd_fall0_r[rd_i];
sr_rise1_r[rd_i] <= #TCQ mux_rd_rise1_r[rd_i];
sr_fall1_r[rd_i] <= #TCQ mux_rd_fall1_r[rd_i];
sr_rise2_r[rd_i] <= #TCQ mux_rd_rise2_r[rd_i];
sr_fall2_r[rd_i] <= #TCQ mux_rd_fall2_r[rd_i];
sr_rise3_r[rd_i] <= #TCQ mux_rd_rise3_r[rd_i];
sr_fall3_r[rd_i] <= #TCQ mux_rd_fall3_r[rd_i];
end
end
end
end else if (RD_SHIFT_LEN > 1) begin: gen_sr_len_gt1
for (rd_i = 0; rd_i < DRAM_WIDTH; rd_i = rd_i + 1) begin: gen_sr
always @(posedge clk) begin
if (mux_rd_valid_r) begin
sr_rise0_r[rd_i] <= #TCQ {sr_rise0_r[rd_i][RD_SHIFT_LEN-2:0],
mux_rd_rise0_r[rd_i]};
sr_fall0_r[rd_i] <= #TCQ {sr_fall0_r[rd_i][RD_SHIFT_LEN-2:0],
mux_rd_fall0_r[rd_i]};
sr_rise1_r[rd_i] <= #TCQ {sr_rise1_r[rd_i][RD_SHIFT_LEN-2:0],
mux_rd_rise1_r[rd_i]};
sr_fall1_r[rd_i] <= #TCQ {sr_fall1_r[rd_i][RD_SHIFT_LEN-2:0],
mux_rd_fall1_r[rd_i]};
sr_rise2_r[rd_i] <= #TCQ {sr_rise2_r[rd_i][RD_SHIFT_LEN-2:0],
mux_rd_rise2_r[rd_i]};
sr_fall2_r[rd_i] <= #TCQ {sr_fall2_r[rd_i][RD_SHIFT_LEN-2:0],
mux_rd_fall2_r[rd_i]};
sr_rise3_r[rd_i] <= #TCQ {sr_rise3_r[rd_i][RD_SHIFT_LEN-2:0],
mux_rd_rise3_r[rd_i]};
sr_fall3_r[rd_i] <= #TCQ {sr_fall3_r[rd_i][RD_SHIFT_LEN-2:0],
mux_rd_fall3_r[rd_i]};
end
end
end
end
end else if (nCK_PER_CLK == 2) begin: gen_sr_div2
if (RD_SHIFT_LEN == 1) begin: gen_sr_len_eq1
for (rd_i = 0; rd_i < DRAM_WIDTH; rd_i = rd_i + 1) begin: gen_sr
always @(posedge clk) begin
if (mux_rd_valid_r) begin
sr_rise0_r[rd_i] <= #TCQ {mux_rd_rise0_r[rd_i]};
sr_fall0_r[rd_i] <= #TCQ {mux_rd_fall0_r[rd_i]};
sr_rise1_r[rd_i] <= #TCQ {mux_rd_rise1_r[rd_i]};
sr_fall1_r[rd_i] <= #TCQ {mux_rd_fall1_r[rd_i]};
end
end
end
end else if (RD_SHIFT_LEN > 1) begin: gen_sr_len_gt1
for (rd_i = 0; rd_i < DRAM_WIDTH; rd_i = rd_i + 1) begin: gen_sr
always @(posedge clk) begin
if (mux_rd_valid_r) begin
sr_rise0_r[rd_i] <= #TCQ {sr_rise0_r[rd_i][RD_SHIFT_LEN-2:0],
mux_rd_rise0_r[rd_i]};
sr_fall0_r[rd_i] <= #TCQ {sr_fall0_r[rd_i][RD_SHIFT_LEN-2:0],
mux_rd_fall0_r[rd_i]};
sr_rise1_r[rd_i] <= #TCQ {sr_rise1_r[rd_i][RD_SHIFT_LEN-2:0],
mux_rd_rise1_r[rd_i]};
sr_fall1_r[rd_i] <= #TCQ {sr_fall1_r[rd_i][RD_SHIFT_LEN-2:0],
mux_rd_fall1_r[rd_i]};
end
end
end
end
end
endgenerate
//***************************************************************************
// Conversion to pattern calibration
//***************************************************************************
// Pattern for DQ IDELAY calibration
//*****************************************************************
// Expected data pattern when DQ shifted to the right such that
// DQS before the left edge of the DVW:
// Based on pattern of ({rise,fall}) =
// 0x1, 0xB, 0x4, 0x4, 0xB, 0x9
// Each nibble will look like:
// bit3: 0, 1, 0, 0, 1, 1
// bit2: 0, 0, 1, 1, 0, 0
// bit1: 0, 1, 0, 0, 1, 0
// bit0: 1, 1, 0, 0, 1, 1
// Or if the write is early it could look like:
// 0x4, 0x4, 0xB, 0x9, 0x6, 0xE
// bit3: 0, 0, 1, 1, 0, 1
// bit2: 1, 1, 0, 0, 1, 1
// bit1: 0, 0, 1, 0, 1, 1
// bit0: 0, 0, 1, 1, 0, 0
// Change the hard-coded pattern below accordingly as RD_SHIFT_LEN
// and the actual training pattern contents change
//*****************************************************************
generate
if (nCK_PER_CLK == 4) begin: gen_pat_div4
// Pattern for DQ IDELAY increment
// Target pattern for "early write"
assign {idel_pat0_rise0[3], idel_pat0_rise0[2],
idel_pat0_rise0[1], idel_pat0_rise0[0]} = 4'h1;
assign {idel_pat0_fall0[3], idel_pat0_fall0[2],
idel_pat0_fall0[1], idel_pat0_fall0[0]} = 4'h7;
assign {idel_pat0_rise1[3], idel_pat0_rise1[2],
idel_pat0_rise1[1], idel_pat0_rise1[0]} = 4'hE;
assign {idel_pat0_fall1[3], idel_pat0_fall1[2],
idel_pat0_fall1[1], idel_pat0_fall1[0]} = 4'hC;
assign {idel_pat0_rise2[3], idel_pat0_rise2[2],
idel_pat0_rise2[1], idel_pat0_rise2[0]} = 4'h9;
assign {idel_pat0_fall2[3], idel_pat0_fall2[2],
idel_pat0_fall2[1], idel_pat0_fall2[0]} = 4'h2;
assign {idel_pat0_rise3[3], idel_pat0_rise3[2],
idel_pat0_rise3[1], idel_pat0_rise3[0]} = 4'h4;
assign {idel_pat0_fall3[3], idel_pat0_fall3[2],
idel_pat0_fall3[1], idel_pat0_fall3[0]} = 4'hB;
// Target pattern for "on-time write"
assign {idel_pat1_rise0[3], idel_pat1_rise0[2],
idel_pat1_rise0[1], idel_pat1_rise0[0]} = 4'h4;
assign {idel_pat1_fall0[3], idel_pat1_fall0[2],
idel_pat1_fall0[1], idel_pat1_fall0[0]} = 4'h9;
assign {idel_pat1_rise1[3], idel_pat1_rise1[2],
idel_pat1_rise1[1], idel_pat1_rise1[0]} = 4'h3;
assign {idel_pat1_fall1[3], idel_pat1_fall1[2],
idel_pat1_fall1[1], idel_pat1_fall1[0]} = 4'h7;
assign {idel_pat1_rise2[3], idel_pat1_rise2[2],
idel_pat1_rise2[1], idel_pat1_rise2[0]} = 4'hE;
assign {idel_pat1_fall2[3], idel_pat1_fall2[2],
idel_pat1_fall2[1], idel_pat1_fall2[0]} = 4'hC;
assign {idel_pat1_rise3[3], idel_pat1_rise3[2],
idel_pat1_rise3[1], idel_pat1_rise3[0]} = 4'h9;
assign {idel_pat1_fall3[3], idel_pat1_fall3[2],
idel_pat1_fall3[1], idel_pat1_fall3[0]} = 4'h2;
// Correct data valid window for "early write"
assign {pat0_rise0[3], pat0_rise0[2],
pat0_rise0[1], pat0_rise0[0]} = 4'h7;
assign {pat0_fall0[3], pat0_fall0[2],
pat0_fall0[1], pat0_fall0[0]} = 4'hE;
assign {pat0_rise1[3], pat0_rise1[2],
pat0_rise1[1], pat0_rise1[0]} = 4'hC;
assign {pat0_fall1[3], pat0_fall1[2],
pat0_fall1[1], pat0_fall1[0]} = 4'h9;
assign {pat0_rise2[3], pat0_rise2[2],
pat0_rise2[1], pat0_rise2[0]} = 4'h2;
assign {pat0_fall2[3], pat0_fall2[2],
pat0_fall2[1], pat0_fall2[0]} = 4'h4;
assign {pat0_rise3[3], pat0_rise3[2],
pat0_rise3[1], pat0_rise3[0]} = 4'hB;
assign {pat0_fall3[3], pat0_fall3[2],
pat0_fall3[1], pat0_fall3[0]} = 4'h1;
// Correct data valid window for "on-time write"
assign {pat1_rise0[3], pat1_rise0[2],
pat1_rise0[1], pat1_rise0[0]} = 4'h9;
assign {pat1_fall0[3], pat1_fall0[2],
pat1_fall0[1], pat1_fall0[0]} = 4'h3;
assign {pat1_rise1[3], pat1_rise1[2],
pat1_rise1[1], pat1_rise1[0]} = 4'h7;
assign {pat1_fall1[3], pat1_fall1[2],
pat1_fall1[1], pat1_fall1[0]} = 4'hE;
assign {pat1_rise2[3], pat1_rise2[2],
pat1_rise2[1], pat1_rise2[0]} = 4'hC;
assign {pat1_fall2[3], pat1_fall2[2],
pat1_fall2[1], pat1_fall2[0]} = 4'h9;
assign {pat1_rise3[3], pat1_rise3[2],
pat1_rise3[1], pat1_rise3[0]} = 4'h2;
assign {pat1_fall3[3], pat1_fall3[2],
pat1_fall3[1], pat1_fall3[0]} = 4'h4;
end else if (nCK_PER_CLK == 2) begin: gen_pat_div2
// Pattern for DQ IDELAY increment
// Target pattern for "early write"
assign idel_pat0_rise0[3] = 2'b01;
assign idel_pat0_fall0[3] = 2'b00;
assign idel_pat0_rise1[3] = 2'b10;
assign idel_pat0_fall1[3] = 2'b11;
assign idel_pat0_rise0[2] = 2'b00;
assign idel_pat0_fall0[2] = 2'b10;
assign idel_pat0_rise1[2] = 2'b11;
assign idel_pat0_fall1[2] = 2'b10;
assign idel_pat0_rise0[1] = 2'b00;
assign idel_pat0_fall0[1] = 2'b11;
assign idel_pat0_rise1[1] = 2'b10;
assign idel_pat0_fall1[1] = 2'b01;
assign idel_pat0_rise0[0] = 2'b11;
assign idel_pat0_fall0[0] = 2'b10;
assign idel_pat0_rise1[0] = 2'b00;
assign idel_pat0_fall1[0] = 2'b01;
// Target pattern for "on-time write"
assign idel_pat1_rise0[3] = 2'b01;
assign idel_pat1_fall0[3] = 2'b11;
assign idel_pat1_rise1[3] = 2'b01;
assign idel_pat1_fall1[3] = 2'b00;
assign idel_pat1_rise0[2] = 2'b11;
assign idel_pat1_fall0[2] = 2'b01;
assign idel_pat1_rise1[2] = 2'b00;
assign idel_pat1_fall1[2] = 2'b10;
assign idel_pat1_rise0[1] = 2'b01;
assign idel_pat1_fall0[1] = 2'b00;
assign idel_pat1_rise1[1] = 2'b10;
assign idel_pat1_fall1[1] = 2'b11;
assign idel_pat1_rise0[0] = 2'b00;
assign idel_pat1_fall0[0] = 2'b10;
assign idel_pat1_rise1[0] = 2'b11;
assign idel_pat1_fall1[0] = 2'b10;
// Correct data valid window for "early write"
assign pat0_rise0[3] = 2'b00;
assign pat0_fall0[3] = 2'b10;
assign pat0_rise1[3] = 2'b11;
assign pat0_fall1[3] = 2'b10;
assign pat0_rise0[2] = 2'b10;
assign pat0_fall0[2] = 2'b11;
assign pat0_rise1[2] = 2'b10;
assign pat0_fall1[2] = 2'b00;
assign pat0_rise0[1] = 2'b11;
assign pat0_fall0[1] = 2'b10;
assign pat0_rise1[1] = 2'b01;
assign pat0_fall1[1] = 2'b00;
assign pat0_rise0[0] = 2'b10;
assign pat0_fall0[0] = 2'b00;
assign pat0_rise1[0] = 2'b01;
assign pat0_fall1[0] = 2'b11;
// Correct data valid window for "on-time write"
assign pat1_rise0[3] = 2'b11;
assign pat1_fall0[3] = 2'b01;
assign pat1_rise1[3] = 2'b00;
assign pat1_fall1[3] = 2'b10;
assign pat1_rise0[2] = 2'b01;
assign pat1_fall0[2] = 2'b00;
assign pat1_rise1[2] = 2'b10;
assign pat1_fall1[2] = 2'b11;
assign pat1_rise0[1] = 2'b00;
assign pat1_fall0[1] = 2'b10;
assign pat1_rise1[1] = 2'b11;
assign pat1_fall1[1] = 2'b10;
assign pat1_rise0[0] = 2'b10;
assign pat1_fall0[0] = 2'b11;
assign pat1_rise1[0] = 2'b10;
assign pat1_fall1[0] = 2'b00;
end
endgenerate
// Each bit of each byte is compared to expected pattern.
// This was done to prevent (and "drastically decrease") the chance that
// invalid data clocked in when the DQ bus is tri-state (along with a
// combination of the correct data) will resemble the expected data
// pattern. A better fix for this is to change the training pattern and/or
// make the pattern longer.
generate
genvar pt_i;
if (nCK_PER_CLK == 4) begin: gen_pat_match_div4
for (pt_i = 0; pt_i < DRAM_WIDTH; pt_i = pt_i + 1) begin: gen_pat_match
// DQ IDELAY pattern detection
always @(posedge clk) begin
if (sr_rise0_r[pt_i] == idel_pat0_rise0[pt_i%4])
idel_pat0_match_rise0_r[pt_i] <= #TCQ 1'b1;
else
idel_pat0_match_rise0_r[pt_i] <= #TCQ 1'b0;
if (sr_fall0_r[pt_i] == idel_pat0_fall0[pt_i%4])
idel_pat0_match_fall0_r[pt_i] <= #TCQ 1'b1;
else
idel_pat0_match_fall0_r[pt_i] <= #TCQ 1'b0;
if (sr_rise1_r[pt_i] == idel_pat0_rise1[pt_i%4])
idel_pat0_match_rise1_r[pt_i] <= #TCQ 1'b1;
else
idel_pat0_match_rise1_r[pt_i] <= #TCQ 1'b0;
if (sr_fall1_r[pt_i] == idel_pat0_fall1[pt_i%4])
idel_pat0_match_fall1_r[pt_i] <= #TCQ 1'b1;
else
idel_pat0_match_fall1_r[pt_i] <= #TCQ 1'b0;
if (sr_rise2_r[pt_i] == idel_pat0_rise2[pt_i%4])
idel_pat0_match_rise2_r[pt_i] <= #TCQ 1'b1;
else
idel_pat0_match_rise2_r[pt_i] <= #TCQ 1'b0;
if (sr_fall2_r[pt_i] == idel_pat0_fall2[pt_i%4])
idel_pat0_match_fall2_r[pt_i] <= #TCQ 1'b1;
else
idel_pat0_match_fall2_r[pt_i] <= #TCQ 1'b0;
if (sr_rise3_r[pt_i] == idel_pat0_rise3[pt_i%4])
idel_pat0_match_rise3_r[pt_i] <= #TCQ 1'b1;
else
idel_pat0_match_rise3_r[pt_i] <= #TCQ 1'b0;
if (sr_fall3_r[pt_i] == idel_pat0_fall3[pt_i%4])
idel_pat0_match_fall3_r[pt_i] <= #TCQ 1'b1;
else
idel_pat0_match_fall3_r[pt_i] <= #TCQ 1'b0;
end
always @(posedge clk) begin
if (sr_rise0_r[pt_i] == idel_pat1_rise0[pt_i%4])
idel_pat1_match_rise0_r[pt_i] <= #TCQ 1'b1;
else
idel_pat1_match_rise0_r[pt_i] <= #TCQ 1'b0;
if (sr_fall0_r[pt_i] == idel_pat1_fall0[pt_i%4])
idel_pat1_match_fall0_r[pt_i] <= #TCQ 1'b1;
else
idel_pat1_match_fall0_r[pt_i] <= #TCQ 1'b0;
if (sr_rise1_r[pt_i] == idel_pat1_rise1[pt_i%4])
idel_pat1_match_rise1_r[pt_i] <= #TCQ 1'b1;
else
idel_pat1_match_rise1_r[pt_i] <= #TCQ 1'b0;
if (sr_fall1_r[pt_i] == idel_pat1_fall1[pt_i%4])
idel_pat1_match_fall1_r[pt_i] <= #TCQ 1'b1;
else
idel_pat1_match_fall1_r[pt_i] <= #TCQ 1'b0;
if (sr_rise2_r[pt_i] == idel_pat1_rise2[pt_i%4])
idel_pat1_match_rise2_r[pt_i] <= #TCQ 1'b1;
else
idel_pat1_match_rise2_r[pt_i] <= #TCQ 1'b0;
if (sr_fall2_r[pt_i] == idel_pat1_fall2[pt_i%4])
idel_pat1_match_fall2_r[pt_i] <= #TCQ 1'b1;
else
idel_pat1_match_fall2_r[pt_i] <= #TCQ 1'b0;
if (sr_rise3_r[pt_i] == idel_pat1_rise3[pt_i%4])
idel_pat1_match_rise3_r[pt_i] <= #TCQ 1'b1;
else
idel_pat1_match_rise3_r[pt_i] <= #TCQ 1'b0;
if (sr_fall3_r[pt_i] == idel_pat1_fall3[pt_i%4])
idel_pat1_match_fall3_r[pt_i] <= #TCQ 1'b1;
else
idel_pat1_match_fall3_r[pt_i] <= #TCQ 1'b0;
end
// DQS DVW pattern detection
always @(posedge clk) begin
if (sr_rise0_r[pt_i] == pat0_rise0[pt_i%4])
pat0_match_rise0_r[pt_i] <= #TCQ 1'b1;
else
pat0_match_rise0_r[pt_i] <= #TCQ 1'b0;
if (sr_fall0_r[pt_i] == pat0_fall0[pt_i%4])
pat0_match_fall0_r[pt_i] <= #TCQ 1'b1;
else
pat0_match_fall0_r[pt_i] <= #TCQ 1'b0;
if (sr_rise1_r[pt_i] == pat0_rise1[pt_i%4])
pat0_match_rise1_r[pt_i] <= #TCQ 1'b1;
else
pat0_match_rise1_r[pt_i] <= #TCQ 1'b0;
if (sr_fall1_r[pt_i] == pat0_fall1[pt_i%4])
pat0_match_fall1_r[pt_i] <= #TCQ 1'b1;
else
pat0_match_fall1_r[pt_i] <= #TCQ 1'b0;
if (sr_rise2_r[pt_i] == pat0_rise2[pt_i%4])
pat0_match_rise2_r[pt_i] <= #TCQ 1'b1;
else
pat0_match_rise2_r[pt_i] <= #TCQ 1'b0;
if (sr_fall2_r[pt_i] == pat0_fall2[pt_i%4])
pat0_match_fall2_r[pt_i] <= #TCQ 1'b1;
else
pat0_match_fall2_r[pt_i] <= #TCQ 1'b0;
if (sr_rise3_r[pt_i] == pat0_rise3[pt_i%4])
pat0_match_rise3_r[pt_i] <= #TCQ 1'b1;
else
pat0_match_rise3_r[pt_i] <= #TCQ 1'b0;
if (sr_fall3_r[pt_i] == pat0_fall3[pt_i%4])
pat0_match_fall3_r[pt_i] <= #TCQ 1'b1;
else
pat0_match_fall3_r[pt_i] <= #TCQ 1'b0;
end
always @(posedge clk) begin
if (sr_rise0_r[pt_i] == pat1_rise0[pt_i%4])
pat1_match_rise0_r[pt_i] <= #TCQ 1'b1;
else
pat1_match_rise0_r[pt_i] <= #TCQ 1'b0;
if (sr_fall0_r[pt_i] == pat1_fall0[pt_i%4])
pat1_match_fall0_r[pt_i] <= #TCQ 1'b1;
else
pat1_match_fall0_r[pt_i] <= #TCQ 1'b0;
if (sr_rise1_r[pt_i] == pat1_rise1[pt_i%4])
pat1_match_rise1_r[pt_i] <= #TCQ 1'b1;
else
pat1_match_rise1_r[pt_i] <= #TCQ 1'b0;
if (sr_fall1_r[pt_i] == pat1_fall1[pt_i%4])
pat1_match_fall1_r[pt_i] <= #TCQ 1'b1;
else
pat1_match_fall1_r[pt_i] <= #TCQ 1'b0;
if (sr_rise2_r[pt_i] == pat1_rise2[pt_i%4])
pat1_match_rise2_r[pt_i] <= #TCQ 1'b1;
else
pat1_match_rise2_r[pt_i] <= #TCQ 1'b0;
if (sr_fall2_r[pt_i] == pat1_fall2[pt_i%4])
pat1_match_fall2_r[pt_i] <= #TCQ 1'b1;
else
pat1_match_fall2_r[pt_i] <= #TCQ 1'b0;
if (sr_rise3_r[pt_i] == pat1_rise3[pt_i%4])
pat1_match_rise3_r[pt_i] <= #TCQ 1'b1;
else
pat1_match_rise3_r[pt_i] <= #TCQ 1'b0;
if (sr_fall3_r[pt_i] == pat1_fall3[pt_i%4])
pat1_match_fall3_r[pt_i] <= #TCQ 1'b1;
else
pat1_match_fall3_r[pt_i] <= #TCQ 1'b0;
end
end
// Combine pattern match "subterms" for DQ-IDELAY stage
always @(posedge clk) begin
idel_pat0_match_rise0_and_r <= #TCQ &idel_pat0_match_rise0_r;
idel_pat0_match_fall0_and_r <= #TCQ &idel_pat0_match_fall0_r;
idel_pat0_match_rise1_and_r <= #TCQ &idel_pat0_match_rise1_r;
idel_pat0_match_fall1_and_r <= #TCQ &idel_pat0_match_fall1_r;
idel_pat0_match_rise2_and_r <= #TCQ &idel_pat0_match_rise2_r;
idel_pat0_match_fall2_and_r <= #TCQ &idel_pat0_match_fall2_r;
idel_pat0_match_rise3_and_r <= #TCQ &idel_pat0_match_rise3_r;
idel_pat0_match_fall3_and_r <= #TCQ &idel_pat0_match_fall3_r;
idel_pat0_data_match_r <= #TCQ (idel_pat0_match_rise0_and_r &&
idel_pat0_match_fall0_and_r &&
idel_pat0_match_rise1_and_r &&
idel_pat0_match_fall1_and_r &&
idel_pat0_match_rise2_and_r &&
idel_pat0_match_fall2_and_r &&
idel_pat0_match_rise3_and_r &&
idel_pat0_match_fall3_and_r);
end
always @(posedge clk) begin
idel_pat1_match_rise0_and_r <= #TCQ &idel_pat1_match_rise0_r;
idel_pat1_match_fall0_and_r <= #TCQ &idel_pat1_match_fall0_r;
idel_pat1_match_rise1_and_r <= #TCQ &idel_pat1_match_rise1_r;
idel_pat1_match_fall1_and_r <= #TCQ &idel_pat1_match_fall1_r;
idel_pat1_match_rise2_and_r <= #TCQ &idel_pat1_match_rise2_r;
idel_pat1_match_fall2_and_r <= #TCQ &idel_pat1_match_fall2_r;
idel_pat1_match_rise3_and_r <= #TCQ &idel_pat1_match_rise3_r;
idel_pat1_match_fall3_and_r <= #TCQ &idel_pat1_match_fall3_r;
idel_pat1_data_match_r <= #TCQ (idel_pat1_match_rise0_and_r &&
idel_pat1_match_fall0_and_r &&
idel_pat1_match_rise1_and_r &&
idel_pat1_match_fall1_and_r &&
idel_pat1_match_rise2_and_r &&
idel_pat1_match_fall2_and_r &&
idel_pat1_match_rise3_and_r &&
idel_pat1_match_fall3_and_r);
end
always @(idel_pat0_data_match_r or idel_pat1_data_match_r)
idel_pat_data_match <= #TCQ idel_pat0_data_match_r |
idel_pat1_data_match_r;
always @(posedge clk)
idel_pat_data_match_r <= #TCQ idel_pat_data_match;
// Combine pattern match "subterms" for DQS-PHASER_IN stage
always @(posedge clk) begin
pat0_match_rise0_and_r <= #TCQ &pat0_match_rise0_r;
pat0_match_fall0_and_r <= #TCQ &pat0_match_fall0_r;
pat0_match_rise1_and_r <= #TCQ &pat0_match_rise1_r;
pat0_match_fall1_and_r <= #TCQ &pat0_match_fall1_r;
pat0_match_rise2_and_r <= #TCQ &pat0_match_rise2_r;
pat0_match_fall2_and_r <= #TCQ &pat0_match_fall2_r;
pat0_match_rise3_and_r <= #TCQ &pat0_match_rise3_r;
pat0_match_fall3_and_r <= #TCQ &pat0_match_fall3_r;
pat0_data_match_r <= #TCQ (pat0_match_rise0_and_r &&
pat0_match_fall0_and_r &&
pat0_match_rise1_and_r &&
pat0_match_fall1_and_r &&
pat0_match_rise2_and_r &&
pat0_match_fall2_and_r &&
pat0_match_rise3_and_r &&
pat0_match_fall3_and_r);
end
always @(posedge clk) begin
pat1_match_rise0_and_r <= #TCQ &pat1_match_rise0_r;
pat1_match_fall0_and_r <= #TCQ &pat1_match_fall0_r;
pat1_match_rise1_and_r <= #TCQ &pat1_match_rise1_r;
pat1_match_fall1_and_r <= #TCQ &pat1_match_fall1_r;
pat1_match_rise2_and_r <= #TCQ &pat1_match_rise2_r;
pat1_match_fall2_and_r <= #TCQ &pat1_match_fall2_r;
pat1_match_rise3_and_r <= #TCQ &pat1_match_rise3_r;
pat1_match_fall3_and_r <= #TCQ &pat1_match_fall3_r;
pat1_data_match_r <= #TCQ (pat1_match_rise0_and_r &&
pat1_match_fall0_and_r &&
pat1_match_rise1_and_r &&
pat1_match_fall1_and_r &&
pat1_match_rise2_and_r &&
pat1_match_fall2_and_r &&
pat1_match_rise3_and_r &&
pat1_match_fall3_and_r);
end
assign pat_data_match_r = pat0_data_match_r | pat1_data_match_r;
end else if (nCK_PER_CLK == 2) begin: gen_pat_match_div2
for (pt_i = 0; pt_i < DRAM_WIDTH; pt_i = pt_i + 1) begin: gen_pat_match
// DQ IDELAY pattern detection
always @(posedge clk) begin
if (sr_rise0_r[pt_i] == idel_pat0_rise0[pt_i%4])
idel_pat0_match_rise0_r[pt_i] <= #TCQ 1'b1;
else
idel_pat0_match_rise0_r[pt_i] <= #TCQ 1'b0;
if (sr_fall0_r[pt_i] == idel_pat0_fall0[pt_i%4])
idel_pat0_match_fall0_r[pt_i] <= #TCQ 1'b1;
else
idel_pat0_match_fall0_r[pt_i] <= #TCQ 1'b0;
if (sr_rise1_r[pt_i] == idel_pat0_rise1[pt_i%4])
idel_pat0_match_rise1_r[pt_i] <= #TCQ 1'b1;
else
idel_pat0_match_rise1_r[pt_i] <= #TCQ 1'b0;
if (sr_fall1_r[pt_i] == idel_pat0_fall1[pt_i%4])
idel_pat0_match_fall1_r[pt_i] <= #TCQ 1'b1;
else
idel_pat0_match_fall1_r[pt_i] <= #TCQ 1'b0;
end
always @(posedge clk) begin
if (sr_rise0_r[pt_i] == idel_pat1_rise0[pt_i%4])
idel_pat1_match_rise0_r[pt_i] <= #TCQ 1'b1;
else
idel_pat1_match_rise0_r[pt_i] <= #TCQ 1'b0;
if (sr_fall0_r[pt_i] == idel_pat1_fall0[pt_i%4])
idel_pat1_match_fall0_r[pt_i] <= #TCQ 1'b1;
else
idel_pat1_match_fall0_r[pt_i] <= #TCQ 1'b0;
if (sr_rise1_r[pt_i] == idel_pat1_rise1[pt_i%4])
idel_pat1_match_rise1_r[pt_i] <= #TCQ 1'b1;
else
idel_pat1_match_rise1_r[pt_i] <= #TCQ 1'b0;
if (sr_fall1_r[pt_i] == idel_pat1_fall1[pt_i%4])
idel_pat1_match_fall1_r[pt_i] <= #TCQ 1'b1;
else
idel_pat1_match_fall1_r[pt_i] <= #TCQ 1'b0;
end
// DQS DVW pattern detection
always @(posedge clk) begin
if (sr_rise0_r[pt_i] == pat0_rise0[pt_i%4])
pat0_match_rise0_r[pt_i] <= #TCQ 1'b1;
else
pat0_match_rise0_r[pt_i] <= #TCQ 1'b0;
if (sr_fall0_r[pt_i] == pat0_fall0[pt_i%4])
pat0_match_fall0_r[pt_i] <= #TCQ 1'b1;
else
pat0_match_fall0_r[pt_i] <= #TCQ 1'b0;
if (sr_rise1_r[pt_i] == pat0_rise1[pt_i%4])
pat0_match_rise1_r[pt_i] <= #TCQ 1'b1;
else
pat0_match_rise1_r[pt_i] <= #TCQ 1'b0;
if (sr_fall1_r[pt_i] == pat0_fall1[pt_i%4])
pat0_match_fall1_r[pt_i] <= #TCQ 1'b1;
else
pat0_match_fall1_r[pt_i] <= #TCQ 1'b0;
end
always @(posedge clk) begin
if (sr_rise0_r[pt_i] == pat1_rise0[pt_i%4])
pat1_match_rise0_r[pt_i] <= #TCQ 1'b1;
else
pat1_match_rise0_r[pt_i] <= #TCQ 1'b0;
if (sr_fall0_r[pt_i] == pat1_fall0[pt_i%4])
pat1_match_fall0_r[pt_i] <= #TCQ 1'b1;
else
pat1_match_fall0_r[pt_i] <= #TCQ 1'b0;
if (sr_rise1_r[pt_i] == pat1_rise1[pt_i%4])
pat1_match_rise1_r[pt_i] <= #TCQ 1'b1;
else
pat1_match_rise1_r[pt_i] <= #TCQ 1'b0;
if (sr_fall1_r[pt_i] == pat1_fall1[pt_i%4])
pat1_match_fall1_r[pt_i] <= #TCQ 1'b1;
else
pat1_match_fall1_r[pt_i] <= #TCQ 1'b0;
end
end
// Combine pattern match "subterms" for DQ-IDELAY stage
always @(posedge clk) begin
idel_pat0_match_rise0_and_r <= #TCQ &idel_pat0_match_rise0_r;
idel_pat0_match_fall0_and_r <= #TCQ &idel_pat0_match_fall0_r;
idel_pat0_match_rise1_and_r <= #TCQ &idel_pat0_match_rise1_r;
idel_pat0_match_fall1_and_r <= #TCQ &idel_pat0_match_fall1_r;
idel_pat0_data_match_r <= #TCQ (idel_pat0_match_rise0_and_r &&
idel_pat0_match_fall0_and_r &&
idel_pat0_match_rise1_and_r &&
idel_pat0_match_fall1_and_r);
end
always @(posedge clk) begin
idel_pat1_match_rise0_and_r <= #TCQ &idel_pat1_match_rise0_r;
idel_pat1_match_fall0_and_r <= #TCQ &idel_pat1_match_fall0_r;
idel_pat1_match_rise1_and_r <= #TCQ &idel_pat1_match_rise1_r;
idel_pat1_match_fall1_and_r <= #TCQ &idel_pat1_match_fall1_r;
idel_pat1_data_match_r <= #TCQ (idel_pat1_match_rise0_and_r &&
idel_pat1_match_fall0_and_r &&
idel_pat1_match_rise1_and_r &&
idel_pat1_match_fall1_and_r);
end
always @(posedge clk) begin
if (sr_valid_r2)
idel_pat_data_match <= #TCQ idel_pat0_data_match_r |
idel_pat1_data_match_r;
end
//assign idel_pat_data_match = idel_pat0_data_match_r |
// idel_pat1_data_match_r;
always @(posedge clk)
idel_pat_data_match_r <= #TCQ idel_pat_data_match;
// Combine pattern match "subterms" for DQS-PHASER_IN stage
always @(posedge clk) begin
pat0_match_rise0_and_r <= #TCQ &pat0_match_rise0_r;
pat0_match_fall0_and_r <= #TCQ &pat0_match_fall0_r;
pat0_match_rise1_and_r <= #TCQ &pat0_match_rise1_r;
pat0_match_fall1_and_r <= #TCQ &pat0_match_fall1_r;
pat0_data_match_r <= #TCQ (pat0_match_rise0_and_r &&
pat0_match_fall0_and_r &&
pat0_match_rise1_and_r &&
pat0_match_fall1_and_r);
end
always @(posedge clk) begin
pat1_match_rise0_and_r <= #TCQ &pat1_match_rise0_r;
pat1_match_fall0_and_r <= #TCQ &pat1_match_fall0_r;
pat1_match_rise1_and_r <= #TCQ &pat1_match_rise1_r;
pat1_match_fall1_and_r <= #TCQ &pat1_match_fall1_r;
pat1_data_match_r <= #TCQ (pat1_match_rise0_and_r &&
pat1_match_fall0_and_r &&
pat1_match_rise1_and_r &&
pat1_match_fall1_and_r);
end
assign pat_data_match_r = pat0_data_match_r | pat1_data_match_r;
end
endgenerate
always @(posedge clk) begin
rdlvl_stg1_start_r <= #TCQ rdlvl_stg1_start;
mpr_rdlvl_done_r1 <= #TCQ mpr_rdlvl_done_r;
mpr_rdlvl_done_r2 <= #TCQ mpr_rdlvl_done_r1;
mpr_rdlvl_start_r <= #TCQ mpr_rdlvl_start;
end
//***************************************************************************
// First stage calibration: Capture clock
//***************************************************************************
//*****************************************************************
// Keep track of how many samples have been written to shift registers
// Every time RD_SHIFT_LEN samples have been written, then we have a
// full read training pattern loaded into the sr_* registers. Then assert
// sr_valid_r to indicate that: (1) comparison between the sr_* and
// old_sr_* and prev_sr_* registers can take place, (2) transfer of
// the contents of sr_* to old_sr_* and prev_sr_* registers can also
// take place
//*****************************************************************
always @(posedge clk)
if (rst || (mpr_rdlvl_done_r && ~rdlvl_stg1_start)) begin
cnt_shift_r <= #TCQ 'b1;
sr_valid_r <= #TCQ 1'b0;
mpr_valid_r <= #TCQ 1'b0;
end else begin
if (mux_rd_valid_r && mpr_rdlvl_start && ~mpr_rdlvl_done_r) begin
if (cnt_shift_r == 'b0)
mpr_valid_r <= #TCQ 1'b1;
else begin
mpr_valid_r <= #TCQ 1'b0;
cnt_shift_r <= #TCQ cnt_shift_r + 1;
end
end else
mpr_valid_r <= #TCQ 1'b0;
if (mux_rd_valid_r && rdlvl_stg1_start) begin
if (cnt_shift_r == RD_SHIFT_LEN-1) begin
sr_valid_r <= #TCQ 1'b1;
cnt_shift_r <= #TCQ 'b0;
end else begin
sr_valid_r <= #TCQ 1'b0;
cnt_shift_r <= #TCQ cnt_shift_r + 1;
end
end else
// When the current mux_rd_* contents are not valid, then
// retain the current value of cnt_shift_r, and make sure
// that sr_valid_r = 0 to prevent any downstream loads or
// comparisons
sr_valid_r <= #TCQ 1'b0;
end
//*****************************************************************
// Logic to determine when either edge of the data eye encountered
// Pre- and post-IDELAY update data pattern is compared, if they
// differ, than an edge has been encountered. Currently no attempt
// made to determine if the data pattern itself is "correct", only
// whether it changes after incrementing the IDELAY (possible
// future enhancement)
//*****************************************************************
// One-way control for ensuring that state machine request to store
// current read data into OLD SR shift register only occurs on a
// valid clock cycle. The FSM provides a one-cycle request pulse.
// It is the responsibility of the FSM to wait the worst-case time
// before relying on any downstream results of this load.
always @(posedge clk)
if (rst)
store_sr_r <= #TCQ 1'b0;
else begin
if (store_sr_req_r)
store_sr_r <= #TCQ 1'b1;
else if ((sr_valid_r || mpr_valid_r) && store_sr_r)
store_sr_r <= #TCQ 1'b0;
end
// Transfer current data to old data, prior to incrementing delay
// Also store data from current sampling window - so that we can detect
// if the current delay tap yields data that is "jittery"
generate
if (nCK_PER_CLK == 4) begin: gen_old_sr_div4
for (z = 0; z < DRAM_WIDTH; z = z + 1) begin: gen_old_sr
always @(posedge clk) begin
if (sr_valid_r || mpr_valid_r) begin
// Load last sample (i.e. from current sampling interval)
prev_sr_rise0_r[z] <= #TCQ sr_rise0_r[z];
prev_sr_fall0_r[z] <= #TCQ sr_fall0_r[z];
prev_sr_rise1_r[z] <= #TCQ sr_rise1_r[z];
prev_sr_fall1_r[z] <= #TCQ sr_fall1_r[z];
prev_sr_rise2_r[z] <= #TCQ sr_rise2_r[z];
prev_sr_fall2_r[z] <= #TCQ sr_fall2_r[z];
prev_sr_rise3_r[z] <= #TCQ sr_rise3_r[z];
prev_sr_fall3_r[z] <= #TCQ sr_fall3_r[z];
end
if ((sr_valid_r || mpr_valid_r) && store_sr_r) begin
old_sr_rise0_r[z] <= #TCQ sr_rise0_r[z];
old_sr_fall0_r[z] <= #TCQ sr_fall0_r[z];
old_sr_rise1_r[z] <= #TCQ sr_rise1_r[z];
old_sr_fall1_r[z] <= #TCQ sr_fall1_r[z];
old_sr_rise2_r[z] <= #TCQ sr_rise2_r[z];
old_sr_fall2_r[z] <= #TCQ sr_fall2_r[z];
old_sr_rise3_r[z] <= #TCQ sr_rise3_r[z];
old_sr_fall3_r[z] <= #TCQ sr_fall3_r[z];
end
end
end
end else if (nCK_PER_CLK == 2) begin: gen_old_sr_div2
for (z = 0; z < DRAM_WIDTH; z = z + 1) begin: gen_old_sr
always @(posedge clk) begin
if (sr_valid_r || mpr_valid_r) begin
prev_sr_rise0_r[z] <= #TCQ sr_rise0_r[z];
prev_sr_fall0_r[z] <= #TCQ sr_fall0_r[z];
prev_sr_rise1_r[z] <= #TCQ sr_rise1_r[z];
prev_sr_fall1_r[z] <= #TCQ sr_fall1_r[z];
end
if ((sr_valid_r || mpr_valid_r) && store_sr_r) begin
old_sr_rise0_r[z] <= #TCQ sr_rise0_r[z];
old_sr_fall0_r[z] <= #TCQ sr_fall0_r[z];
old_sr_rise1_r[z] <= #TCQ sr_rise1_r[z];
old_sr_fall1_r[z] <= #TCQ sr_fall1_r[z];
end
end
end
end
endgenerate
//*******************************************************
// Match determination occurs over 3 cycles - pipelined for better timing
//*******************************************************
// Match valid with # of cycles of pipelining in match determination
always @(posedge clk) begin
sr_valid_r1 <= #TCQ sr_valid_r;
sr_valid_r2 <= #TCQ sr_valid_r1;
mpr_valid_r1 <= #TCQ mpr_valid_r;
mpr_valid_r2 <= #TCQ mpr_valid_r1;
end
generate
if (nCK_PER_CLK == 4) begin: gen_sr_match_div4
for (z = 0; z < DRAM_WIDTH; z = z + 1) begin: gen_sr_match
always @(posedge clk) begin
// CYCLE1: Compare all bits in DQS grp, generate separate term for
// each bit over four bit times. For example, if there are 8-bits
// per DQS group, 32 terms are generated on cycle 1
// NOTE: Structure HDL such that X on data bus will result in a
// mismatch. This is required for memory models that can drive the
// bus with X's to model uncertainty regions (e.g. Denali)
if ((pat_data_match_r || mpr_valid_r1) && (sr_rise0_r[z] == old_sr_rise0_r[z]))
old_sr_match_rise0_r[z] <= #TCQ 1'b1;
else if (~mpr_valid_r1 && mpr_rdlvl_start && ~mpr_rdlvl_done_r)
old_sr_match_rise0_r[z] <= #TCQ old_sr_match_rise0_r[z];
else
old_sr_match_rise0_r[z] <= #TCQ 1'b0;
if ((pat_data_match_r || mpr_valid_r1) && (sr_fall0_r[z] == old_sr_fall0_r[z]))
old_sr_match_fall0_r[z] <= #TCQ 1'b1;
else if (~mpr_valid_r1 && mpr_rdlvl_start && ~mpr_rdlvl_done_r)
old_sr_match_fall0_r[z] <= #TCQ old_sr_match_fall0_r[z];
else
old_sr_match_fall0_r[z] <= #TCQ 1'b0;
if ((pat_data_match_r || mpr_valid_r1) && (sr_rise1_r[z] == old_sr_rise1_r[z]))
old_sr_match_rise1_r[z] <= #TCQ 1'b1;
else if (~mpr_valid_r1 && mpr_rdlvl_start && ~mpr_rdlvl_done_r)
old_sr_match_rise1_r[z] <= #TCQ old_sr_match_rise1_r[z];
else
old_sr_match_rise1_r[z] <= #TCQ 1'b0;
if ((pat_data_match_r || mpr_valid_r1) && (sr_fall1_r[z] == old_sr_fall1_r[z]))
old_sr_match_fall1_r[z] <= #TCQ 1'b1;
else if (~mpr_valid_r1 && mpr_rdlvl_start && ~mpr_rdlvl_done_r)
old_sr_match_fall1_r[z] <= #TCQ old_sr_match_fall1_r[z];
else
old_sr_match_fall1_r[z] <= #TCQ 1'b0;
if ((pat_data_match_r || mpr_valid_r1) && (sr_rise2_r[z] == old_sr_rise2_r[z]))
old_sr_match_rise2_r[z] <= #TCQ 1'b1;
else if (~mpr_valid_r1 && mpr_rdlvl_start && ~mpr_rdlvl_done_r)
old_sr_match_rise2_r[z] <= #TCQ old_sr_match_rise2_r[z];
else
old_sr_match_rise2_r[z] <= #TCQ 1'b0;
if ((pat_data_match_r || mpr_valid_r1) && (sr_fall2_r[z] == old_sr_fall2_r[z]))
old_sr_match_fall2_r[z] <= #TCQ 1'b1;
else if (~mpr_valid_r1 && mpr_rdlvl_start && ~mpr_rdlvl_done_r)
old_sr_match_fall2_r[z] <= #TCQ old_sr_match_fall2_r[z];
else
old_sr_match_fall2_r[z] <= #TCQ 1'b0;
if ((pat_data_match_r || mpr_valid_r1) && (sr_rise3_r[z] == old_sr_rise3_r[z]))
old_sr_match_rise3_r[z] <= #TCQ 1'b1;
else if (~mpr_valid_r1 && mpr_rdlvl_start && ~mpr_rdlvl_done_r)
old_sr_match_rise3_r[z] <= #TCQ old_sr_match_rise3_r[z];
else
old_sr_match_rise3_r[z] <= #TCQ 1'b0;
if ((pat_data_match_r || mpr_valid_r1) && (sr_fall3_r[z] == old_sr_fall3_r[z]))
old_sr_match_fall3_r[z] <= #TCQ 1'b1;
else if (~mpr_valid_r1 && mpr_rdlvl_start && ~mpr_rdlvl_done_r)
old_sr_match_fall3_r[z] <= #TCQ old_sr_match_fall3_r[z];
else
old_sr_match_fall3_r[z] <= #TCQ 1'b0;
if ((pat_data_match_r || mpr_valid_r1) && (sr_rise0_r[z] == prev_sr_rise0_r[z]))
prev_sr_match_rise0_r[z] <= #TCQ 1'b1;
else if (~mpr_valid_r1 && mpr_rdlvl_start && ~mpr_rdlvl_done_r)
prev_sr_match_rise0_r[z] <= #TCQ prev_sr_match_rise0_r[z];
else
prev_sr_match_rise0_r[z] <= #TCQ 1'b0;
if ((pat_data_match_r || mpr_valid_r1) && (sr_fall0_r[z] == prev_sr_fall0_r[z]))
prev_sr_match_fall0_r[z] <= #TCQ 1'b1;
else if (~mpr_valid_r1 && mpr_rdlvl_start && ~mpr_rdlvl_done_r)
prev_sr_match_fall0_r[z] <= #TCQ prev_sr_match_fall0_r[z];
else
prev_sr_match_fall0_r[z] <= #TCQ 1'b0;
if ((pat_data_match_r || mpr_valid_r1) && (sr_rise1_r[z] == prev_sr_rise1_r[z]))
prev_sr_match_rise1_r[z] <= #TCQ 1'b1;
else if (~mpr_valid_r1 && mpr_rdlvl_start && ~mpr_rdlvl_done_r)
prev_sr_match_rise1_r[z] <= #TCQ prev_sr_match_rise1_r[z];
else
prev_sr_match_rise1_r[z] <= #TCQ 1'b0;
if ((pat_data_match_r || mpr_valid_r1) && (sr_fall1_r[z] == prev_sr_fall1_r[z]))
prev_sr_match_fall1_r[z] <= #TCQ 1'b1;
else if (~mpr_valid_r1 && mpr_rdlvl_start && ~mpr_rdlvl_done_r)
prev_sr_match_fall1_r[z] <= #TCQ prev_sr_match_fall1_r[z];
else
prev_sr_match_fall1_r[z] <= #TCQ 1'b0;
if ((pat_data_match_r || mpr_valid_r1) && (sr_rise2_r[z] == prev_sr_rise2_r[z]))
prev_sr_match_rise2_r[z] <= #TCQ 1'b1;
else if (~mpr_valid_r1 && mpr_rdlvl_start && ~mpr_rdlvl_done_r)
prev_sr_match_rise2_r[z] <= #TCQ prev_sr_match_rise2_r[z];
else
prev_sr_match_rise2_r[z] <= #TCQ 1'b0;
if ((pat_data_match_r || mpr_valid_r1) && (sr_fall2_r[z] == prev_sr_fall2_r[z]))
prev_sr_match_fall2_r[z] <= #TCQ 1'b1;
else if (~mpr_valid_r1 && mpr_rdlvl_start && ~mpr_rdlvl_done_r)
prev_sr_match_fall2_r[z] <= #TCQ prev_sr_match_fall2_r[z];
else
prev_sr_match_fall2_r[z] <= #TCQ 1'b0;
if ((pat_data_match_r || mpr_valid_r1) && (sr_rise3_r[z] == prev_sr_rise3_r[z]))
prev_sr_match_rise3_r[z] <= #TCQ 1'b1;
else if (~mpr_valid_r1 && mpr_rdlvl_start && ~mpr_rdlvl_done_r)
prev_sr_match_rise3_r[z] <= #TCQ prev_sr_match_rise3_r[z];
else
prev_sr_match_rise3_r[z] <= #TCQ 1'b0;
if ((pat_data_match_r || mpr_valid_r1) && (sr_fall3_r[z] == prev_sr_fall3_r[z]))
prev_sr_match_fall3_r[z] <= #TCQ 1'b1;
else if (~mpr_valid_r1 && mpr_rdlvl_start && ~mpr_rdlvl_done_r)
prev_sr_match_fall3_r[z] <= #TCQ prev_sr_match_fall3_r[z];
else
prev_sr_match_fall3_r[z] <= #TCQ 1'b0;
// CYCLE2: Combine all the comparisons for every 8 words (rise0,
// fall0,rise1, fall1) in the calibration sequence. Now we're down
// to DRAM_WIDTH terms
old_sr_match_cyc2_r[z] <= #TCQ
old_sr_match_rise0_r[z] &
old_sr_match_fall0_r[z] &
old_sr_match_rise1_r[z] &
old_sr_match_fall1_r[z] &
old_sr_match_rise2_r[z] &
old_sr_match_fall2_r[z] &
old_sr_match_rise3_r[z] &
old_sr_match_fall3_r[z];
prev_sr_match_cyc2_r[z] <= #TCQ
prev_sr_match_rise0_r[z] &
prev_sr_match_fall0_r[z] &
prev_sr_match_rise1_r[z] &
prev_sr_match_fall1_r[z] &
prev_sr_match_rise2_r[z] &
prev_sr_match_fall2_r[z] &
prev_sr_match_rise3_r[z] &
prev_sr_match_fall3_r[z];
// CYCLE3: Invert value (i.e. assert when DIFFERENCE in value seen),
// and qualify with pipelined valid signal) - probably don't need
// a cycle just do do this....
if (sr_valid_r2 || mpr_valid_r2) begin
old_sr_diff_r[z] <= #TCQ ~old_sr_match_cyc2_r[z];
prev_sr_diff_r[z] <= #TCQ ~prev_sr_match_cyc2_r[z];
end else begin
old_sr_diff_r[z] <= #TCQ 'b0;
prev_sr_diff_r[z] <= #TCQ 'b0;
end
end
end
end if (nCK_PER_CLK == 2) begin: gen_sr_match_div2
for (z = 0; z < DRAM_WIDTH; z = z + 1) begin: gen_sr_match
always @(posedge clk) begin
if ((pat_data_match_r || mpr_valid_r1) && (sr_rise0_r[z] == old_sr_rise0_r[z]))
old_sr_match_rise0_r[z] <= #TCQ 1'b1;
else if (~mpr_valid_r1 && mpr_rdlvl_start && ~mpr_rdlvl_done_r)
old_sr_match_rise0_r[z] <= #TCQ old_sr_match_rise0_r[z];
else
old_sr_match_rise0_r[z] <= #TCQ 1'b0;
if ((pat_data_match_r || mpr_valid_r1) && (sr_fall0_r[z] == old_sr_fall0_r[z]))
old_sr_match_fall0_r[z] <= #TCQ 1'b1;
else if (~mpr_valid_r1 && mpr_rdlvl_start && ~mpr_rdlvl_done_r)
old_sr_match_fall0_r[z] <= #TCQ old_sr_match_fall0_r[z];
else
old_sr_match_fall0_r[z] <= #TCQ 1'b0;
if ((pat_data_match_r || mpr_valid_r1) && (sr_rise1_r[z] == old_sr_rise1_r[z]))
old_sr_match_rise1_r[z] <= #TCQ 1'b1;
else if (~mpr_valid_r1 && mpr_rdlvl_start && ~mpr_rdlvl_done_r)
old_sr_match_rise1_r[z] <= #TCQ old_sr_match_rise1_r[z];
else
old_sr_match_rise1_r[z] <= #TCQ 1'b0;
if ((pat_data_match_r || mpr_valid_r1) && (sr_fall1_r[z] == old_sr_fall1_r[z]))
old_sr_match_fall1_r[z] <= #TCQ 1'b1;
else if (~mpr_valid_r1 && mpr_rdlvl_start && ~mpr_rdlvl_done_r)
old_sr_match_fall1_r[z] <= #TCQ old_sr_match_fall1_r[z];
else
old_sr_match_fall1_r[z] <= #TCQ 1'b0;
if ((pat_data_match_r || mpr_valid_r1) && (sr_rise0_r[z] == prev_sr_rise0_r[z]))
prev_sr_match_rise0_r[z] <= #TCQ 1'b1;
else if (~mpr_valid_r1 && mpr_rdlvl_start && ~mpr_rdlvl_done_r)
prev_sr_match_rise0_r[z] <= #TCQ prev_sr_match_rise0_r[z];
else
prev_sr_match_rise0_r[z] <= #TCQ 1'b0;
if ((pat_data_match_r || mpr_valid_r1) && (sr_fall0_r[z] == prev_sr_fall0_r[z]))
prev_sr_match_fall0_r[z] <= #TCQ 1'b1;
else if (~mpr_valid_r1 && mpr_rdlvl_start && ~mpr_rdlvl_done_r)
prev_sr_match_fall0_r[z] <= #TCQ prev_sr_match_fall0_r[z];
else
prev_sr_match_fall0_r[z] <= #TCQ 1'b0;
if ((pat_data_match_r || mpr_valid_r1) && (sr_rise1_r[z] == prev_sr_rise1_r[z]))
prev_sr_match_rise1_r[z] <= #TCQ 1'b1;
else if (~mpr_valid_r1 && mpr_rdlvl_start && ~mpr_rdlvl_done_r)
prev_sr_match_rise1_r[z] <= #TCQ prev_sr_match_rise1_r[z];
else
prev_sr_match_rise1_r[z] <= #TCQ 1'b0;
if ((pat_data_match_r || mpr_valid_r1) && (sr_fall1_r[z] == prev_sr_fall1_r[z]))
prev_sr_match_fall1_r[z] <= #TCQ 1'b1;
else if (~mpr_valid_r1 && mpr_rdlvl_start && ~mpr_rdlvl_done_r)
prev_sr_match_fall1_r[z] <= #TCQ prev_sr_match_fall1_r[z];
else
prev_sr_match_fall1_r[z] <= #TCQ 1'b0;
old_sr_match_cyc2_r[z] <= #TCQ
old_sr_match_rise0_r[z] &
old_sr_match_fall0_r[z] &
old_sr_match_rise1_r[z] &
old_sr_match_fall1_r[z];
prev_sr_match_cyc2_r[z] <= #TCQ
prev_sr_match_rise0_r[z] &
prev_sr_match_fall0_r[z] &
prev_sr_match_rise1_r[z] &
prev_sr_match_fall1_r[z];
// CYCLE3: Invert value (i.e. assert when DIFFERENCE in value seen),
// and qualify with pipelined valid signal) - probably don't need
// a cycle just do do this....
if (sr_valid_r2 || mpr_valid_r2) begin
old_sr_diff_r[z] <= #TCQ ~old_sr_match_cyc2_r[z];
prev_sr_diff_r[z] <= #TCQ ~prev_sr_match_cyc2_r[z];
end else begin
old_sr_diff_r[z] <= #TCQ 'b0;
prev_sr_diff_r[z] <= #TCQ 'b0;
end
end
end
end
endgenerate
//***************************************************************************
// First stage calibration: DQS Capture
//***************************************************************************
//*******************************************************
// Counters for tracking # of samples compared
// For each comparision point (i.e. to determine if an edge has
// occurred after each IODELAY increment when read leveling),
// multiple samples are compared in order to average out the effects
// of jitter. If any one of these samples is different than the "old"
// sample corresponding to the previous IODELAY value, then an edge
// is declared to be detected.
//*******************************************************
// Two cascaded counters are used to keep track of # of samples compared,
// in order to make it easier to meeting timing on these paths. Once
// optimal sampling interval is determined, it may be possible to remove
// the second counter
always @(posedge clk)
samp_edge_cnt0_en_r <= #TCQ
(cal1_state_r == CAL1_PAT_DETECT) ||
(cal1_state_r == CAL1_DETECT_EDGE) ||
(cal1_state_r == CAL1_PB_DETECT_EDGE) ||
(cal1_state_r == CAL1_PB_DETECT_EDGE_DQ);
// First counter counts # of samples compared
always @(posedge clk)
if (rst)
samp_edge_cnt0_r <= #TCQ 'b0;
else begin
if (!samp_edge_cnt0_en_r)
// Reset sample counter when not in any of the "sampling" states
samp_edge_cnt0_r <= #TCQ 'b0;
else if (sr_valid_r2 || mpr_valid_r2)
// Otherwise, count # of samples compared
samp_edge_cnt0_r <= #TCQ samp_edge_cnt0_r + 1;
end
// Counter #2 enable generation
always @(posedge clk)
if (rst)
samp_edge_cnt1_en_r <= #TCQ 1'b0;
else begin
// Assert pulse when correct number of samples compared
if ((samp_edge_cnt0_r == DETECT_EDGE_SAMPLE_CNT0) &&
(sr_valid_r2 || mpr_valid_r2))
samp_edge_cnt1_en_r <= #TCQ 1'b1;
else
samp_edge_cnt1_en_r <= #TCQ 1'b0;
end
// Counter #2
always @(posedge clk)
if (rst)
samp_edge_cnt1_r <= #TCQ 'b0;
else
if (!samp_edge_cnt0_en_r)
samp_edge_cnt1_r <= #TCQ 'b0;
else if (samp_edge_cnt1_en_r)
samp_edge_cnt1_r <= #TCQ samp_edge_cnt1_r + 1;
always @(posedge clk)
if (rst)
samp_cnt_done_r <= #TCQ 1'b0;
else begin
if (!samp_edge_cnt0_en_r)
samp_cnt_done_r <= #TCQ 'b0;
else if ((SIM_CAL_OPTION == "FAST_CAL") ||
(SIM_CAL_OPTION == "FAST_WIN_DETECT")) begin
if (samp_edge_cnt0_r == SR_VALID_DELAY-1)
// For simulation only, stay in edge detection mode a minimum
// amount of time - just enough for two data compares to finish
samp_cnt_done_r <= #TCQ 1'b1;
end else begin
if (samp_edge_cnt1_r == DETECT_EDGE_SAMPLE_CNT1)
samp_cnt_done_r <= #TCQ 1'b1;
end
end
//*****************************************************************
// Logic to keep track of (on per-bit basis):
// 1. When a region of stability preceded by a known edge occurs
// 2. If for the current tap, the read data jitters
// 3. If an edge occured between the current and previous tap
// 4. When the current edge detection/sampling interval can end
// Essentially, these are a series of status bits - the stage 1
// calibration FSM monitors these to determine when an edge is
// found. Additional information is provided to help the FSM
// determine if a left or right edge has been found.
//****************************************************************
assign pb_detect_edge_setup
= (cal1_state_r == CAL1_STORE_FIRST_WAIT) ||
(cal1_state_r == CAL1_PB_STORE_FIRST_WAIT) ||
(cal1_state_r == CAL1_PB_DEC_CPT_LEFT_WAIT);
assign pb_detect_edge
= (cal1_state_r == CAL1_PAT_DETECT) ||
(cal1_state_r == CAL1_DETECT_EDGE) ||
(cal1_state_r == CAL1_PB_DETECT_EDGE) ||
(cal1_state_r == CAL1_PB_DETECT_EDGE_DQ);
generate
for (z = 0; z < DRAM_WIDTH; z = z + 1) begin: gen_track_left_edge
always @(posedge clk) begin
if (pb_detect_edge_setup) begin
// Reset eye size, stable eye marker, and jitter marker before
// starting new edge detection iteration
pb_cnt_eye_size_r[z] <= #TCQ 5'd0;
pb_detect_edge_done_r[z] <= #TCQ 1'b0;
pb_found_stable_eye_r[z] <= #TCQ 1'b0;
pb_last_tap_jitter_r[z] <= #TCQ 1'b0;
pb_found_edge_last_r[z] <= #TCQ 1'b0;
pb_found_edge_r[z] <= #TCQ 1'b0;
pb_found_first_edge_r[z] <= #TCQ 1'b0;
end else if (pb_detect_edge) begin
// Save information on which DQ bits are already out of the
// data valid window - those DQ bits will later not have their
// IDELAY tap value incremented
pb_found_edge_last_r[z] <= #TCQ pb_found_edge_r[z];
if (!pb_detect_edge_done_r[z]) begin
if (samp_cnt_done_r) begin
// If we've reached end of sampling interval, no jitter on
// current tap has been found (although an edge could have
// been found between the current and previous taps), and
// the sampling interval is complete. Increment the stable
// eye counter if no edge found, and always clear the jitter
// flag in preparation for the next tap.
pb_last_tap_jitter_r[z] <= #TCQ 1'b0;
pb_detect_edge_done_r[z] <= #TCQ 1'b1;
if (!pb_found_edge_r[z] && !pb_last_tap_jitter_r[z]) begin
// If the data was completely stable during this tap and
// no edge was found between this and the previous tap
// then increment the stable eye counter "as appropriate"
if (pb_cnt_eye_size_r[z] != MIN_EYE_SIZE-1)
pb_cnt_eye_size_r[z] <= #TCQ pb_cnt_eye_size_r[z] + 1;
else //if (pb_found_first_edge_r[z])
// We've reached minimum stable eye width
pb_found_stable_eye_r[z] <= #TCQ 1'b1;
end else begin
// Otherwise, an edge was found, either because of a
// difference between this and the previous tap's read
// data, and/or because the previous tap's data jittered
// (but not the current tap's data), then just set the
// edge found flag, and enable the stable eye counter
pb_cnt_eye_size_r[z] <= #TCQ 5'd0;
pb_found_stable_eye_r[z] <= #TCQ 1'b0;
pb_found_edge_r[z] <= #TCQ 1'b1;
pb_detect_edge_done_r[z] <= #TCQ 1'b1;
end
end else if (prev_sr_diff_r[z]) begin
// If we find that the current tap read data jitters, then
// set edge and jitter found flags, "enable" the eye size
// counter, and stop sampling interval for this bit
pb_cnt_eye_size_r[z] <= #TCQ 5'd0;
pb_found_stable_eye_r[z] <= #TCQ 1'b0;
pb_last_tap_jitter_r[z] <= #TCQ 1'b1;
pb_found_edge_r[z] <= #TCQ 1'b1;
pb_found_first_edge_r[z] <= #TCQ 1'b1;
pb_detect_edge_done_r[z] <= #TCQ 1'b1;
end else if (old_sr_diff_r[z] || pb_last_tap_jitter_r[z]) begin
// If either an edge was found (i.e. difference between
// current tap and previous tap read data), or the previous
// tap exhibited jitter (which means by definition that the
// current tap cannot match the previous tap because the
// previous tap gave unstable data), then set the edge found
// flag, and "enable" eye size counter. But do not stop
// sampling interval - we still need to check if the current
// tap exhibits jitter
pb_cnt_eye_size_r[z] <= #TCQ 5'd0;
pb_found_stable_eye_r[z] <= #TCQ 1'b0;
pb_found_edge_r[z] <= #TCQ 1'b1;
pb_found_first_edge_r[z] <= #TCQ 1'b1;
end
end
end else begin
// Before every edge detection interval, reset "intra-tap" flags
pb_found_edge_r[z] <= #TCQ 1'b0;
pb_detect_edge_done_r[z] <= #TCQ 1'b0;
end
end
end
endgenerate
// Combine the above per-bit status flags into combined terms when
// performing deskew on the aggregate data window
always @(posedge clk) begin
detect_edge_done_r <= #TCQ &pb_detect_edge_done_r;
found_edge_r <= #TCQ |pb_found_edge_r;
found_edge_all_r <= #TCQ &pb_found_edge_r;
found_stable_eye_r <= #TCQ &pb_found_stable_eye_r;
end
// last IODELAY "stable eye" indicator is updated only after
// detect_edge_done_r is asserted - so that when we do find the "right edge"
// of the data valid window, found_edge_r = 1, AND found_stable_eye_r = 1
// when detect_edge_done_r = 1 (otherwise, if found_stable_eye_r updates
// immediately, then it never possible to have found_stable_eye_r = 1
// when we detect an edge - and we'll never know whether we've found
// a "right edge")
always @(posedge clk)
if (pb_detect_edge_setup)
found_stable_eye_last_r <= #TCQ 1'b0;
else if (detect_edge_done_r)
found_stable_eye_last_r <= #TCQ found_stable_eye_r;
//*****************************************************************
// Keep track of DQ IDELAYE2 taps used
//*****************************************************************
// Added additional register stage to improve timing
always @(posedge clk)
if (rst)
idelay_tap_cnt_slice_r <= 5'h0;
else
idelay_tap_cnt_slice_r <= idelay_tap_cnt_r[rnk_cnt_r][cal1_cnt_cpt_timing];
always @(posedge clk)
if (rst || (SIM_CAL_OPTION == "SKIP_CAL")) begin //|| new_cnt_cpt_r
for (s = 0; s < RANKS; s = s + 1) begin
for (t = 0; t < DQS_WIDTH; t = t + 1) begin
idelay_tap_cnt_r[s][t] <= #TCQ idelaye2_init_val;
end
end
end else if (SIM_CAL_OPTION == "FAST_CAL") begin
for (u = 0; u < RANKS; u = u + 1) begin
for (w = 0; w < DQS_WIDTH; w = w + 1) begin
if (cal1_dq_idel_ce) begin
if (cal1_dq_idel_inc)
idelay_tap_cnt_r[u][w] <= #TCQ idelay_tap_cnt_r[u][w] + 1;
else
idelay_tap_cnt_r[u][w] <= #TCQ idelay_tap_cnt_r[u][w] - 1;
end
end
end
end else if ((rnk_cnt_r == RANKS-1) && (RANKS == 2) &&
rdlvl_rank_done_r && (cal1_state_r == CAL1_IDLE)) begin
for (f = 0; f < DQS_WIDTH; f = f + 1) begin
idelay_tap_cnt_r[rnk_cnt_r][f] <= #TCQ idelay_tap_cnt_r[(rnk_cnt_r-1)][f];
end
end else if (cal1_dq_idel_ce) begin
if (cal1_dq_idel_inc)
idelay_tap_cnt_r[rnk_cnt_r][cal1_cnt_cpt_timing] <= #TCQ idelay_tap_cnt_slice_r + 5'h1;
else
idelay_tap_cnt_r[rnk_cnt_r][cal1_cnt_cpt_timing] <= #TCQ idelay_tap_cnt_slice_r - 5'h1;
end else if (idelay_ld)
idelay_tap_cnt_r[0][wrcal_cnt] <= #TCQ 5'b00000;
always @(posedge clk)
if (rst || new_cnt_cpt_r)
idelay_tap_limit_r <= #TCQ 1'b0;
else if (idelay_tap_cnt_r[rnk_cnt_r][cal1_cnt_cpt_r] == 'd31)
idelay_tap_limit_r <= #TCQ 1'b1;
//*****************************************************************
// keep track of edge tap counts found, and current capture clock
// tap count
//*****************************************************************
always @(posedge clk)
if (rst || new_cnt_cpt_r ||
(mpr_rdlvl_done_r1 && ~mpr_rdlvl_done_r2))
tap_cnt_cpt_r <= #TCQ 'b0;
else if (cal1_dlyce_cpt_r) begin
if (cal1_dlyinc_cpt_r)
tap_cnt_cpt_r <= #TCQ tap_cnt_cpt_r + 1;
else if (tap_cnt_cpt_r != 'd0)
tap_cnt_cpt_r <= #TCQ tap_cnt_cpt_r - 1;
end
always @(posedge clk)
if (rst || new_cnt_cpt_r ||
(cal1_state_r1 == CAL1_DQ_IDEL_TAP_INC) ||
(mpr_rdlvl_done_r1 && ~mpr_rdlvl_done_r2))
tap_limit_cpt_r <= #TCQ 1'b0;
else if (tap_cnt_cpt_r == 6'd63)
tap_limit_cpt_r <= #TCQ 1'b1;
always @(posedge clk)
cal1_cnt_cpt_timing_r <= #TCQ cal1_cnt_cpt_r;
assign cal1_cnt_cpt_timing = {2'b00, cal1_cnt_cpt_r};
// Storing DQS tap values at the end of each DQS read leveling
always @(posedge clk) begin
if (rst) begin
for (a = 0; a < RANKS; a = a + 1) begin: rst_rdlvl_dqs_tap_count_loop
for (b = 0; b < DQS_WIDTH; b = b + 1)
rdlvl_dqs_tap_cnt_r[a][b] <= #TCQ 'b0;
end
end else if ((SIM_CAL_OPTION == "FAST_CAL") & (cal1_state_r1 == CAL1_NEXT_DQS)) begin
for (p = 0; p < RANKS; p = p +1) begin: rdlvl_dqs_tap_rank_cnt
for(q = 0; q < DQS_WIDTH; q = q +1) begin: rdlvl_dqs_tap_cnt
rdlvl_dqs_tap_cnt_r[p][q] <= #TCQ tap_cnt_cpt_r;
end
end
end else if (SIM_CAL_OPTION == "SKIP_CAL") begin
for (j = 0; j < RANKS; j = j +1) begin: rdlvl_dqs_tap_rnk_cnt
for(i = 0; i < DQS_WIDTH; i = i +1) begin: rdlvl_dqs_cnt
rdlvl_dqs_tap_cnt_r[j][i] <= #TCQ 6'd31;
end
end
end else if (cal1_state_r1 == CAL1_NEXT_DQS) begin
rdlvl_dqs_tap_cnt_r[rnk_cnt_r][cal1_cnt_cpt_timing_r] <= #TCQ tap_cnt_cpt_r;
end
end
// Counter to track maximum DQ IODELAY tap usage during the per-bit
// deskew portion of stage 1 calibration
always @(posedge clk)
if (rst) begin
idel_tap_cnt_dq_pb_r <= #TCQ 'b0;
idel_tap_limit_dq_pb_r <= #TCQ 1'b0;
end else
if (new_cnt_cpt_r) begin
idel_tap_cnt_dq_pb_r <= #TCQ 'b0;
idel_tap_limit_dq_pb_r <= #TCQ 1'b0;
end else if (|cal1_dlyce_dq_r) begin
if (cal1_dlyinc_dq_r)
idel_tap_cnt_dq_pb_r <= #TCQ idel_tap_cnt_dq_pb_r + 1;
else
idel_tap_cnt_dq_pb_r <= #TCQ idel_tap_cnt_dq_pb_r - 1;
if (idel_tap_cnt_dq_pb_r == 31)
idel_tap_limit_dq_pb_r <= #TCQ 1'b1;
else
idel_tap_limit_dq_pb_r <= #TCQ 1'b0;
end
//*****************************************************************
always @(posedge clk)
cal1_state_r1 <= #TCQ cal1_state_r;
always @(posedge clk)
if (rst) begin
cal1_cnt_cpt_r <= #TCQ 'b0;
cal1_dlyce_cpt_r <= #TCQ 1'b0;
cal1_dlyinc_cpt_r <= #TCQ 1'b0;
cal1_dq_idel_ce <= #TCQ 1'b0;
cal1_dq_idel_inc <= #TCQ 1'b0;
cal1_prech_req_r <= #TCQ 1'b0;
cal1_state_r <= #TCQ CAL1_IDLE;
cnt_idel_dec_cpt_r <= #TCQ 6'bxxxxxx;
found_first_edge_r <= #TCQ 1'b0;
found_second_edge_r <= #TCQ 1'b0;
right_edge_taps_r <= #TCQ 6'bxxxxxx;
first_edge_taps_r <= #TCQ 6'bxxxxxx;
new_cnt_cpt_r <= #TCQ 1'b0;
rdlvl_stg1_done <= #TCQ 1'b0;
rdlvl_stg1_err <= #TCQ 1'b0;
second_edge_taps_r <= #TCQ 6'bxxxxxx;
store_sr_req_pulsed_r <= #TCQ 1'b0;
store_sr_req_r <= #TCQ 1'b0;
rnk_cnt_r <= #TCQ 2'b00;
rdlvl_rank_done_r <= #TCQ 1'b0;
idel_dec_cnt <= #TCQ 'd0;
rdlvl_last_byte_done <= #TCQ 1'b0;
idel_pat_detect_valid_r <= #TCQ 1'b0;
mpr_rank_done_r <= #TCQ 1'b0;
mpr_last_byte_done <= #TCQ 1'b0;
if (OCAL_EN == "ON")
mpr_rdlvl_done_r <= #TCQ 1'b0;
else
mpr_rdlvl_done_r <= #TCQ 1'b1;
mpr_dec_cpt_r <= #TCQ 1'b0;
end else begin
// default (inactive) states for all "pulse" outputs
cal1_prech_req_r <= #TCQ 1'b0;
cal1_dlyce_cpt_r <= #TCQ 1'b0;
cal1_dlyinc_cpt_r <= #TCQ 1'b0;
cal1_dq_idel_ce <= #TCQ 1'b0;
cal1_dq_idel_inc <= #TCQ 1'b0;
new_cnt_cpt_r <= #TCQ 1'b0;
store_sr_req_pulsed_r <= #TCQ 1'b0;
store_sr_req_r <= #TCQ 1'b0;
case (cal1_state_r)
CAL1_IDLE: begin
rdlvl_rank_done_r <= #TCQ 1'b0;
rdlvl_last_byte_done <= #TCQ 1'b0;
mpr_rank_done_r <= #TCQ 1'b0;
mpr_last_byte_done <= #TCQ 1'b0;
if (mpr_rdlvl_start && ~mpr_rdlvl_start_r) begin
cal1_state_r <= #TCQ CAL1_MPR_NEW_DQS_WAIT;
end else
if (rdlvl_stg1_start && ~rdlvl_stg1_start_r) begin
if (SIM_CAL_OPTION == "SKIP_CAL")
cal1_state_r <= #TCQ CAL1_REGL_LOAD;
else if (SIM_CAL_OPTION == "FAST_CAL")
cal1_state_r <= #TCQ CAL1_NEXT_DQS;
else begin
new_cnt_cpt_r <= #TCQ 1'b1;
cal1_state_r <= #TCQ CAL1_NEW_DQS_WAIT;
end
end
end
CAL1_MPR_NEW_DQS_WAIT: begin
cal1_prech_req_r <= #TCQ 1'b0;
if (!cal1_wait_r && mpr_valid_r)
cal1_state_r <= #TCQ CAL1_MPR_PAT_DETECT;
end
// Wait for the new DQS group to change
// also gives time for the read data IN_FIFO to
// output the updated data for the new DQS group
CAL1_NEW_DQS_WAIT: begin
rdlvl_rank_done_r <= #TCQ 1'b0;
rdlvl_last_byte_done <= #TCQ 1'b0;
mpr_rank_done_r <= #TCQ 1'b0;
mpr_last_byte_done <= #TCQ 1'b0;
cal1_prech_req_r <= #TCQ 1'b0;
if (|pi_counter_read_val) begin //VK_REVIEW
mpr_dec_cpt_r <= #TCQ 1'b1;
cal1_state_r <= #TCQ CAL1_IDEL_DEC_CPT;
cnt_idel_dec_cpt_r <= #TCQ pi_counter_read_val;
end else if (!cal1_wait_r) begin
//if (!cal1_wait_r) begin
// Store "previous tap" read data. Technically there is no
// "previous" read data, since we are starting a new DQS
// group, so we'll never find an edge at tap 0 unless the
// data is fluctuating/jittering
store_sr_req_r <= #TCQ 1'b1;
// If per-bit deskew is disabled, then skip the first
// portion of stage 1 calibration
if (PER_BIT_DESKEW == "OFF")
cal1_state_r <= #TCQ CAL1_STORE_FIRST_WAIT;
else if (PER_BIT_DESKEW == "ON")
cal1_state_r <= #TCQ CAL1_PB_STORE_FIRST_WAIT;
end
end
//*****************************************************************
// Per-bit deskew states
//*****************************************************************
// Wait state following storage of initial read data
CAL1_PB_STORE_FIRST_WAIT:
if (!cal1_wait_r)
cal1_state_r <= #TCQ CAL1_PB_DETECT_EDGE;
// Look for an edge on all DQ bits in current DQS group
CAL1_PB_DETECT_EDGE:
if (detect_edge_done_r) begin
if (found_stable_eye_r) begin
// If we've found the left edge for all bits (or more precisely,
// we've found the left edge, and then part of the stable
// window thereafter), then proceed to positioning the CPT clock
// right before the left margin
cnt_idel_dec_cpt_r <= #TCQ MIN_EYE_SIZE + 1;
cal1_state_r <= #TCQ CAL1_PB_DEC_CPT_LEFT;
end else begin
// If we've reached the end of the sampling time, and haven't
// yet found the left margin of all the DQ bits, then:
if (!tap_limit_cpt_r) begin
// If we still have taps left to use, then store current value
// of read data, increment the capture clock, and continue to
// look for (left) edges
store_sr_req_r <= #TCQ 1'b1;
cal1_state_r <= #TCQ CAL1_PB_INC_CPT;
end else begin
// If we ran out of taps moving the capture clock, and we
// haven't finished edge detection, then reset the capture
// clock taps to 0 (gradually, one tap at a time...
// then exit the per-bit portion of the algorithm -
// i.e. proceed to adjust the capture clock and DQ IODELAYs as
cnt_idel_dec_cpt_r <= #TCQ 6'd63;
cal1_state_r <= #TCQ CAL1_PB_DEC_CPT;
end
end
end
// Increment delay for DQS
CAL1_PB_INC_CPT: begin
cal1_dlyce_cpt_r <= #TCQ 1'b1;
cal1_dlyinc_cpt_r <= #TCQ 1'b1;
cal1_state_r <= #TCQ CAL1_PB_INC_CPT_WAIT;
end
// Wait for IODELAY for both capture and internal nodes within
// ISERDES to settle, before checking again for an edge
CAL1_PB_INC_CPT_WAIT: begin
cal1_dlyce_cpt_r <= #TCQ 1'b0;
cal1_dlyinc_cpt_r <= #TCQ 1'b0;
if (!cal1_wait_r)
cal1_state_r <= #TCQ CAL1_PB_DETECT_EDGE;
end
// We've found the left edges of the windows for all DQ bits
// (actually, we found it MIN_EYE_SIZE taps ago) Decrement capture
// clock IDELAY to position just outside left edge of data window
CAL1_PB_DEC_CPT_LEFT:
if (cnt_idel_dec_cpt_r == 6'b000000)
cal1_state_r <= #TCQ CAL1_PB_DEC_CPT_LEFT_WAIT;
else begin
cal1_dlyce_cpt_r <= #TCQ 1'b1;
cal1_dlyinc_cpt_r <= #TCQ 1'b0;
cnt_idel_dec_cpt_r <= #TCQ cnt_idel_dec_cpt_r - 1;
end
CAL1_PB_DEC_CPT_LEFT_WAIT:
if (!cal1_wait_r)
cal1_state_r <= #TCQ CAL1_PB_DETECT_EDGE_DQ;
// If there is skew between individual DQ bits, then after we've
// positioned the CPT clock, we will be "in the window" for some
// DQ bits ("early" DQ bits), and "out of the window" for others
// ("late" DQ bits). Increase DQ taps until we are out of the
// window for all DQ bits
CAL1_PB_DETECT_EDGE_DQ:
if (detect_edge_done_r)
if (found_edge_all_r) begin
// We're out of the window for all DQ bits in this DQS group
// We're done with per-bit deskew for this group - now decr
// capture clock IODELAY tap count back to 0, and proceed
// with the rest of stage 1 calibration for this DQS group
cnt_idel_dec_cpt_r <= #TCQ tap_cnt_cpt_r;
cal1_state_r <= #TCQ CAL1_PB_DEC_CPT;
end else
if (!idel_tap_limit_dq_pb_r)
// If we still have DQ taps available for deskew, keep
// incrementing IODELAY tap count for the appropriate DQ bits
cal1_state_r <= #TCQ CAL1_PB_INC_DQ;
else begin
// Otherwise, stop immediately (we've done the best we can)
// and proceed with rest of stage 1 calibration
cnt_idel_dec_cpt_r <= #TCQ tap_cnt_cpt_r;
cal1_state_r <= #TCQ CAL1_PB_DEC_CPT;
end
CAL1_PB_INC_DQ: begin
// Increment only those DQ for which an edge hasn't been found yet
cal1_dlyce_dq_r <= #TCQ ~pb_found_edge_last_r;
cal1_dlyinc_dq_r <= #TCQ 1'b1;
cal1_state_r <= #TCQ CAL1_PB_INC_DQ_WAIT;
end
CAL1_PB_INC_DQ_WAIT:
if (!cal1_wait_r)
cal1_state_r <= #TCQ CAL1_PB_DETECT_EDGE_DQ;
// Decrement capture clock taps back to initial value
CAL1_PB_DEC_CPT:
if (cnt_idel_dec_cpt_r == 6'b000000)
cal1_state_r <= #TCQ CAL1_PB_DEC_CPT_WAIT;
else begin
cal1_dlyce_cpt_r <= #TCQ 1'b1;
cal1_dlyinc_cpt_r <= #TCQ 1'b0;
cnt_idel_dec_cpt_r <= #TCQ cnt_idel_dec_cpt_r - 1;
end
// Wait for capture clock to settle, then proceed to rest of
// state 1 calibration for this DQS group
CAL1_PB_DEC_CPT_WAIT:
if (!cal1_wait_r) begin
store_sr_req_r <= #TCQ 1'b1;
cal1_state_r <= #TCQ CAL1_STORE_FIRST_WAIT;
end
// When first starting calibration for a DQS group, save the
// current value of the read data shift register, and use this
// as a reference. Note that for the first iteration of the
// edge detection loop, we will in effect be checking for an edge
// at IODELAY taps = 0 - normally, we are comparing the read data
// for IODELAY taps = N, with the read data for IODELAY taps = N-1
// An edge can only be found at IODELAY taps = 0 if the read data
// is changing during this time (possible due to jitter)
CAL1_STORE_FIRST_WAIT: begin
mpr_dec_cpt_r <= #TCQ 1'b0;
if (!cal1_wait_r)
cal1_state_r <= #TCQ CAL1_PAT_DETECT;
end
CAL1_VALID_WAIT: begin
if (!cal1_wait_r)
cal1_state_r <= #TCQ CAL1_MPR_PAT_DETECT;
end
CAL1_MPR_PAT_DETECT: begin
// MPR read leveling for centering DQS in valid window before
// OCLKDELAYED calibration begins in order to eliminate read issues
if (idel_pat_detect_valid_r == 1'b0) begin
cal1_state_r <= #TCQ CAL1_VALID_WAIT;
idel_pat_detect_valid_r <= #TCQ 1'b1;
end else if (idel_pat_detect_valid_r && idel_mpr_pat_detect_r) begin
cal1_state_r <= #TCQ CAL1_DETECT_EDGE;
idel_dec_cnt <= #TCQ 'd0;
end else if (!idelay_tap_limit_r)
cal1_state_r <= #TCQ CAL1_DQ_IDEL_TAP_INC;
else
cal1_state_r <= #TCQ CAL1_RDLVL_ERR;
end
CAL1_PAT_DETECT: begin
// All DQ bits associated with a DQS are pushed to the right one IDELAY
// tap at a time until first rising DQS is in the tri-state region
// before first rising edge window.
// The detect_edge_done_r condition included to support averaging
// during IDELAY tap increments
if (detect_edge_done_r) begin
if (idel_pat_data_match) begin
cal1_state_r <= #TCQ CAL1_DETECT_EDGE;
idel_dec_cnt <= #TCQ 'd0;
end else if (!idelay_tap_limit_r) begin
cal1_state_r <= #TCQ CAL1_DQ_IDEL_TAP_INC;
end else begin
cal1_state_r <= #TCQ CAL1_RDLVL_ERR;
end
end
end
// Increment IDELAY tap by 1 for DQ bits in the byte being calibrated
// until left edge of valid window detected
CAL1_DQ_IDEL_TAP_INC: begin
cal1_dq_idel_ce <= #TCQ 1'b1;
cal1_dq_idel_inc <= #TCQ 1'b1;
cal1_state_r <= #TCQ CAL1_DQ_IDEL_TAP_INC_WAIT;
idel_pat_detect_valid_r <= #TCQ 1'b0;
end
CAL1_DQ_IDEL_TAP_INC_WAIT: begin
cal1_dq_idel_ce <= #TCQ 1'b0;
cal1_dq_idel_inc <= #TCQ 1'b0;
if (!cal1_wait_r) begin
if (~mpr_rdlvl_done_r & (DRAM_TYPE == "DDR3"))
cal1_state_r <= #TCQ CAL1_MPR_PAT_DETECT;
else
cal1_state_r <= #TCQ CAL1_PAT_DETECT;
end
end
// Decrement by 2 IDELAY taps once idel_pat_data_match detected
CAL1_DQ_IDEL_TAP_DEC: begin
cal1_dq_idel_inc <= #TCQ 1'b0;
cal1_state_r <= #TCQ CAL1_DQ_IDEL_TAP_DEC_WAIT;
if (idel_dec_cnt >= 'd0)
cal1_dq_idel_ce <= #TCQ 1'b1;
else
cal1_dq_idel_ce <= #TCQ 1'b0;
if (idel_dec_cnt > 'd0)
idel_dec_cnt <= #TCQ idel_dec_cnt - 1;
else
idel_dec_cnt <= #TCQ idel_dec_cnt;
end
CAL1_DQ_IDEL_TAP_DEC_WAIT: begin
cal1_dq_idel_ce <= #TCQ 1'b0;
cal1_dq_idel_inc <= #TCQ 1'b0;
if (!cal1_wait_r) begin
if ((idel_dec_cnt > 'd0) || (pi_rdval_cnt > 'd0))
cal1_state_r <= #TCQ CAL1_DQ_IDEL_TAP_DEC;
else if (mpr_dec_cpt_r)
cal1_state_r <= #TCQ CAL1_STORE_FIRST_WAIT;
else
cal1_state_r <= #TCQ CAL1_DETECT_EDGE;
end
end
// Check for presence of data eye edge. During this state, we
// sample the read data multiple times, and look for changes
// in the read data, specifically:
// 1. A change in the read data compared with the value of
// read data from the previous delay tap. This indicates
// that the most recent tap delay increment has moved us
// into either a new window, or moved/kept us in the
// transition/jitter region between windows. Note that this
// condition only needs to be checked for once, and for
// logistical purposes, we check this soon after entering
// this state (see comment in CAL1_DETECT_EDGE below for
// why this is done)
// 2. A change in the read data while we are in this state
// (i.e. in the absence of a tap delay increment). This
// indicates that we're close enough to a window edge that
// jitter will cause the read data to change even in the
// absence of a tap delay change
CAL1_DETECT_EDGE: begin
// Essentially wait for the first comparision to finish, then
// store current data into "old" data register. This store
// happens now, rather than later (e.g. when we've have already
// left this state) in order to avoid the situation the data that
// is stored as "old" data has not been used in an "active
// comparison" - i.e. data is stored after the last comparison
// of this state. In this case, we can miss an edge if the
// following sequence occurs:
// 1. Comparison completes in this state - no edge found
// 2. "Momentary jitter" occurs which "pushes" the data out the
// equivalent of one delay tap
// 3. We store this jittered data as the "old" data
// 4. "Jitter" no longer present
// 5. We increment the delay tap by one
// 6. Now we compare the current with the "old" data - they're
// the same, and no edge is detected
// NOTE: Given the large # of comparisons done in this state, it's
// highly unlikely the above sequence will occur in actual H/W
// Wait for the first load of read data into the comparison
// shift register to finish, then load the current read data
// into the "old" data register. This allows us to do one
// initial comparision between the current read data, and
// stored data corresponding to the previous delay tap
idel_pat_detect_valid_r <= #TCQ 1'b0;
if (!store_sr_req_pulsed_r) begin
// Pulse store_sr_req_r only once in this state
store_sr_req_r <= #TCQ 1'b1;
store_sr_req_pulsed_r <= #TCQ 1'b1;
end else begin
store_sr_req_r <= #TCQ 1'b0;
store_sr_req_pulsed_r <= #TCQ 1'b1;
end
// Continue to sample read data and look for edges until the
// appropriate time interval (shorter for simulation-only,
// much, much longer for actual h/w) has elapsed
if (detect_edge_done_r) begin
if (tap_limit_cpt_r)
// Only one edge detected and ran out of taps since only one
// bit time worth of taps available for window detection. This
// can happen if at tap 0 DQS is in previous window which results
// in only left edge being detected. Or at tap 0 DQS is in the
// current window resulting in only right edge being detected.
// Depending on the frequency this case can also happen if at
// tap 0 DQS is in the left noise region resulting in only left
// edge being detected.
cal1_state_r <= #TCQ CAL1_CALC_IDEL;
else if (found_edge_r) begin
// Sticky bit - asserted after we encounter an edge, although
// the current edge may not be considered the "first edge" this
// just means we found at least one edge
found_first_edge_r <= #TCQ 1'b1;
// Only the right edge of the data valid window is found
// Record the inner right edge tap value
if (!found_first_edge_r && found_stable_eye_last_r) begin
if (tap_cnt_cpt_r == 'd0)
right_edge_taps_r <= #TCQ 'd0;
else
right_edge_taps_r <= #TCQ tap_cnt_cpt_r;
end
// Both edges of data valid window found:
// If we've found a second edge after a region of stability
// then we must have just passed the second ("right" edge of
// the window. Record this second_edge_taps = current tap-1,
// because we're one past the actual second edge tap, where
// the edge taps represent the extremes of the data valid
// window (i.e. smallest & largest taps where data still valid
if (found_first_edge_r && found_stable_eye_last_r) begin
found_second_edge_r <= #TCQ 1'b1;
second_edge_taps_r <= #TCQ tap_cnt_cpt_r - 1;
cal1_state_r <= #TCQ CAL1_CALC_IDEL;
end else begin
// Otherwise, an edge was found (just not the "second" edge)
// Assuming DQS is in the correct window at tap 0 of Phaser IN
// fine tap. The first edge found is the right edge of the valid
// window and is the beginning of the jitter region hence done!
first_edge_taps_r <= #TCQ tap_cnt_cpt_r;
cal1_state_r <= #TCQ CAL1_IDEL_INC_CPT;
end
end else
// Otherwise, if we haven't found an edge....
// If we still have taps left to use, then keep incrementing
cal1_state_r <= #TCQ CAL1_IDEL_INC_CPT;
end
end
// Increment Phaser_IN delay for DQS
CAL1_IDEL_INC_CPT: begin
cal1_state_r <= #TCQ CAL1_IDEL_INC_CPT_WAIT;
if (~tap_limit_cpt_r) begin
cal1_dlyce_cpt_r <= #TCQ 1'b1;
cal1_dlyinc_cpt_r <= #TCQ 1'b1;
end else begin
cal1_dlyce_cpt_r <= #TCQ 1'b0;
cal1_dlyinc_cpt_r <= #TCQ 1'b0;
end
end
// Wait for Phaser_In to settle, before checking again for an edge
CAL1_IDEL_INC_CPT_WAIT: begin
cal1_dlyce_cpt_r <= #TCQ 1'b0;
cal1_dlyinc_cpt_r <= #TCQ 1'b0;
if (!cal1_wait_r)
cal1_state_r <= #TCQ CAL1_DETECT_EDGE;
end
// Calculate final value of Phaser_IN taps. At this point, one or both
// edges of data eye have been found, and/or all taps have been
// exhausted looking for the edges
// NOTE: We're calculating the amount to decrement by, not the
// absolute setting for DQS.
CAL1_CALC_IDEL: begin
// CASE1: If 2 edges found.
if (found_second_edge_r)
cnt_idel_dec_cpt_r
<= #TCQ ((second_edge_taps_r -
first_edge_taps_r)>>1) + 1;
else if (right_edge_taps_r > 6'd0)
// Only right edge detected
// right_edge_taps_r is the inner right edge tap value
// hence used for calculation
cnt_idel_dec_cpt_r
<= #TCQ (tap_cnt_cpt_r - (right_edge_taps_r>>1));
else if (found_first_edge_r)
// Only left edge detected
cnt_idel_dec_cpt_r
<= #TCQ ((tap_cnt_cpt_r - first_edge_taps_r)>>1);
else
cnt_idel_dec_cpt_r
<= #TCQ (tap_cnt_cpt_r>>1);
// Now use the value we just calculated to decrement CPT taps
// to the desired calibration point
cal1_state_r <= #TCQ CAL1_IDEL_DEC_CPT;
end
// decrement capture clock for final adjustment - center
// capture clock in middle of data eye. This adjustment will occur
// only when both the edges are found usign CPT taps. Must do this
// incrementally to avoid clock glitching (since CPT drives clock
// divider within each ISERDES)
CAL1_IDEL_DEC_CPT: begin
cal1_dlyce_cpt_r <= #TCQ 1'b1;
cal1_dlyinc_cpt_r <= #TCQ 1'b0;
// once adjustment is complete, we're done with calibration for
// this DQS, repeat for next DQS
cnt_idel_dec_cpt_r <= #TCQ cnt_idel_dec_cpt_r - 1;
if (cnt_idel_dec_cpt_r == 6'b000001) begin
if (mpr_dec_cpt_r) begin
if (|idelay_tap_cnt_r[rnk_cnt_r][cal1_cnt_cpt_timing]) begin
idel_dec_cnt <= #TCQ idelay_tap_cnt_r[rnk_cnt_r][cal1_cnt_cpt_timing];
cal1_state_r <= #TCQ CAL1_DQ_IDEL_TAP_DEC;
end else
cal1_state_r <= #TCQ CAL1_STORE_FIRST_WAIT;
end else
cal1_state_r <= #TCQ CAL1_NEXT_DQS;
end else
cal1_state_r <= #TCQ CAL1_IDEL_DEC_CPT_WAIT;
end
CAL1_IDEL_DEC_CPT_WAIT: begin
cal1_dlyce_cpt_r <= #TCQ 1'b0;
cal1_dlyinc_cpt_r <= #TCQ 1'b0;
if (!cal1_wait_r)
cal1_state_r <= #TCQ CAL1_IDEL_DEC_CPT;
end
// Determine whether we're done, or have more DQS's to calibrate
// Also request precharge after every byte, as appropriate
CAL1_NEXT_DQS: begin
//if (mpr_rdlvl_done_r || (DRAM_TYPE == "DDR2"))
cal1_prech_req_r <= #TCQ 1'b1;
//else
// cal1_prech_req_r <= #TCQ 1'b0;
cal1_dlyce_cpt_r <= #TCQ 1'b0;
cal1_dlyinc_cpt_r <= #TCQ 1'b0;
// Prepare for another iteration with next DQS group
found_first_edge_r <= #TCQ 1'b0;
found_second_edge_r <= #TCQ 1'b0;
first_edge_taps_r <= #TCQ 'd0;
second_edge_taps_r <= #TCQ 'd0;
if ((SIM_CAL_OPTION == "FAST_CAL") ||
(cal1_cnt_cpt_r >= DQS_WIDTH-1)) begin
if (mpr_rdlvl_done_r) begin
rdlvl_last_byte_done <= #TCQ 1'b1;
mpr_last_byte_done <= #TCQ 1'b0;
end else begin
rdlvl_last_byte_done <= #TCQ 1'b0;
mpr_last_byte_done <= #TCQ 1'b1;
end
end
// Wait until precharge that occurs in between calibration of
// DQS groups is finished
if (prech_done) begin // || (~mpr_rdlvl_done_r & (DRAM_TYPE == "DDR3"))) begin
if (SIM_CAL_OPTION == "FAST_CAL") begin
//rdlvl_rank_done_r <= #TCQ 1'b1;
rdlvl_last_byte_done <= #TCQ 1'b0;
mpr_last_byte_done <= #TCQ 1'b0;
cal1_state_r <= #TCQ CAL1_DONE; //CAL1_REGL_LOAD;
end else if (cal1_cnt_cpt_r >= DQS_WIDTH-1) begin
if (~mpr_rdlvl_done_r) begin
mpr_rank_done_r <= #TCQ 1'b1;
// if (rnk_cnt_r == RANKS-1) begin
// All DQS groups in all ranks done
cal1_state_r <= #TCQ CAL1_DONE;
cal1_cnt_cpt_r <= #TCQ 'b0;
// end else begin
// // Process DQS groups in next rank
// rnk_cnt_r <= #TCQ rnk_cnt_r + 1;
// new_cnt_cpt_r <= #TCQ 1'b1;
// cal1_cnt_cpt_r <= #TCQ 'b0;
// cal1_state_r <= #TCQ CAL1_IDLE;
// end
end else begin
// All DQS groups in a rank done
rdlvl_rank_done_r <= #TCQ 1'b1;
if (rnk_cnt_r == RANKS-1) begin
// All DQS groups in all ranks done
cal1_state_r <= #TCQ CAL1_REGL_LOAD;
end else begin
// Process DQS groups in next rank
rnk_cnt_r <= #TCQ rnk_cnt_r + 1;
new_cnt_cpt_r <= #TCQ 1'b1;
cal1_cnt_cpt_r <= #TCQ 'b0;
cal1_state_r <= #TCQ CAL1_IDLE;
end
end
end else begin
// Process next DQS group
new_cnt_cpt_r <= #TCQ 1'b1;
cal1_cnt_cpt_r <= #TCQ cal1_cnt_cpt_r + 1;
cal1_state_r <= #TCQ CAL1_NEW_DQS_PREWAIT;
end
end
end
CAL1_NEW_DQS_PREWAIT: begin
if (!cal1_wait_r) begin
if (~mpr_rdlvl_done_r & (DRAM_TYPE == "DDR3"))
cal1_state_r <= #TCQ CAL1_MPR_NEW_DQS_WAIT;
else
cal1_state_r <= #TCQ CAL1_NEW_DQS_WAIT;
end
end
// Load rank registers in Phaser_IN
CAL1_REGL_LOAD: begin
rdlvl_rank_done_r <= #TCQ 1'b0;
mpr_rank_done_r <= #TCQ 1'b0;
cal1_prech_req_r <= #TCQ 1'b0;
cal1_cnt_cpt_r <= #TCQ 'b0;
rnk_cnt_r <= #TCQ 2'b00;
if ((regl_rank_cnt == RANKS-1) &&
((regl_dqs_cnt == DQS_WIDTH-1) && (done_cnt == 4'd1))) begin
cal1_state_r <= #TCQ CAL1_DONE;
rdlvl_last_byte_done <= #TCQ 1'b0;
mpr_last_byte_done <= #TCQ 1'b0;
end else
cal1_state_r <= #TCQ CAL1_REGL_LOAD;
end
CAL1_RDLVL_ERR: begin
rdlvl_stg1_err <= #TCQ 1'b1;
end
// Done with this stage of calibration
// if used, allow DEBUG_PORT to control taps
CAL1_DONE: begin
mpr_rdlvl_done_r <= #TCQ 1'b1;
cal1_prech_req_r <= #TCQ 1'b0;
if (~mpr_rdlvl_done_r && (OCAL_EN=="ON") && (DRAM_TYPE == "DDR3")) begin
rdlvl_stg1_done <= #TCQ 1'b0;
cal1_state_r <= #TCQ CAL1_IDLE;
end else
rdlvl_stg1_done <= #TCQ 1'b1;
end
endcase
end
endmodule
|
//*****************************************************************************
// (c) Copyright 2008 - 2013 Xilinx, Inc. All rights reserved.
//
// This file contains confidential and proprietary information
// of Xilinx, Inc. and is protected under U.S. and
// international copyright and other intellectual property
// laws.
//
// DISCLAIMER
// This disclaimer is not a license and does not grant any
// rights to the materials distributed herewith. Except as
// otherwise provided in a valid license issued to you by
// Xilinx, and to the maximum extent permitted by applicable
// law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND
// WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES
// AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
// BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-
// INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and
// (2) Xilinx shall not be liable (whether in contract or tort,
// including negligence, or under any other theory of
// liability) for any loss or damage of any kind or nature
// related to, arising under or in connection with these
// materials, including for any direct, or any indirect,
// special, incidental, or consequential loss or damage
// (including loss of data, profits, goodwill, or any type of
// loss or damage suffered as a result of any action brought
// by a third party) even if such damage or loss was
// reasonably foreseeable or Xilinx had been advised of the
// possibility of the same.
//
// CRITICAL APPLICATIONS
// Xilinx products are not designed or intended to be fail-
// safe, or for use in any application requiring fail-safe
// performance, such as life-support or safety devices or
// systems, Class III medical devices, nuclear facilities,
// applications related to the deployment of airbags, or any
// other applications that could lead to death, personal
// injury, or severe property or environmental damage
// (individually and collectively, "Critical
// Applications"). Customer assumes the sole risk and
// liability of any use of Xilinx products in Critical
// Applications, subject only to applicable laws and
// regulations governing limitations on product liability.
//
// THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS
// PART OF THIS FILE AT ALL TIMES.
//
//*****************************************************************************
// ____ ____
// / /\/ /
// /___/ \ / Vendor : Xilinx
// \ \ \/ Version : %version
// \ \ Application : MIG
// / / Filename : arb_mux.v
// /___/ /\ Date Last Modified : $date$
// \ \ / \ Date Created : Tue Jun 30 2009
// \___\/\___\
//
//Device : 7-Series
//Design Name : DDR3 SDRAM
//Purpose :
//Reference :
//Revision History :
//*****************************************************************************
`timescale 1ps/1ps
module mig_7series_v1_9_arb_mux #
(
parameter TCQ = 100,
parameter EVEN_CWL_2T_MODE = "OFF",
parameter ADDR_CMD_MODE = "1T",
parameter BANK_VECT_INDX = 11,
parameter BANK_WIDTH = 3,
parameter BURST_MODE = "8",
parameter CS_WIDTH = 4,
parameter CL = 5,
parameter CWL = 5,
parameter DATA_BUF_ADDR_VECT_INDX = 31,
parameter DATA_BUF_ADDR_WIDTH = 8,
parameter DRAM_TYPE = "DDR3",
parameter CKE_ODT_AUX = "FALSE", //Parameter to turn on/off the aux_out signal
parameter EARLY_WR_DATA_ADDR = "OFF",
parameter ECC = "OFF",
parameter nBANK_MACHS = 4,
parameter nCK_PER_CLK = 2, // # DRAM CKs per fabric CLKs
parameter nCS_PER_RANK = 1,
parameter nRAS = 37500, // ACT->PRE cmd period (CKs)
parameter nRCD = 12500, // ACT->R/W delay (CKs)
parameter nSLOTS = 2,
parameter nWR = 6, // Write recovery (CKs)
parameter RANKS = 1,
parameter RANK_VECT_INDX = 15,
parameter RANK_WIDTH = 2,
parameter ROW_VECT_INDX = 63,
parameter ROW_WIDTH = 16,
parameter RTT_NOM = "40",
parameter RTT_WR = "120",
parameter SLOT_0_CONFIG = 8'b0000_0101,
parameter SLOT_1_CONFIG = 8'b0000_1010
)
(/*AUTOARG*/
// Outputs
output [ROW_WIDTH-1:0] col_a, // From arb_select0 of arb_select.v
output [BANK_WIDTH-1:0] col_ba, // From arb_select0 of arb_select.v
output [DATA_BUF_ADDR_WIDTH-1:0] col_data_buf_addr,// From arb_select0 of arb_select.v
output col_periodic_rd, // From arb_select0 of arb_select.v
output [RANK_WIDTH-1:0] col_ra, // From arb_select0 of arb_select.v
output col_rmw, // From arb_select0 of arb_select.v
output col_rd_wr,
output [ROW_WIDTH-1:0] col_row, // From arb_select0 of arb_select.v
output col_size, // From arb_select0 of arb_select.v
output [DATA_BUF_ADDR_WIDTH-1:0] col_wr_data_buf_addr,// From arb_select0 of arb_select.v
output wire [nCK_PER_CLK-1:0] mc_ras_n,
output wire [nCK_PER_CLK-1:0] mc_cas_n,
output wire [nCK_PER_CLK-1:0] mc_we_n,
output wire [nCK_PER_CLK*ROW_WIDTH-1:0] mc_address,
output wire [nCK_PER_CLK*BANK_WIDTH-1:0] mc_bank,
output wire [CS_WIDTH*nCS_PER_RANK*nCK_PER_CLK-1:0] mc_cs_n,
output wire [1:0] mc_odt,
output wire [nCK_PER_CLK-1:0] mc_cke,
output wire [3:0] mc_aux_out0,
output wire [3:0] mc_aux_out1,
output [2:0] mc_cmd,
output [5:0] mc_data_offset,
output [5:0] mc_data_offset_1,
output [5:0] mc_data_offset_2,
output [1:0] mc_cas_slot,
output [RANK_WIDTH-1:0] rnk_config, // From arb_select0 of arb_select.v
output rnk_config_valid_r, // From arb_row_col0 of arb_row_col.v
output [nBANK_MACHS-1:0] sending_row, // From arb_row_col0 of arb_row_col.v
output [nBANK_MACHS-1:0] sending_pre,
output sent_col, // From arb_row_col0 of arb_row_col.v
output sent_col_r, // From arb_row_col0 of arb_row_col.v
output sent_row, // From arb_row_col0 of arb_row_col.v
output [nBANK_MACHS-1:0] sending_col,
output rnk_config_strobe,
output insert_maint_r1,
output rnk_config_kill_rts_col,
// Inputs
input clk,
input rst,
input init_calib_complete,
input [6*RANKS-1:0] calib_rddata_offset,
input [6*RANKS-1:0] calib_rddata_offset_1,
input [6*RANKS-1:0] calib_rddata_offset_2,
input [ROW_VECT_INDX:0] col_addr, // To arb_select0 of arb_select.v
input [nBANK_MACHS-1:0] col_rdy_wr, // To arb_row_col0 of arb_row_col.v
input insert_maint_r, // To arb_row_col0 of arb_row_col.v
input [RANK_WIDTH-1:0] maint_rank_r, // To arb_select0 of arb_select.v
input maint_zq_r, // To arb_select0 of arb_select.v
input maint_sre_r, // To arb_select0 of arb_select.v
input maint_srx_r, // To arb_select0 of arb_select.v
input [nBANK_MACHS-1:0] rd_wr_r, // To arb_select0 of arb_select.v
input [BANK_VECT_INDX:0] req_bank_r, // To arb_select0 of arb_select.v
input [nBANK_MACHS-1:0] req_cas, // To arb_select0 of arb_select.v
input [DATA_BUF_ADDR_VECT_INDX:0] req_data_buf_addr_r,// To arb_select0 of arb_select.v
input [nBANK_MACHS-1:0] req_periodic_rd_r, // To arb_select0 of arb_select.v
input [RANK_VECT_INDX:0] req_rank_r, // To arb_select0 of arb_select.v
input [nBANK_MACHS-1:0] req_ras, // To arb_select0 of arb_select.v
input [ROW_VECT_INDX:0] req_row_r, // To arb_select0 of arb_select.v
input [nBANK_MACHS-1:0] req_size_r, // To arb_select0 of arb_select.v
input [nBANK_MACHS-1:0] req_wr_r, // To arb_select0 of arb_select.v
input [ROW_VECT_INDX:0] row_addr, // To arb_select0 of arb_select.v
input [nBANK_MACHS-1:0] row_cmd_wr, // To arb_select0 of arb_select.v
input [nBANK_MACHS-1:0] rtc, // To arb_row_col0 of arb_row_col.v
input [nBANK_MACHS-1:0] rts_col, // To arb_row_col0 of arb_row_col.v
input [nBANK_MACHS-1:0] rts_row, // To arb_row_col0 of arb_row_col.v
input [nBANK_MACHS-1:0] rts_pre, // To arb_row_col0 of arb_row_col.v
input [7:0] slot_0_present, // To arb_select0 of arb_select.v
input [7:0] slot_1_present // To arb_select0 of arb_select.v
);
/*AUTOINPUT*/
// Beginning of automatic inputs (from unused autoinst inputs)
// End of automatics
/*AUTOOUTPUT*/
// Beginning of automatic outputs (from unused autoinst outputs)
// End of automatics
/*AUTOWIRE*/
// Beginning of automatic wires (for undeclared instantiated-module outputs)
wire cs_en0; // From arb_row_col0 of arb_row_col.v
wire cs_en1; // From arb_row_col0 of arb_row_col.v
wire [nBANK_MACHS-1:0] grant_col_r; // From arb_row_col0 of arb_row_col.v
wire [nBANK_MACHS-1:0] grant_col_wr; // From arb_row_col0 of arb_row_col.v
wire [nBANK_MACHS-1:0] grant_config_r; // From arb_row_col0 of arb_row_col.v
wire [nBANK_MACHS-1:0] grant_row_r; // From arb_row_col0 of arb_row_col.v
wire [nBANK_MACHS-1:0] grant_pre_r; // From arb_row_col0 of arb_row_col.v
wire send_cmd0_row; // From arb_row_col0 of arb_row_col.v
wire send_cmd0_col; // From arb_row_col0 of arb_row_col.v
wire send_cmd1_row; // From arb_row_col0 of arb_row_col.v
wire send_cmd1_col;
wire send_cmd2_row;
wire send_cmd2_col;
wire send_cmd2_pre;
wire send_cmd3_col;
wire [5:0] col_channel_offset;
// End of automatics
wire sent_col_i;
assign sent_col = sent_col_i;
mig_7series_v1_9_arb_row_col #
(/*AUTOINSTPARAM*/
// Parameters
.TCQ (TCQ),
.ADDR_CMD_MODE (ADDR_CMD_MODE),
.CWL (CWL),
.EARLY_WR_DATA_ADDR (EARLY_WR_DATA_ADDR),
.nBANK_MACHS (nBANK_MACHS),
.nCK_PER_CLK (nCK_PER_CLK),
.nRAS (nRAS),
.nRCD (nRCD),
.nWR (nWR))
arb_row_col0
(/*AUTOINST*/
// Outputs
.grant_row_r (grant_row_r[nBANK_MACHS-1:0]),
.grant_pre_r (grant_pre_r[nBANK_MACHS-1:0]),
.sent_row (sent_row),
.sending_row (sending_row[nBANK_MACHS-1:0]),
.sending_pre (sending_pre[nBANK_MACHS-1:0]),
.grant_config_r (grant_config_r[nBANK_MACHS-1:0]),
.rnk_config_strobe (rnk_config_strobe),
.rnk_config_kill_rts_col (rnk_config_kill_rts_col),
.rnk_config_valid_r (rnk_config_valid_r),
.grant_col_r (grant_col_r[nBANK_MACHS-1:0]),
.sending_col (sending_col[nBANK_MACHS-1:0]),
.sent_col (sent_col_i),
.sent_col_r (sent_col_r),
.grant_col_wr (grant_col_wr[nBANK_MACHS-1:0]),
.send_cmd0_row (send_cmd0_row),
.send_cmd0_col (send_cmd0_col),
.send_cmd1_row (send_cmd1_row),
.send_cmd1_col (send_cmd1_col),
.send_cmd2_row (send_cmd2_row),
.send_cmd2_col (send_cmd2_col),
.send_cmd2_pre (send_cmd2_pre),
.send_cmd3_col (send_cmd3_col),
.col_channel_offset (col_channel_offset),
.cs_en0 (cs_en0),
.cs_en1 (cs_en1),
.cs_en2 (cs_en2),
.cs_en3 (cs_en3),
.insert_maint_r1 (insert_maint_r1),
// Inputs
.clk (clk),
.rst (rst),
.rts_row (rts_row[nBANK_MACHS-1:0]),
.rts_pre (rts_pre[nBANK_MACHS-1:0]),
.insert_maint_r (insert_maint_r),
.rts_col (rts_col[nBANK_MACHS-1:0]),
.rtc (rtc[nBANK_MACHS-1:0]),
.col_rdy_wr (col_rdy_wr[nBANK_MACHS-1:0]));
mig_7series_v1_9_arb_select #
(/*AUTOINSTPARAM*/
// Parameters
.TCQ (TCQ),
.EVEN_CWL_2T_MODE (EVEN_CWL_2T_MODE),
.ADDR_CMD_MODE (ADDR_CMD_MODE),
.BANK_VECT_INDX (BANK_VECT_INDX),
.BANK_WIDTH (BANK_WIDTH),
.BURST_MODE (BURST_MODE),
.CS_WIDTH (CS_WIDTH),
.CL (CL),
.CWL (CWL),
.DATA_BUF_ADDR_VECT_INDX (DATA_BUF_ADDR_VECT_INDX),
.DATA_BUF_ADDR_WIDTH (DATA_BUF_ADDR_WIDTH),
.DRAM_TYPE (DRAM_TYPE),
.EARLY_WR_DATA_ADDR (EARLY_WR_DATA_ADDR),
.ECC (ECC),
.CKE_ODT_AUX (CKE_ODT_AUX),
.nBANK_MACHS (nBANK_MACHS),
.nCK_PER_CLK (nCK_PER_CLK),
.nCS_PER_RANK (nCS_PER_RANK),
.nSLOTS (nSLOTS),
.RANKS (RANKS),
.RANK_VECT_INDX (RANK_VECT_INDX),
.RANK_WIDTH (RANK_WIDTH),
.ROW_VECT_INDX (ROW_VECT_INDX),
.ROW_WIDTH (ROW_WIDTH),
.RTT_NOM (RTT_NOM),
.RTT_WR (RTT_WR),
.SLOT_0_CONFIG (SLOT_0_CONFIG),
.SLOT_1_CONFIG (SLOT_1_CONFIG))
arb_select0
(/*AUTOINST*/
// Outputs
.col_periodic_rd (col_periodic_rd),
.col_ra (col_ra[RANK_WIDTH-1:0]),
.col_ba (col_ba[BANK_WIDTH-1:0]),
.col_a (col_a[ROW_WIDTH-1:0]),
.col_rmw (col_rmw),
.col_rd_wr (col_rd_wr),
.col_size (col_size),
.col_row (col_row[ROW_WIDTH-1:0]),
.col_data_buf_addr (col_data_buf_addr[DATA_BUF_ADDR_WIDTH-1:0]),
.col_wr_data_buf_addr (col_wr_data_buf_addr[DATA_BUF_ADDR_WIDTH-1:0]),
.mc_bank (mc_bank),
.mc_address (mc_address),
.mc_ras_n (mc_ras_n),
.mc_cas_n (mc_cas_n),
.mc_we_n (mc_we_n),
.mc_cs_n (mc_cs_n),
.mc_odt (mc_odt),
.mc_cke (mc_cke),
.mc_aux_out0 (mc_aux_out0),
.mc_aux_out1 (mc_aux_out1),
.mc_cmd (mc_cmd),
.mc_data_offset (mc_data_offset),
.mc_data_offset_1 (mc_data_offset_1),
.mc_data_offset_2 (mc_data_offset_2),
.mc_cas_slot (mc_cas_slot),
.col_channel_offset (col_channel_offset),
.rnk_config (rnk_config),
// Inputs
.clk (clk),
.rst (rst),
.init_calib_complete (init_calib_complete),
.calib_rddata_offset (calib_rddata_offset),
.calib_rddata_offset_1 (calib_rddata_offset_1),
.calib_rddata_offset_2 (calib_rddata_offset_2),
.req_rank_r (req_rank_r[RANK_VECT_INDX:0]),
.req_bank_r (req_bank_r[BANK_VECT_INDX:0]),
.req_ras (req_ras[nBANK_MACHS-1:0]),
.req_cas (req_cas[nBANK_MACHS-1:0]),
.req_wr_r (req_wr_r[nBANK_MACHS-1:0]),
.grant_row_r (grant_row_r[nBANK_MACHS-1:0]),
.grant_pre_r (grant_pre_r[nBANK_MACHS-1:0]),
.row_addr (row_addr[ROW_VECT_INDX:0]),
.row_cmd_wr (row_cmd_wr[nBANK_MACHS-1:0]),
.insert_maint_r1 (insert_maint_r1),
.maint_zq_r (maint_zq_r),
.maint_sre_r (maint_sre_r),
.maint_srx_r (maint_srx_r),
.maint_rank_r (maint_rank_r[RANK_WIDTH-1:0]),
.req_periodic_rd_r (req_periodic_rd_r[nBANK_MACHS-1:0]),
.req_size_r (req_size_r[nBANK_MACHS-1:0]),
.rd_wr_r (rd_wr_r[nBANK_MACHS-1:0]),
.req_row_r (req_row_r[ROW_VECT_INDX:0]),
.col_addr (col_addr[ROW_VECT_INDX:0]),
.req_data_buf_addr_r (req_data_buf_addr_r[DATA_BUF_ADDR_VECT_INDX:0]),
.grant_col_r (grant_col_r[nBANK_MACHS-1:0]),
.grant_col_wr (grant_col_wr[nBANK_MACHS-1:0]),
.send_cmd0_row (send_cmd0_row),
.send_cmd0_col (send_cmd0_col),
.send_cmd1_row (send_cmd1_row),
.send_cmd1_col (send_cmd1_col),
.send_cmd2_row (send_cmd2_row),
.send_cmd2_col (send_cmd2_col),
.send_cmd2_pre (send_cmd2_pre),
.send_cmd3_col (send_cmd3_col),
.sent_col (EVEN_CWL_2T_MODE == "ON" ? sent_col_r : sent_col),
.cs_en0 (cs_en0),
.cs_en1 (cs_en1),
.cs_en2 (cs_en2),
.cs_en3 (cs_en3),
.grant_config_r (grant_config_r[nBANK_MACHS-1:0]),
.rnk_config_strobe (rnk_config_strobe),
.slot_0_present (slot_0_present[7:0]),
.slot_1_present (slot_1_present[7:0]));
endmodule
|
// ----------------------------------------------------------------------
// Copyright (c) 2016, The Regents of the University of California All
// rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// * Neither the name of The Regents of the University of California
// nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL REGENTS OF THE
// UNIVERSITY OF CALIFORNIA BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
// OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
// TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
// ----------------------------------------------------------------------
//----------------------------------------------------------------------------
// Filename: rx_port_reader.v
// Version: 1.00.a
// Verilog Standard: Verilog-2001
// Description: Handles the RX lifecycle and issuing requests for receiving
// data input.
// for the RIFFA channel.
// Author: Matt Jacobsen
// History: @mattj: Version 2.0
//-----------------------------------------------------------------------------
`define S_RXPORTRD_MAIN_IDLE 6'b00_0001
`define S_RXPORTRD_MAIN_CHECK 6'b00_0010
`define S_RXPORTRD_MAIN_READ 6'b00_0100
`define S_RXPORTRD_MAIN_FLUSH 6'b00_1000
`define S_RXPORTRD_MAIN_DONE 6'b01_0000
`define S_RXPORTRD_MAIN_RESET 6'b10_0000
`define S_RXPORTRD_RX_IDLE 8'b0000_0001
`define S_RXPORTRD_RX_BUF 8'b0000_0010
`define S_RXPORTRD_RX_ADJ_0 8'b0000_0100
`define S_RXPORTRD_RX_ADJ_1 8'b0000_1000
`define S_RXPORTRD_RX_ISSUE 8'b0001_0000
`define S_RXPORTRD_RX_WAIT_0 8'b0010_0000
`define S_RXPORTRD_RX_WAIT_1 8'b0100_0000
`define S_RXPORTRD_RX_DONE 8'b1000_0000
`timescale 1ns/1ns
module rx_port_reader #(
parameter C_DATA_WIDTH = 9'd64,
parameter C_FIFO_DEPTH = 1024,
parameter C_MAX_READ_REQ = 2, // Max read: 000=128B, 001=256B, 010=512B, 011=1024B, 100=2048B, 101=4096B
// Local parameters
parameter C_DATA_WORD_WIDTH = clog2((C_DATA_WIDTH/32)+1),
parameter C_FIFO_WORDS = (C_DATA_WIDTH/32)*C_FIFO_DEPTH
)
(
input CLK,
input RST,
input [2:0] CONFIG_MAX_READ_REQUEST_SIZE, // Maximum read payload: 000=128B, 001=256B, 010=512B, 011=1024B, 100=2048B, 101=4096B
input [31:0] TXN_DATA, // Read transaction data
input TXN_LEN_VALID, // Read transaction length valid
input TXN_OFF_LAST_VALID, // Read transaction offset/last valid
output [31:0] TXN_DONE_LEN, // Read transaction actual transfer length
output TXN_DONE, // Read transaction done
output TXN_ERR, // Read transaction completed with error
input TXN_DONE_ACK, // Read transaction actual transfer length read
output TXN_DATA_FLUSH, // Request that all data in the packer be flushed
input TXN_DATA_FLUSHED, // All data in the packer has been flushed
output RX_REQ, // Issue a read request
output [63:0] RX_ADDR, // Request address
output [9:0] RX_LEN, // Request length
input RX_REQ_ACK, // Request has been accepted
input [C_DATA_WORD_WIDTH-1:0] RX_DATA_EN, // Incoming read data enable
input RX_DONE, // Incoming read completed
input RX_ERR, // Incoming read completed with error
input SG_DONE, // Incoming scatter gather read completed
input SG_ERR, // Incoming scatter gather read completed with error
input [63:0] SG_ELEM_ADDR, // Scatter gather element address
input [31:0] SG_ELEM_LEN, // Scatter gather element length (in words)
input SG_ELEM_RDY, // Scatter gather element ready
output SG_ELEM_REN, // Scatter gather element read enable
output SG_RST, // Scatter gather reset
output CHNL_RX, // Signal channel RX
output [31:0] CHNL_RX_LEN, // Channel RX length
output CHNL_RX_LAST, // Channel RX last
output [30:0] CHNL_RX_OFF, // Channel RX offset
input CHNL_RX_RECVD, // Channel RX received
input CHNL_RX_ACK_RECVD, // Channel RX acknowledgment received
input [31:0] CHNL_RX_CONSUMED // Channel words consumed in current RX
);
`include "functions.vh"
reg [31:0] rTxnData=0, _rTxnData=0;
reg rTxnOffLastValid=0, _rTxnOffLastValid=0;
reg rTxnLenValid=0, _rTxnLenValid=0;
reg [C_DATA_WORD_WIDTH-1:0] rRxDataEn=0, _rRxDataEn=0;
(* syn_encoding = "user" *)
(* fsm_encoding = "user" *)
reg [5:0] rMainState=`S_RXPORTRD_MAIN_IDLE, _rMainState=`S_RXPORTRD_MAIN_IDLE;
reg [31:0] rOffLast=0, _rOffLast=0;
reg [31:0] rReadWords=0, _rReadWords=0;
reg rReadWordsZero=0, _rReadWordsZero=0;
reg [0:0] rStart=0, _rStart=0;
reg [3:0] rFlushed=0, _rFlushed=0;
reg [31:0] rDoneLen=0, _rDoneLen=0;
reg rTxnDone=0, _rTxnDone=0;
(* syn_encoding = "user" *)
(* fsm_encoding = "user" *)
reg [7:0] rRxState=`S_RXPORTRD_RX_IDLE, _rRxState=`S_RXPORTRD_RX_IDLE;
reg rSgRen=0, _rSgRen=0;
reg [31:0] rWords=0, _rWords=0;
reg [31:0] rBufWords=0, _rBufWords=0;
reg [31:0] rBufWordsInit=0, _rBufWordsInit=0;
reg rLargeBuf=0, _rLargeBuf=0;
reg [63:0] rAddr=64'd0, _rAddr=64'd0;
reg [3:0] rValsProp=0, _rValsProp=0;
reg [2:0] rCarry=0, _rCarry=0;
reg rCopyBufWords=0, _rCopyBufWords=0;
reg rUseInit=0, _rUseInit=0;
reg [10:0] rPageRem=0, _rPageRem=0;
reg rPageSpill=0, _rPageSpill=0;
reg rPageSpillInit=0, _rPageSpillInit=0;
reg [10:0] rPreLen=0, _rPreLen=0;
reg [2:0] rMaxPayloadTrain=0, _rMaxPayloadTrain=0;
reg [2:0] rMaxPayloadShift=0, _rMaxPayloadShift=0;
reg [9:0] rMaxPayload=0, _rMaxPayload=0;
reg rPayloadSpill=0, _rPayloadSpill=0;
reg rMaxLen=0, _rMaxLen=0;
reg [9:0] rLen=0, _rLen=0;
reg rLenEQWordsHi=0, _rLenEQWordsHi=0;
reg rLenEQWordsLo=0, _rLenEQWordsLo=0;
reg rLenEQBufWordsHi=0, _rLenEQBufWordsHi=0;
reg rLenEQBufWordsLo=0, _rLenEQBufWordsLo=0;
reg [31:0] rRecvdWords=0, _rRecvdWords=0;
reg [31:0] rReqdWords=0, _rReqdWords=0;
reg [31:0] rRequestingWords=0, _rRequestingWords=0;
reg [31:0] rAvailWords=0, _rAvailWords=0;
reg [31:0] rPartWords=0, _rPartWords=0;
reg [10:0] rAckCount=0, _rAckCount=0;
reg rAckCountEQ0=0, _rAckCountEQ0=0;
reg rLastDoneRead=1, _rLastDoneRead=1;
reg rTxnDoneAck=0, _rTxnDoneAck=0;
reg rPartWordsRecvd=0, _rPartWordsRecvd=0;
reg rCarryInv=0, _rCarryInv=0;
reg rSpaceAvail=0, _rSpaceAvail=0;
reg rPartialDone=0, _rPartialDone=0;
reg rReqPartialDone=0, _rReqPartialDone=0;
reg rErr=0, _rErr=0;
assign TXN_DONE_LEN = rDoneLen;
assign TXN_DONE = (rTxnDone | rPartialDone);
assign TXN_ERR = rErr;
assign TXN_DATA_FLUSH = rMainState[3]; // S_RXPORTRD_MAIN_FLUSH
assign RX_REQ = (rRxState[4] & rSpaceAvail); // S_RXPORTRD_RX_ISSUE
assign RX_ADDR = rAddr;
assign RX_LEN = rLen;
assign SG_ELEM_REN = rSgRen;
assign SG_RST = rMainState[1]; // S_RXPORTRD_MAIN_CHECK
assign CHNL_RX = (rMainState[2] | rMainState[3] | rMainState[4]); // S_RXPORTRD_MAIN_READ | S_RXPORTRD_MAIN_FLUSH | S_RXPORTRD_MAIN_DONE
assign CHNL_RX_LEN = rReadWords;
assign CHNL_RX_LAST = rOffLast[0];
assign CHNL_RX_OFF = rOffLast[31:1];
// Buffer signals that come from outside the rx_port.
always @ (posedge CLK) begin
rTxnData <= #1 _rTxnData;
rTxnOffLastValid <= #1 _rTxnOffLastValid;
rTxnLenValid <= #1 _rTxnLenValid;
rTxnDoneAck <= #1 (RST ? 1'd0 : _rTxnDoneAck);
rRxDataEn <= #1 _rRxDataEn;
end
always @ (*) begin
_rTxnData = TXN_DATA;
_rTxnOffLastValid = TXN_OFF_LAST_VALID;
_rTxnLenValid = TXN_LEN_VALID;
_rTxnDoneAck = TXN_DONE_ACK;
_rRxDataEn = RX_DATA_EN;
end
// Handle RX lifecycle.
always @ (posedge CLK) begin
rMainState <= #1 (RST ? `S_RXPORTRD_MAIN_IDLE : _rMainState);
rOffLast <= #1 _rOffLast;
rReadWords <= #1 _rReadWords;
rReadWordsZero <= #1 _rReadWordsZero;
rStart <= #1 _rStart;
rFlushed <= #1 _rFlushed;
rDoneLen <= #1 (RST ? 0 : _rDoneLen);
rTxnDone <= #1 _rTxnDone;
end
always @ (*) begin
_rMainState = rMainState;
_rDoneLen = rDoneLen;
_rTxnDone = rTxnDone;
_rOffLast = (rTxnOffLastValid ? rTxnData : rOffLast);
_rReadWords = (rMainState[0] & rTxnLenValid ? rTxnData : rReadWords);
_rReadWordsZero = (rReadWords == 0);
_rStart = ((rStart<<1) | rTxnLenValid);
_rFlushed = ((rFlushed<<1) | TXN_DATA_FLUSHED);
case (rMainState)
`S_RXPORTRD_MAIN_IDLE: begin // Wait for new read transaction offset/last & length
_rTxnDone = 0;
if (rStart[0])
_rMainState = `S_RXPORTRD_MAIN_CHECK;
end
`S_RXPORTRD_MAIN_CHECK: begin // See if we should start a transaction
if (!rReadWordsZero)
_rMainState = `S_RXPORTRD_MAIN_READ;
else if (rOffLast[0])
_rMainState = `S_RXPORTRD_MAIN_FLUSH;
else
_rMainState = `S_RXPORTRD_MAIN_IDLE;
end
`S_RXPORTRD_MAIN_READ: begin // Issue read transfers, wait for data to arrive
if (rRxState[7] & rLastDoneRead) begin // S_RXPORTRD_RX_DONE
_rDoneLen = rRecvdWords;
_rMainState = `S_RXPORTRD_MAIN_FLUSH;
end
end
`S_RXPORTRD_MAIN_FLUSH: begin // Wait for data to be flushed
if (rFlushed[3])
_rMainState = `S_RXPORTRD_MAIN_DONE;
end
`S_RXPORTRD_MAIN_DONE: begin // Wait for RX to be received and ackd in the channel
if (CHNL_RX_RECVD & CHNL_RX_ACK_RECVD)
_rMainState = `S_RXPORTRD_MAIN_RESET;
end
`S_RXPORTRD_MAIN_RESET: begin // Wait until RX has dropped in the channel
if (!CHNL_RX_RECVD) begin
_rTxnDone = 1;
_rMainState = `S_RXPORTRD_MAIN_IDLE;
end
end
default: begin
_rMainState = `S_RXPORTRD_MAIN_IDLE;
end
endcase
end
// Issue the read requests at the buffer level. Decrement the amount requested
// after every request. Continue until all words have been requested.
wire [9:0] wAddrLoInv = ~rAddr[11:2];
always @ (posedge CLK) begin
rRxState <= #1 (RST ? `S_RXPORTRD_RX_IDLE : _rRxState);
rSgRen <= #1 (RST ? 1'd0: _rSgRen);
rWords <= #1 _rWords;
rBufWords <= #1 _rBufWords;
rBufWordsInit <= #1 _rBufWordsInit;
rLargeBuf <= #1 _rLargeBuf;
rAddr <= #1 _rAddr;
rCarry <= #1 _rCarry;
rValsProp <= #1 _rValsProp;
rPageRem <= #1 _rPageRem;
rPageSpill <= #1 _rPageSpill;
rPageSpillInit <= #1 _rPageSpillInit;
rCopyBufWords <= #1 _rCopyBufWords;
rUseInit <= #1 _rUseInit;
rPreLen <= #1 _rPreLen;
rMaxPayloadTrain <= #1 _rMaxPayloadTrain;
rMaxPayloadShift <= #1 _rMaxPayloadShift;
rMaxPayload <= #1 _rMaxPayload;
rPayloadSpill <= #1 _rPayloadSpill;
rMaxLen <= #1 _rMaxLen;
rLen <= #1 _rLen;
rLenEQWordsHi <= #1 _rLenEQWordsHi;
rLenEQWordsLo <= #1 _rLenEQWordsLo;
rLenEQBufWordsHi <= #1 _rLenEQBufWordsHi;
rLenEQBufWordsLo <= #1 _rLenEQBufWordsLo;
end
always @ (*) begin
_rRxState = rRxState;
_rCopyBufWords = rCopyBufWords;
_rUseInit = rUseInit;
_rSgRen = rSgRen;
_rValsProp = ((rValsProp<<1) | rRxState[2]); // S_RXPORTRD_RX_ADJ_0
_rLargeBuf = (SG_ELEM_LEN > rWords);
{_rCarry[0], _rAddr[15:0]} = (rRxState[1] ? SG_ELEM_ADDR[15:0] : (rAddr[15:0] + ({12{RX_REQ_ACK}} & {rLen,2'd0})));
{_rCarry[1], _rAddr[31:16]} = (rRxState[1] ? SG_ELEM_ADDR[31:16] : (rAddr[31:16] + rCarry[0]));
{_rCarry[2], _rAddr[47:32]} = (rRxState[1] ? SG_ELEM_ADDR[47:32] : (rAddr[47:32] + rCarry[1]));
_rAddr[63:48] = (rRxState[1] ? SG_ELEM_ADDR[63:48] : (rAddr[63:48] + rCarry[2]));
_rWords = (rRxState[0] ? rReadWords : (rWords - ({10{RX_REQ_ACK}} & rLen)));
_rBufWordsInit = (rLargeBuf ? rWords : SG_ELEM_LEN);
_rBufWords = (rCopyBufWords ? rBufWordsInit : rBufWords) - ({10{RX_REQ_ACK}} & rLen);
_rPageRem = (wAddrLoInv + 1'd1);
_rPageSpillInit = (rBufWordsInit > rPageRem);
_rPageSpill = (rBufWords > rPageRem);
_rPreLen = ((rPageSpillInit & rUseInit) | (rPageSpill & !rUseInit) ? rPageRem : rBufWords[10:0]);
_rMaxPayloadTrain = (CONFIG_MAX_READ_REQUEST_SIZE > 3'd4 ? 3'd4 : CONFIG_MAX_READ_REQUEST_SIZE);
_rMaxPayloadShift = (C_MAX_READ_REQ[2:0] < rMaxPayloadTrain ? C_MAX_READ_REQ[2:0] : rMaxPayloadTrain);
_rMaxPayload = (6'd32<<rMaxPayloadShift);
_rPayloadSpill = (rPreLen > rMaxPayload);
_rMaxLen = ((rMaxLen & !rValsProp[2]) | RX_REQ_ACK);
_rLen = (rPayloadSpill | rMaxLen ? rMaxPayload : rPreLen[9:0]);
_rLenEQWordsHi = (16'd0 == rWords[31:16]);
_rLenEQWordsLo = ({6'd0, rLen} == rWords[15:0]);
_rLenEQBufWordsHi = (16'd0 == rBufWords[31:16]);
_rLenEQBufWordsLo = ({6'd0, rLen} == rBufWords[15:0]);
case (rRxState)
`S_RXPORTRD_RX_IDLE: begin // Wait for a new read transaction
if (rMainState[2]) // S_RXPORTRD_MAIN_READ
_rRxState = `S_RXPORTRD_RX_BUF;
end
`S_RXPORTRD_RX_BUF: begin // Wait for buffer length and address
if (SG_ELEM_RDY) begin
_rSgRen = 1;
_rRxState = `S_RXPORTRD_RX_ADJ_0;
end
else if (rErr) begin
_rRxState = `S_RXPORTRD_RX_WAIT_0;
end
end
`S_RXPORTRD_RX_ADJ_0: begin // Fix for large buffer
_rSgRen = 0;
_rCopyBufWords = rSgRen;
_rRxState = `S_RXPORTRD_RX_ADJ_1;
end
// (bufwords and pagerem valid here)
`S_RXPORTRD_RX_ADJ_1: begin // Wait for the value to propagate
// Check for page boundary crossing
// Fix for page boundary crossing
// Check for max read payload
// Fix for max read payload
_rCopyBufWords = 0;
_rUseInit = rCopyBufWords;
if (rValsProp[3])
_rRxState = `S_RXPORTRD_RX_ISSUE;
end
`S_RXPORTRD_RX_ISSUE: begin // Wait for the request to be accepted
if (RX_REQ_ACK) begin
if (rErr | (rLenEQWordsHi & rLenEQWordsLo))
_rRxState = `S_RXPORTRD_RX_WAIT_0;
else if (rLenEQBufWordsHi & rLenEQBufWordsLo)
_rRxState = `S_RXPORTRD_RX_BUF;
else
_rRxState = `S_RXPORTRD_RX_ADJ_0;
end
end
`S_RXPORTRD_RX_WAIT_0: begin // Wait for rAckCount to update
_rRxState = `S_RXPORTRD_RX_WAIT_1;
end
`S_RXPORTRD_RX_WAIT_1: begin // Wait for requested data to arrive
if (rAckCountEQ0)
_rRxState = `S_RXPORTRD_RX_DONE;
end
`S_RXPORTRD_RX_DONE: begin // Signal done
if (rMainState[3]) // S_RXPORTRD_MAIN_FLUSH
_rRxState = `S_RXPORTRD_RX_IDLE;
end
default: begin
_rRxState = `S_RXPORTRD_RX_IDLE;
end
endcase
end
// Count the data.
always @ (posedge CLK) begin
rRecvdWords <= #1 _rRecvdWords;
rReqdWords <= #1 _rReqdWords;
rPartWords <= #1 _rPartWords;
rAckCount <= #1 _rAckCount;
rAckCountEQ0 <= #1 _rAckCountEQ0;
rPartWordsRecvd <= #1 _rPartWordsRecvd;
rRequestingWords <= #1 _rRequestingWords;
rAvailWords <= #1 _rAvailWords;
rCarryInv <= #1 _rCarryInv;
rSpaceAvail <= #1 _rSpaceAvail;
rLastDoneRead <= #1 (RST ? 1'd1 : _rLastDoneRead);
end
always @ (*) begin
// Count words as they arrive (words from the rx_engine directly).
if (rMainState[0]) // S_RXPORTRD_MAIN_IDLE
_rRecvdWords = #1 0;
else
_rRecvdWords = #1 rRecvdWords + rRxDataEn;
// Count words as they are requested.
if (rMainState[0]) // S_RXPORTRD_MAIN_IDLE
_rReqdWords = #1 0;
else
_rReqdWords = #1 rReqdWords + ({10{RX_REQ_ACK}} & rLen);
// Track outstanding requests
if (rMainState[0]) // S_RXPORTRD_MAIN_IDLE
_rAckCount = 0;
else
_rAckCount = rAckCount + RX_REQ_ACK - RX_DONE;
_rAckCountEQ0 = (rAckCount == 11'd0);
// Track when the user reads the actual transfer amount.
_rLastDoneRead = (rTxnDone ? 1'd0 : (rLastDoneRead | rTxnDoneAck));
// Track the amount of words that are expected to arrive.
_rPartWords = #1 (rTxnLenValid ? rTxnData : rPartWords);
// Compare counts.
_rPartWordsRecvd = (rRecvdWords >= rPartWords);
_rRequestingWords = rReqdWords + rLen;
{_rCarryInv, _rAvailWords[15:0]} = {1'd1, rRequestingWords[15:0]} - CHNL_RX_CONSUMED[15:0];
_rAvailWords[31:16] = rRequestingWords[31:16] - CHNL_RX_CONSUMED[31:16] - !rCarryInv;
_rSpaceAvail = (rAvailWords <= C_FIFO_WORDS);
end
// Facilitate sending a TXN_DONE when we receive a TXN_ACK after the transaction
// has begun sending. This will happen when the workstation detects that it has
// sent/used all its currently mapped scatter gather elements, but it's not enough
// to complete the transaction. The TXN_DONE will let the workstation know it can
// release the current scatter gather mappings and allocate new ones.
always @ (posedge CLK) begin
rPartialDone <= #1 _rPartialDone;
rReqPartialDone <= #1 (RST ? 1'd0 : _rReqPartialDone);
end
always @ (*) begin
// Signal TXN_DONE after we've recieved the (seemingly superfluous) TXN_ACK
// and received the corresponding amount of words.
_rPartialDone = (rReqPartialDone & rPartWordsRecvd);
// Keep track of (seemingly superfluous) TXN_ACK requests.
if ((rReqPartialDone & rPartWordsRecvd) | rMainState[0]) // S_RXPORTRD_MAIN_IDLE
_rReqPartialDone = 0;
else
_rReqPartialDone = (rReqPartialDone | rTxnLenValid);
end
// Handle errors in the main data or scatter gather data.
always @ (posedge CLK) begin
rErr <= #1 (RST ? 1'd0 : _rErr);
end
always @ (*) begin
// Keep track of errors if we encounter them.
if (rMainState[0]) // S_RXPORTRD_MAIN_IDLE
_rErr = 0;
else
_rErr = (rErr | (RX_DONE & RX_ERR) | (SG_DONE & SG_ERR));
end
/*
wire [35:0] wControl0;
chipscope_icon_1 cs_icon(
.CONTROL0(wControl0)
);
chipscope_ila_t8_512 a0(
.CLK(CLK),
.CONTROL(wControl0),
.TRIG0({TXN_LEN_VALID | TXN_DONE_ACK | TXN_DONE | TXN_ERR, 1'd0, rMainState}),
.DATA({176'd0,
64'd0, // 64
rAddr, // 64
SG_ELEM_RDY, // 1
1'd0, // 1
1'd0, // 1
1'd0, // 1
rSgRen, // 1
1'd0, // 1
rLastDoneRead, // 1
rLen, // 10
rWords, // 32
rAckCount, // 11
rPartWords, // 32
rPartWordsRecvd, // 1
rReqPartialDone, // 1
rPartialDone, // 1
rTxnDone, // 1
rRxState, // 8
rRecvdWords, // 32
rReadWords, // 32
TXN_LEN_VALID, // 1
TXN_DONE_ACK, // 1
rDoneLen, // 32
rMainState}) // 6
);
*/
endmodule
|
// (C) 2001-2016 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
// THIS FILE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THIS FILE OR THE USE OR OTHER DEALINGS
// IN THIS FILE.
/******************************************************************************
* *
* This module writes data to the RS232 UART Port. *
* *
******************************************************************************/
module altera_up_rs232_out_serializer (
// Inputs
clk,
reset,
transmit_data,
transmit_data_en,
// Bidirectionals
// Outputs
fifo_write_space,
serial_data_out
);
/*****************************************************************************
* Parameter Declarations *
*****************************************************************************/
parameter CW = 9; // Baud counter width
parameter BAUD_TICK_COUNT = 433;
parameter HALF_BAUD_TICK_COUNT = 216;
parameter TDW = 11; // Total data width
parameter DW = 9; // Data width
/*****************************************************************************
* Port Declarations *
*****************************************************************************/
// Inputs
input clk;
input reset;
input [DW: 0] transmit_data;
input transmit_data_en;
// Bidirectionals
// Outputs
output reg [ 7: 0] fifo_write_space;
output reg serial_data_out;
/*****************************************************************************
* Constant Declarations *
*****************************************************************************/
/*****************************************************************************
* Internal Wires and Registers Declarations *
*****************************************************************************/
// Internal Wires
wire shift_data_reg_en;
wire all_bits_transmitted;
wire read_fifo_en;
wire fifo_is_empty;
wire fifo_is_full;
wire [ 6: 0] fifo_used;
wire [DW: 0] data_from_fifo;
// Internal Registers
reg transmitting_data;
reg [DW+1:0] data_out_shift_reg;
// State Machine Registers
/*****************************************************************************
* Finite State Machine(s) *
*****************************************************************************/
/*****************************************************************************
* Sequential Logic *
*****************************************************************************/
always @(posedge clk)
begin
if (reset)
fifo_write_space <= 8'h00;
else
fifo_write_space <= 8'h80 - {fifo_is_full, fifo_used};
end
always @(posedge clk)
begin
if (reset)
serial_data_out <= 1'b1;
else
serial_data_out <= data_out_shift_reg[0];
end
always @(posedge clk)
begin
if (reset)
transmitting_data <= 1'b0;
else if (all_bits_transmitted)
transmitting_data <= 1'b0;
else if (fifo_is_empty == 1'b0)
transmitting_data <= 1'b1;
end
always @(posedge clk)
begin
if (reset)
data_out_shift_reg <= {(DW + 2){1'b1}};
else if (read_fifo_en)
data_out_shift_reg <= {data_from_fifo, 1'b0};
else if (shift_data_reg_en)
data_out_shift_reg <=
{1'b1, data_out_shift_reg[DW+1:1]};
end
/*****************************************************************************
* Combinational Logic *
*****************************************************************************/
assign read_fifo_en =
~transmitting_data & ~fifo_is_empty & ~all_bits_transmitted;
/*****************************************************************************
* Internal Modules *
*****************************************************************************/
altera_up_rs232_counters RS232_Out_Counters (
// Inputs
.clk (clk),
.reset (reset),
.reset_counters (~transmitting_data),
// Bidirectionals
// Outputs
.baud_clock_rising_edge (shift_data_reg_en),
.baud_clock_falling_edge (),
.all_bits_transmitted (all_bits_transmitted)
);
defparam
RS232_Out_Counters.CW = CW,
RS232_Out_Counters.BAUD_TICK_COUNT = BAUD_TICK_COUNT,
RS232_Out_Counters.HALF_BAUD_TICK_COUNT = HALF_BAUD_TICK_COUNT,
RS232_Out_Counters.TDW = TDW;
altera_up_sync_fifo RS232_Out_FIFO (
// Inputs
.clk (clk),
.reset (reset),
.write_en (transmit_data_en & ~fifo_is_full),
.write_data (transmit_data),
.read_en (read_fifo_en),
// Bidirectionals
// Outputs
.fifo_is_empty (fifo_is_empty),
.fifo_is_full (fifo_is_full),
.words_used (fifo_used),
.read_data (data_from_fifo)
);
defparam
RS232_Out_FIFO.DW = DW,
RS232_Out_FIFO.DATA_DEPTH = 128,
RS232_Out_FIFO.AW = 6;
endmodule
|
// (C) 2001-2016 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
// THIS FILE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THIS FILE OR THE USE OR OTHER DEALINGS
// IN THIS FILE.
/******************************************************************************
* *
* This module writes data to the RS232 UART Port. *
* *
******************************************************************************/
module altera_up_rs232_out_serializer (
// Inputs
clk,
reset,
transmit_data,
transmit_data_en,
// Bidirectionals
// Outputs
fifo_write_space,
serial_data_out
);
/*****************************************************************************
* Parameter Declarations *
*****************************************************************************/
parameter CW = 9; // Baud counter width
parameter BAUD_TICK_COUNT = 433;
parameter HALF_BAUD_TICK_COUNT = 216;
parameter TDW = 11; // Total data width
parameter DW = 9; // Data width
/*****************************************************************************
* Port Declarations *
*****************************************************************************/
// Inputs
input clk;
input reset;
input [DW: 0] transmit_data;
input transmit_data_en;
// Bidirectionals
// Outputs
output reg [ 7: 0] fifo_write_space;
output reg serial_data_out;
/*****************************************************************************
* Constant Declarations *
*****************************************************************************/
/*****************************************************************************
* Internal Wires and Registers Declarations *
*****************************************************************************/
// Internal Wires
wire shift_data_reg_en;
wire all_bits_transmitted;
wire read_fifo_en;
wire fifo_is_empty;
wire fifo_is_full;
wire [ 6: 0] fifo_used;
wire [DW: 0] data_from_fifo;
// Internal Registers
reg transmitting_data;
reg [DW+1:0] data_out_shift_reg;
// State Machine Registers
/*****************************************************************************
* Finite State Machine(s) *
*****************************************************************************/
/*****************************************************************************
* Sequential Logic *
*****************************************************************************/
always @(posedge clk)
begin
if (reset)
fifo_write_space <= 8'h00;
else
fifo_write_space <= 8'h80 - {fifo_is_full, fifo_used};
end
always @(posedge clk)
begin
if (reset)
serial_data_out <= 1'b1;
else
serial_data_out <= data_out_shift_reg[0];
end
always @(posedge clk)
begin
if (reset)
transmitting_data <= 1'b0;
else if (all_bits_transmitted)
transmitting_data <= 1'b0;
else if (fifo_is_empty == 1'b0)
transmitting_data <= 1'b1;
end
always @(posedge clk)
begin
if (reset)
data_out_shift_reg <= {(DW + 2){1'b1}};
else if (read_fifo_en)
data_out_shift_reg <= {data_from_fifo, 1'b0};
else if (shift_data_reg_en)
data_out_shift_reg <=
{1'b1, data_out_shift_reg[DW+1:1]};
end
/*****************************************************************************
* Combinational Logic *
*****************************************************************************/
assign read_fifo_en =
~transmitting_data & ~fifo_is_empty & ~all_bits_transmitted;
/*****************************************************************************
* Internal Modules *
*****************************************************************************/
altera_up_rs232_counters RS232_Out_Counters (
// Inputs
.clk (clk),
.reset (reset),
.reset_counters (~transmitting_data),
// Bidirectionals
// Outputs
.baud_clock_rising_edge (shift_data_reg_en),
.baud_clock_falling_edge (),
.all_bits_transmitted (all_bits_transmitted)
);
defparam
RS232_Out_Counters.CW = CW,
RS232_Out_Counters.BAUD_TICK_COUNT = BAUD_TICK_COUNT,
RS232_Out_Counters.HALF_BAUD_TICK_COUNT = HALF_BAUD_TICK_COUNT,
RS232_Out_Counters.TDW = TDW;
altera_up_sync_fifo RS232_Out_FIFO (
// Inputs
.clk (clk),
.reset (reset),
.write_en (transmit_data_en & ~fifo_is_full),
.write_data (transmit_data),
.read_en (read_fifo_en),
// Bidirectionals
// Outputs
.fifo_is_empty (fifo_is_empty),
.fifo_is_full (fifo_is_full),
.words_used (fifo_used),
.read_data (data_from_fifo)
);
defparam
RS232_Out_FIFO.DW = DW,
RS232_Out_FIFO.DATA_DEPTH = 128,
RS232_Out_FIFO.AW = 6;
endmodule
|
// ----------------------------------------------------------------------
// Copyright (c) 2016, The Regents of the University of California All
// rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// * Neither the name of The Regents of the University of California
// nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL REGENTS OF THE
// UNIVERSITY OF CALIFORNIA BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
// OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
// TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
// ----------------------------------------------------------------------
//----------------------------------------------------------------------------
// Filename: fifo_packer_128.v
// Version: 1.00.a
// Verilog Standard: Verilog-2001
// Description: Packs 32, 64, or 96 bit received data into a 128 bit wide
// FIFO. Assumes the FIFO always has room to accommodate the data.
// Author: Matt Jacobsen
// History: @mattj: Version 2.0
// Additional Comments:
//-----------------------------------------------------------------------------
`timescale 1ns/1ns
module fifo_packer_128 (
input CLK,
input RST,
input [127:0] DATA_IN, // Incoming data
input [2:0] DATA_IN_EN, // Incoming data enable
input DATA_IN_DONE, // Incoming data packet end
input DATA_IN_ERR, // Incoming data error
input DATA_IN_FLUSH, // End of incoming data
output [127:0] PACKED_DATA, // Outgoing data
output PACKED_WEN, // Outgoing data write enable
output PACKED_DATA_DONE, // End of outgoing data packet
output PACKED_DATA_ERR, // Error in outgoing data
output PACKED_DATA_FLUSHED // End of outgoing data
);
reg [2:0] rPackedCount=0, _rPackedCount=0;
reg rPackedDone=0, _rPackedDone=0;
reg rPackedErr=0, _rPackedErr=0;
reg rPackedFlush=0, _rPackedFlush=0;
reg rPackedFlushed=0, _rPackedFlushed=0;
reg [223:0] rPackedData=224'd0, _rPackedData=224'd0;
reg [127:0] rDataIn=128'd0, _rDataIn=128'd0;
reg [2:0] rDataInEn=0, _rDataInEn=0;
reg [127:0] rDataMasked=128'd0, _rDataMasked=128'd0;
reg [2:0] rDataMaskedEn=0, _rDataMaskedEn=0;
assign PACKED_DATA = rPackedData[127:0];
assign PACKED_WEN = rPackedCount[2];
assign PACKED_DATA_DONE = rPackedDone;
assign PACKED_DATA_ERR = rPackedErr;
assign PACKED_DATA_FLUSHED = rPackedFlushed;
// Buffers input data until 4 words are available, then writes 4 words out.
wire [127:0] wMask = {128{1'b1}}<<(32*rDataInEn);
wire [127:0] wDataMasked = ~wMask & rDataIn;
always @ (posedge CLK) begin
rPackedCount <= #1 (RST ? 3'd0 : _rPackedCount);
rPackedDone <= #1 (RST ? 1'd0 : _rPackedDone);
rPackedErr <= #1 (RST ? 1'd0 : _rPackedErr);
rPackedFlush <= #1 (RST ? 1'd0 : _rPackedFlush);
rPackedFlushed <= #1 (RST ? 1'd0 : _rPackedFlushed);
rPackedData <= #1 (RST ? 224'd0 : _rPackedData);
rDataIn <= #1 _rDataIn;
rDataInEn <= #1 (RST ? 3'd0 : _rDataInEn);
rDataMasked <= #1 _rDataMasked;
rDataMaskedEn <= #1 (RST ? 3'd0 : _rDataMaskedEn);
end
always @ (*) begin
// Buffer and mask the input data.
_rDataIn = DATA_IN;
_rDataInEn = DATA_IN_EN;
_rDataMasked = wDataMasked;
_rDataMaskedEn = rDataInEn;
// Count what's in our buffer. When we reach 4 words, 4 words will be written
// out. If flush is requested, write out whatever remains.
if (rPackedFlush && (rPackedCount[1] | rPackedCount[0]))
_rPackedCount = 4;
else
_rPackedCount = rPackedCount + rDataMaskedEn - {rPackedCount[2], 2'd0};
// Shift data into and out of our buffer as we receive and write out data.
if (rDataMaskedEn != 3'd0)
_rPackedData = ((rPackedData>>(32*{rPackedCount[2], 2'd0})) | (rDataMasked<<(32*rPackedCount[1:0])));
else
_rPackedData = (rPackedData>>(32*{rPackedCount[2], 2'd0}));
// Track done/error/flush signals.
_rPackedDone = DATA_IN_DONE;
_rPackedErr = DATA_IN_ERR;
_rPackedFlush = DATA_IN_FLUSH;
_rPackedFlushed = rPackedFlush;
end
endmodule
|
// ----------------------------------------------------------------------
// Copyright (c) 2016, The Regents of the University of California All
// rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// * Neither the name of The Regents of the University of California
// nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL REGENTS OF THE
// UNIVERSITY OF CALIFORNIA BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
// OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
// TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
// ----------------------------------------------------------------------
//----------------------------------------------------------------------------
// Filename: tx_port_writer.v
// Version: 1.00.a
// Verilog Standard: Verilog-2001
// Description: Handles receiving new transaction events and data, and
// making requests to tx engine.
// for the RIFFA channel.
// Author: Matt Jacobsen
// History: @mattj: Version 2.0
//-----------------------------------------------------------------------------
`define S_TXPORTWR_MAIN_IDLE 8'b0000_0001
`define S_TXPORTWR_MAIN_CHECK 8'b0000_0010
`define S_TXPORTWR_MAIN_SIG_NEW 8'b0000_0100
`define S_TXPORTWR_MAIN_NEW_ACK 8'b0000_1000
`define S_TXPORTWR_MAIN_WRITE 8'b0001_0000
`define S_TXPORTWR_MAIN_DONE 8'b0010_0000
`define S_TXPORTWR_MAIN_SIG_DONE 8'b0100_0000
`define S_TXPORTWR_MAIN_RESET 8'b1000_0000
`define S_TXPORTWR_TX_IDLE 8'b0000_0001
`define S_TXPORTWR_TX_BUF 8'b0000_0010
`define S_TXPORTWR_TX_ADJ_0 8'b0000_0100
`define S_TXPORTWR_TX_ADJ_1 8'b0000_1000
`define S_TXPORTWR_TX_ADJ_2 8'b0001_0000
`define S_TXPORTWR_TX_CHECK_DATA 8'b0010_0000
`define S_TXPORTWR_TX_WRITE 8'b0100_0000
`define S_TXPORTWR_TX_WRITE_REM 8'b1000_0000
`timescale 1ns/1ns
module tx_port_writer (
input CLK,
input RST,
input [2:0] CONFIG_MAX_PAYLOAD_SIZE, // Maximum write payload: 000=128B, 001=256B, 010=512B, 011=1024B
output TXN, // Write transaction notification
input TXN_ACK, // Write transaction acknowledged
output [31:0] TXN_LEN, // Write transaction length
output [31:0] TXN_OFF_LAST, // Write transaction offset/last
output [31:0] TXN_DONE_LEN, // Write transaction actual transfer length
output TXN_DONE, // Write transaction done
output TXN_ERR, // Write transaction encountered an error
input TXN_DONE_ACK, // Write transaction actual transfer length read
input NEW_TXN, // Transaction parameters are valid
output NEW_TXN_ACK, // Transaction parameter read, continue
input NEW_TXN_LAST, // Channel last write
input [31:0] NEW_TXN_LEN, // Channel write length (in 32 bit words)
input [30:0] NEW_TXN_OFF, // Channel write offset
input [31:0] NEW_TXN_WORDS_RECVD, // Count of data words received in transaction
input NEW_TXN_DONE, // Transaction is closed
input [63:0] SG_ELEM_ADDR, // Scatter gather element address
input [31:0] SG_ELEM_LEN, // Scatter gather element length (in words)
input SG_ELEM_RDY, // Scatter gather element ready
input SG_ELEM_EMPTY, // Scatter gather elements empty
output SG_ELEM_REN, // Scatter gather element read enable
output SG_RST, // Scatter gather data reset
input SG_ERR, // Scatter gather read encountered an error
output TX_REQ, // Outgoing write request
input TX_REQ_ACK, // Outgoing write request acknowledged
output [63:0] TX_ADDR, // Outgoing write high address
output [9:0] TX_LEN, // Outgoing write length (in 32 bit words)
output TX_LAST, // Outgoing write is last request for transaction
input TX_SENT // Outgoing write complete
);
`include "functions.vh"
(* syn_encoding = "user" *)
(* fsm_encoding = "user" *)
reg [7:0] rMainState=`S_TXPORTWR_MAIN_IDLE, _rMainState=`S_TXPORTWR_MAIN_IDLE;
reg [31:0] rOffLast=0, _rOffLast=0;
reg rWordsEQ0=0, _rWordsEQ0=0;
reg rStarted=0, _rStarted=0;
reg [31:0] rDoneLen=0, _rDoneLen=0;
reg rSgErr=0, _rSgErr=0;
reg rTxErrd=0, _rTxErrd=0;
reg rTxnAck=0, _rTxnAck=0;
(* syn_encoding = "user" *)
(* fsm_encoding = "user" *)
reg [7:0] rTxState=`S_TXPORTWR_TX_IDLE, _rTxState=`S_TXPORTWR_TX_IDLE;
reg [31:0] rSentWords=0, _rSentWords=0;
reg [31:0] rWords=0, _rWords=0;
reg [31:0] rBufWords=0, _rBufWords=0;
reg [31:0] rBufWordsInit=0, _rBufWordsInit=0;
reg rLargeBuf=0, _rLargeBuf=0;
reg [63:0] rAddr=64'd0, _rAddr=64'd0;
reg [2:0] rCarry=0, _rCarry=0;
reg rValsPropagated=0, _rValsPropagated=0;
reg [5:0] rValsProp=0, _rValsProp=0;
reg rCopyBufWords=0, _rCopyBufWords=0;
reg rUseInit=0, _rUseInit=0;
reg [10:0] rPageRem=0, _rPageRem=0;
reg rPageSpill=0, _rPageSpill=0;
reg rPageSpillInit=0, _rPageSpillInit=0;
reg [10:0] rPreLen=0, _rPreLen=0;
reg [2:0] rMaxPayloadSize=0, _rMaxPayloadSize=0;
reg [2:0] rMaxPayloadShift=0, _rMaxPayloadShift=0;
reg [9:0] rMaxPayload=0, _rMaxPayload=0;
reg rPayloadSpill=0, _rPayloadSpill=0;
reg rMaxLen=1, _rMaxLen=1;
reg [9:0] rLen=0, _rLen=0;
reg [31:0] rSendingWords=0, _rSendingWords=0;
reg rAvail=0, _rAvail=0;
reg [1:0] rTxnDone=0, _rTxnDone=0;
reg [9:0] rLastLen=0, _rLastLen=0;
reg rLastLenEQ0=0, _rLastLenEQ0=0;
reg rLenEQWords=0, _rLenEQWords=0;
reg rLenEQBufWords=0, _rLenEQBufWords=0;
reg rNotRequesting=1, _rNotRequesting=1;
reg [63:0] rReqAddr=64'd0, _rReqAddr=64'd0;
reg [9:0] rReqLen=0, _rReqLen=0;
reg rReqLast=0, _rReqLast=0;
reg rTxReqAck=0, _rTxReqAck=0;
reg rDone=0, _rDone=0;
reg [9:0] rAckCount=0, _rAckCount=0;
reg rTxSent=0, _rTxSent=0;
reg rLastDoneRead=1, _rLastDoneRead=1;
reg rTxnDoneAck=0, _rTxnDoneAck=0;
reg rReqPartialDone=0, _rReqPartialDone=0;
reg rPartialDone=0, _rPartialDone=0;
assign NEW_TXN_ACK = rMainState[1]; // S_TXPORTWR_MAIN_CHECK
assign TXN = rMainState[2]; // S_TXPORTWR_MAIN_SIG_NEW
assign TXN_DONE = (rMainState[6] | rPartialDone); // S_TXPORTWR_MAIN_SIG_DONE
assign TXN_LEN = rWords;
assign TXN_OFF_LAST = rOffLast;
assign TXN_DONE_LEN = rDoneLen;
assign TXN_ERR = rTxErrd;
assign SG_ELEM_REN = rTxState[2]; // S_TXPORTWR_TX_ADJ_0
assign SG_RST = rMainState[3]; // S_TXPORTWR_MAIN_NEW_ACK
assign TX_REQ = !rNotRequesting;
assign TX_ADDR = rReqAddr;
assign TX_LEN = rReqLen;
assign TX_LAST = rReqLast;
// Buffer the input signals that come from outside the tx_port.
always @ (posedge CLK) begin
rTxnAck <= #1 (RST ? 1'd0 : _rTxnAck);
rTxnDoneAck <= #1 (RST ? 1'd0 : _rTxnDoneAck);
rSgErr <= #1 (RST ? 1'd0 : _rSgErr);
rTxReqAck <= #1 (RST ? 1'd0 : _rTxReqAck);
rTxSent <= #1 (RST ? 1'd0 : _rTxSent);
end
always @ (*) begin
_rTxnAck = TXN_ACK;
_rTxnDoneAck = TXN_DONE_ACK;
_rSgErr = SG_ERR;
_rTxReqAck = TX_REQ_ACK;
_rTxSent = TX_SENT;
end
// Wait for a NEW_TXN request. Then request transfers until all the data is sent
// or until the specified length is reached. Then signal TXN_DONE.
always @ (posedge CLK) begin
rMainState <= #1 (RST ? `S_TXPORTWR_MAIN_IDLE : _rMainState);
rOffLast <= #1 _rOffLast;
rWordsEQ0 <= #1 _rWordsEQ0;
rStarted <= #1 _rStarted;
rDoneLen <= #1 (RST ? 0 : _rDoneLen);
rTxErrd <= #1 (RST ? 1'd0 : _rTxErrd);
end
always @ (*) begin
_rMainState = rMainState;
_rOffLast = rOffLast;
_rWordsEQ0 = rWordsEQ0;
_rStarted = rStarted;
_rDoneLen = rDoneLen;
_rTxErrd = rTxErrd;
case (rMainState)
`S_TXPORTWR_MAIN_IDLE: begin // Wait for channel write request
_rStarted = 0;
_rWordsEQ0 = (NEW_TXN_LEN == 0);
_rOffLast = {NEW_TXN_OFF, NEW_TXN_LAST};
if (NEW_TXN)
_rMainState = `S_TXPORTWR_MAIN_CHECK;
end
`S_TXPORTWR_MAIN_CHECK: begin // Continue with transaction?
if (rOffLast[0] | !rWordsEQ0)
_rMainState = `S_TXPORTWR_MAIN_SIG_NEW;
else
_rMainState = `S_TXPORTWR_MAIN_RESET;
end
`S_TXPORTWR_MAIN_SIG_NEW: begin // Signal new write
_rMainState = `S_TXPORTWR_MAIN_NEW_ACK;
end
`S_TXPORTWR_MAIN_NEW_ACK: begin // Wait for acknowledgement
if (rTxnAck) // ACK'd on PC read of TXN length
_rMainState = (rWordsEQ0 ? `S_TXPORTWR_MAIN_SIG_DONE : `S_TXPORTWR_MAIN_WRITE);
end
`S_TXPORTWR_MAIN_WRITE: begin // Start writing and wait for all writes to complete
_rStarted = (rStarted | rTxState[1]); // S_TXPORTWR_TX_BUF
_rTxErrd = (rTxErrd | rSgErr);
if (rTxState[0] & rStarted) // S_TXPORTWR_TX_IDLE
_rMainState = `S_TXPORTWR_MAIN_DONE;
end
`S_TXPORTWR_MAIN_DONE: begin // Wait for the last transaction to complete
if (rDone & rLastDoneRead) begin
_rDoneLen = rSentWords;
_rMainState = `S_TXPORTWR_MAIN_SIG_DONE;
end
end
`S_TXPORTWR_MAIN_SIG_DONE: begin // Signal the done port
_rTxErrd = 0;
_rMainState = `S_TXPORTWR_MAIN_RESET;
end
`S_TXPORTWR_MAIN_RESET: begin // Wait for the channel tx to drop
if (NEW_TXN_DONE)
_rMainState = `S_TXPORTWR_MAIN_IDLE;
end
default: begin
_rMainState = `S_TXPORTWR_MAIN_IDLE;
end
endcase
end
// Manage sending TX requests to the TX engine. Transfers will be limited
// by each scatter gather buffer's size, max payload size, and must not
// cross a (4KB) page boundary. The request is only made if there is sufficient
// data already written to the buffer.
wire [9:0] wLastLen = (NEW_TXN_WORDS_RECVD - rSentWords);
wire [9:0] wAddrLoInv = ~rAddr[11:2];
wire [10:0] wPageRem = (wAddrLoInv + 1'd1);
always @ (posedge CLK) begin
rTxState <= #1 (RST | rSgErr ? `S_TXPORTWR_TX_IDLE : _rTxState);
rSentWords <= #1 (rMainState[0] ? 0 : _rSentWords);
rWords <= #1 _rWords;
rBufWords <= #1 _rBufWords;
rBufWordsInit <= #1 _rBufWordsInit;
rAddr <= #1 _rAddr;
rCarry <= #1 _rCarry;
rValsPropagated <= #1 _rValsPropagated;
rValsProp <= #1 _rValsProp;
rLargeBuf <= #1 _rLargeBuf;
rPageRem <= #1 _rPageRem;
rPageSpill <= #1 _rPageSpill;
rPageSpillInit <= #1 _rPageSpillInit;
rCopyBufWords <= #1 _rCopyBufWords;
rUseInit <= #1 _rUseInit;
rPreLen <= #1 _rPreLen;
rMaxPayloadSize <= #1 _rMaxPayloadSize;
rMaxPayloadShift <= #1 _rMaxPayloadShift;
rMaxPayload <= #1 _rMaxPayload;
rPayloadSpill <= #1 _rPayloadSpill;
rMaxLen <= #1 (RST ? 1'd1 : _rMaxLen);
rLen <= #1 _rLen;
rSendingWords <= #1 _rSendingWords;
rAvail <= #1 _rAvail;
rTxnDone <= #1 _rTxnDone;
rLastLen <= #1 _rLastLen;
rLastLenEQ0 <= #1 _rLastLenEQ0;
rLenEQWords <= #1 _rLenEQWords;
rLenEQBufWords <= #1 _rLenEQBufWords;
end
always @ (*) begin
_rTxState = rTxState;
_rCopyBufWords = rCopyBufWords;
_rUseInit = rUseInit;
_rValsProp = ((rValsProp<<1) | rTxState[3]); // S_TXPORTWR_TX_ADJ_1
_rValsPropagated = (rValsProp == 6'd0);
_rLargeBuf = (SG_ELEM_LEN > rWords);
{_rCarry[0], _rAddr[15:0]} = (rTxState[1] ? SG_ELEM_ADDR[15:0] : (rAddr[15:0] + ({12{rTxState[6]}} & {rLen, 2'd0}))); // S_TXPORTWR_TX_WRITE
{_rCarry[1], _rAddr[31:16]} = (rTxState[1] ? SG_ELEM_ADDR[31:16] : (rAddr[31:16] + rCarry[0]));
{_rCarry[2], _rAddr[47:32]} = (rTxState[1] ? SG_ELEM_ADDR[47:32] : (rAddr[47:32] + rCarry[1]));
_rAddr[63:48] = (rTxState[1] ? SG_ELEM_ADDR[63:48] : (rAddr[63:48] + rCarry[2]));
_rSentWords = (rTxState[7] ? NEW_TXN_WORDS_RECVD : rSentWords) + ({10{rTxState[6]}} & rLen); // S_TXPORTWR_TX_WRITE
_rWords = (NEW_TXN_ACK ? NEW_TXN_LEN : (rWords - ({10{rTxState[6]}} & rLen))); // S_TXPORTWR_TX_WRITE
_rBufWordsInit = (rLargeBuf ? rWords : SG_ELEM_LEN);
_rBufWords = (rCopyBufWords ? rBufWordsInit : rBufWords) - ({10{rTxState[6]}} & rLen); // S_TXPORTWR_TX_WRITE
_rPageRem = wPageRem;
_rPageSpillInit = (rBufWordsInit > wPageRem);
_rPageSpill = (rBufWords > wPageRem);
_rPreLen = ((rPageSpillInit & rUseInit) | (rPageSpill & !rUseInit) ? rPageRem : rBufWords[10:0]);
_rMaxPayloadSize = CONFIG_MAX_PAYLOAD_SIZE;
_rMaxPayloadShift = (rMaxPayloadSize > 3'd4 ? 3'd4 : rMaxPayloadSize);
_rMaxPayload = (6'd32<<rMaxPayloadShift);
_rPayloadSpill = (rPreLen > rMaxPayload);
_rMaxLen = ((rMaxLen & !rValsProp[1]) | rTxState[6]); // S_TXPORTWR_TX_WRITE
_rLen = (rPayloadSpill | rMaxLen ? rMaxPayload : rPreLen[9:0]);
_rSendingWords = rSentWords + rLen;
_rAvail = (NEW_TXN_WORDS_RECVD >= rSendingWords);
_rTxnDone = ((rTxnDone<<1) | NEW_TXN_DONE);
_rLastLen = wLastLen;
_rLastLenEQ0 = (rLastLen == 10'd0);
_rLenEQWords = (rLen == rWords);
_rLenEQBufWords = (rLen == rBufWords);
case (rTxState)
`S_TXPORTWR_TX_IDLE: begin // Wait for channel write request
if (rMainState[4] & !rStarted) // S_TXPORTWR_MAIN_WRITE
_rTxState = `S_TXPORTWR_TX_BUF;
end
`S_TXPORTWR_TX_BUF: begin // Wait for buffer length and address
if (SG_ELEM_RDY)
_rTxState = `S_TXPORTWR_TX_ADJ_0;
end
`S_TXPORTWR_TX_ADJ_0: begin // Fix for large buffer
_rCopyBufWords = 1;
_rTxState = `S_TXPORTWR_TX_ADJ_1;
end
`S_TXPORTWR_TX_ADJ_1: begin // Check for page boundary crossing
_rCopyBufWords = 0;
_rUseInit = rCopyBufWords;
_rTxState = `S_TXPORTWR_TX_ADJ_2;
end
`S_TXPORTWR_TX_ADJ_2: begin // Wait for values to propagate
// Fix for page boundary crossing
// Check for max payload
// Fix for max payload
_rUseInit = 0;
if (rValsProp[2])
_rTxState = `S_TXPORTWR_TX_CHECK_DATA;
end
`S_TXPORTWR_TX_CHECK_DATA: begin // Wait for available data
if (rNotRequesting) begin
if (rAvail)
_rTxState = `S_TXPORTWR_TX_WRITE;
else if (rValsPropagated & rTxnDone[1])
_rTxState = (rLastLenEQ0 ? `S_TXPORTWR_TX_IDLE : `S_TXPORTWR_TX_WRITE_REM);
end
end
`S_TXPORTWR_TX_WRITE: begin // Send len and repeat or finish?
if (rLenEQWords)
_rTxState = `S_TXPORTWR_TX_IDLE;
else if (rLenEQBufWords)
_rTxState = `S_TXPORTWR_TX_BUF;
else
_rTxState = `S_TXPORTWR_TX_ADJ_1;
end
`S_TXPORTWR_TX_WRITE_REM: begin // Send remaining data and finish
_rTxState = `S_TXPORTWR_TX_IDLE;
end
default: begin
_rTxState = `S_TXPORTWR_TX_IDLE;
end
endcase
end
// Request TX transfers separately so that the TX FSM can continue calculating
// the next set of request parameters without having to wait for the TX_REQ_ACK.
always @ (posedge CLK) begin
rAckCount <= #1 (RST ? 10'd0 : _rAckCount);
rNotRequesting <= #1 (RST ? 1'd1 : _rNotRequesting);
rReqAddr <= #1 _rReqAddr;
rReqLen <= #1 _rReqLen;
rReqLast <= #1 _rReqLast;
rDone <= #1 _rDone;
rLastDoneRead <= #1 (RST ? 1'd1 : _rLastDoneRead);
end
always @ (*) begin
// Start signaling when the TX FSM is ready.
if (rTxState[6] | rTxState[7]) // S_TXPORTWR_TX_WRITE
_rNotRequesting = 0;
else
_rNotRequesting = (rNotRequesting | rTxReqAck);
// Pass off the rAddr & rLen when ready and wait for TX_REQ_ACK.
if (rTxState[6]) begin // S_TXPORTWR_TX_WRITE
_rReqAddr = rAddr;
_rReqLen = rLen;
_rReqLast = rLenEQWords;
end
else if (rTxState[7]) begin // S_TXPORTWR_TX_WRITE_REM
_rReqAddr = rAddr;
_rReqLen = rLastLen;
_rReqLast = 1;
end
else begin
_rReqAddr = rReqAddr;
_rReqLen = rReqLen;
_rReqLast = rReqLast;
end
// Track TX_REQ_ACK and TX_SENT to determine when the transaction is over.
_rDone = (rAckCount == 10'd0);
if (rMainState[0]) // S_TXPORTWR_MAIN_IDLE
_rAckCount = 0;
else
_rAckCount = rAckCount + rTxState[6] + rTxState[7] - rTxSent; // S_TXPORTWR_TX_WRITE, S_TXPORTWR_TX_WRITE_REM
// Track when the user reads the actual transfer amount.
_rLastDoneRead = (rMainState[6] ? 1'd0 : (rLastDoneRead | rTxnDoneAck)); // S_TXPORTWR_MAIN_SIG_DONE
end
// Facilitate sending a TXN_DONE when we receive a TXN_ACK after the transaction
// has begun sending. This will happen when the workstation detects that it has
// sent/used all its currently mapped scatter gather elements, but it's not enough
// to complete the transaction. The TXN_DONE will let the workstation know it can
// release the current scatter gather mappings and allocate new ones.
always @ (posedge CLK) begin
rPartialDone <= #1 _rPartialDone;
rReqPartialDone <= #1 (RST ? 1'd0 : _rReqPartialDone);
end
always @ (*) begin
// Signal TXN_DONE after we've recieved the (seemingly superfluous) TXN_ACK,
// we have no outstanding transfer requests, we're not currently requesting a
// transfer, and there are no more scatter gather elements.
_rPartialDone = (rReqPartialDone & rDone & rNotRequesting & SG_ELEM_EMPTY & rTxState[1]); // S_TXPORTWR_TX_BUF
// Keep track of (seemingly superfluous) TXN_ACK requests.
if ((rReqPartialDone & rDone & rNotRequesting & SG_ELEM_EMPTY & rTxState[1]) | rMainState[0]) // S_TXPORTWR_MAIN_IDLE
_rReqPartialDone = 0;
else
_rReqPartialDone = (rReqPartialDone | (rTxnAck & !rMainState[3])); // !S_TXPORTWR_MAIN_NEW_ACK
end
/*
wire [35:0] wControl0;
chipscope_icon_1 cs_icon(
.CONTROL0(wControl0)
);
chipscope_ila_t8_512 a0(
.CLK(CLK),
.CONTROL(wControl0),
.TRIG0({rTxState[6] | rTxState[7] | rTxSent, rAckCount[6:0]}),
.DATA({280'd0,
NEW_TXN_WORDS_RECVD, // 32
rSendingWords, // 32
rAvail, // 1
rNotRequesting, // 1
NEW_TXN_LAST, // 1
NEW_TXN_LEN, // 32
NEW_TXN_OFF, // 31
NEW_TXN, // 1
rAckCount, // 10
rLastDoneRead, // 1
rWords, // 32
rBufWords, // 32
rLen, // 10
rTxState, // 8
rMainState}) // 8
);
*/
endmodule
|
// ----------------------------------------------------------------------
// Copyright (c) 2016, The Regents of the University of California All
// rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// * Neither the name of The Regents of the University of California
// nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL REGENTS OF THE
// UNIVERSITY OF CALIFORNIA BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
// OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
// TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
// ----------------------------------------------------------------------
//----------------------------------------------------------------------------
// Filename: tx_port_writer.v
// Version: 1.00.a
// Verilog Standard: Verilog-2001
// Description: Handles receiving new transaction events and data, and
// making requests to tx engine.
// for the RIFFA channel.
// Author: Matt Jacobsen
// History: @mattj: Version 2.0
//-----------------------------------------------------------------------------
`define S_TXPORTWR_MAIN_IDLE 8'b0000_0001
`define S_TXPORTWR_MAIN_CHECK 8'b0000_0010
`define S_TXPORTWR_MAIN_SIG_NEW 8'b0000_0100
`define S_TXPORTWR_MAIN_NEW_ACK 8'b0000_1000
`define S_TXPORTWR_MAIN_WRITE 8'b0001_0000
`define S_TXPORTWR_MAIN_DONE 8'b0010_0000
`define S_TXPORTWR_MAIN_SIG_DONE 8'b0100_0000
`define S_TXPORTWR_MAIN_RESET 8'b1000_0000
`define S_TXPORTWR_TX_IDLE 8'b0000_0001
`define S_TXPORTWR_TX_BUF 8'b0000_0010
`define S_TXPORTWR_TX_ADJ_0 8'b0000_0100
`define S_TXPORTWR_TX_ADJ_1 8'b0000_1000
`define S_TXPORTWR_TX_ADJ_2 8'b0001_0000
`define S_TXPORTWR_TX_CHECK_DATA 8'b0010_0000
`define S_TXPORTWR_TX_WRITE 8'b0100_0000
`define S_TXPORTWR_TX_WRITE_REM 8'b1000_0000
`timescale 1ns/1ns
module tx_port_writer (
input CLK,
input RST,
input [2:0] CONFIG_MAX_PAYLOAD_SIZE, // Maximum write payload: 000=128B, 001=256B, 010=512B, 011=1024B
output TXN, // Write transaction notification
input TXN_ACK, // Write transaction acknowledged
output [31:0] TXN_LEN, // Write transaction length
output [31:0] TXN_OFF_LAST, // Write transaction offset/last
output [31:0] TXN_DONE_LEN, // Write transaction actual transfer length
output TXN_DONE, // Write transaction done
output TXN_ERR, // Write transaction encountered an error
input TXN_DONE_ACK, // Write transaction actual transfer length read
input NEW_TXN, // Transaction parameters are valid
output NEW_TXN_ACK, // Transaction parameter read, continue
input NEW_TXN_LAST, // Channel last write
input [31:0] NEW_TXN_LEN, // Channel write length (in 32 bit words)
input [30:0] NEW_TXN_OFF, // Channel write offset
input [31:0] NEW_TXN_WORDS_RECVD, // Count of data words received in transaction
input NEW_TXN_DONE, // Transaction is closed
input [63:0] SG_ELEM_ADDR, // Scatter gather element address
input [31:0] SG_ELEM_LEN, // Scatter gather element length (in words)
input SG_ELEM_RDY, // Scatter gather element ready
input SG_ELEM_EMPTY, // Scatter gather elements empty
output SG_ELEM_REN, // Scatter gather element read enable
output SG_RST, // Scatter gather data reset
input SG_ERR, // Scatter gather read encountered an error
output TX_REQ, // Outgoing write request
input TX_REQ_ACK, // Outgoing write request acknowledged
output [63:0] TX_ADDR, // Outgoing write high address
output [9:0] TX_LEN, // Outgoing write length (in 32 bit words)
output TX_LAST, // Outgoing write is last request for transaction
input TX_SENT // Outgoing write complete
);
`include "functions.vh"
(* syn_encoding = "user" *)
(* fsm_encoding = "user" *)
reg [7:0] rMainState=`S_TXPORTWR_MAIN_IDLE, _rMainState=`S_TXPORTWR_MAIN_IDLE;
reg [31:0] rOffLast=0, _rOffLast=0;
reg rWordsEQ0=0, _rWordsEQ0=0;
reg rStarted=0, _rStarted=0;
reg [31:0] rDoneLen=0, _rDoneLen=0;
reg rSgErr=0, _rSgErr=0;
reg rTxErrd=0, _rTxErrd=0;
reg rTxnAck=0, _rTxnAck=0;
(* syn_encoding = "user" *)
(* fsm_encoding = "user" *)
reg [7:0] rTxState=`S_TXPORTWR_TX_IDLE, _rTxState=`S_TXPORTWR_TX_IDLE;
reg [31:0] rSentWords=0, _rSentWords=0;
reg [31:0] rWords=0, _rWords=0;
reg [31:0] rBufWords=0, _rBufWords=0;
reg [31:0] rBufWordsInit=0, _rBufWordsInit=0;
reg rLargeBuf=0, _rLargeBuf=0;
reg [63:0] rAddr=64'd0, _rAddr=64'd0;
reg [2:0] rCarry=0, _rCarry=0;
reg rValsPropagated=0, _rValsPropagated=0;
reg [5:0] rValsProp=0, _rValsProp=0;
reg rCopyBufWords=0, _rCopyBufWords=0;
reg rUseInit=0, _rUseInit=0;
reg [10:0] rPageRem=0, _rPageRem=0;
reg rPageSpill=0, _rPageSpill=0;
reg rPageSpillInit=0, _rPageSpillInit=0;
reg [10:0] rPreLen=0, _rPreLen=0;
reg [2:0] rMaxPayloadSize=0, _rMaxPayloadSize=0;
reg [2:0] rMaxPayloadShift=0, _rMaxPayloadShift=0;
reg [9:0] rMaxPayload=0, _rMaxPayload=0;
reg rPayloadSpill=0, _rPayloadSpill=0;
reg rMaxLen=1, _rMaxLen=1;
reg [9:0] rLen=0, _rLen=0;
reg [31:0] rSendingWords=0, _rSendingWords=0;
reg rAvail=0, _rAvail=0;
reg [1:0] rTxnDone=0, _rTxnDone=0;
reg [9:0] rLastLen=0, _rLastLen=0;
reg rLastLenEQ0=0, _rLastLenEQ0=0;
reg rLenEQWords=0, _rLenEQWords=0;
reg rLenEQBufWords=0, _rLenEQBufWords=0;
reg rNotRequesting=1, _rNotRequesting=1;
reg [63:0] rReqAddr=64'd0, _rReqAddr=64'd0;
reg [9:0] rReqLen=0, _rReqLen=0;
reg rReqLast=0, _rReqLast=0;
reg rTxReqAck=0, _rTxReqAck=0;
reg rDone=0, _rDone=0;
reg [9:0] rAckCount=0, _rAckCount=0;
reg rTxSent=0, _rTxSent=0;
reg rLastDoneRead=1, _rLastDoneRead=1;
reg rTxnDoneAck=0, _rTxnDoneAck=0;
reg rReqPartialDone=0, _rReqPartialDone=0;
reg rPartialDone=0, _rPartialDone=0;
assign NEW_TXN_ACK = rMainState[1]; // S_TXPORTWR_MAIN_CHECK
assign TXN = rMainState[2]; // S_TXPORTWR_MAIN_SIG_NEW
assign TXN_DONE = (rMainState[6] | rPartialDone); // S_TXPORTWR_MAIN_SIG_DONE
assign TXN_LEN = rWords;
assign TXN_OFF_LAST = rOffLast;
assign TXN_DONE_LEN = rDoneLen;
assign TXN_ERR = rTxErrd;
assign SG_ELEM_REN = rTxState[2]; // S_TXPORTWR_TX_ADJ_0
assign SG_RST = rMainState[3]; // S_TXPORTWR_MAIN_NEW_ACK
assign TX_REQ = !rNotRequesting;
assign TX_ADDR = rReqAddr;
assign TX_LEN = rReqLen;
assign TX_LAST = rReqLast;
// Buffer the input signals that come from outside the tx_port.
always @ (posedge CLK) begin
rTxnAck <= #1 (RST ? 1'd0 : _rTxnAck);
rTxnDoneAck <= #1 (RST ? 1'd0 : _rTxnDoneAck);
rSgErr <= #1 (RST ? 1'd0 : _rSgErr);
rTxReqAck <= #1 (RST ? 1'd0 : _rTxReqAck);
rTxSent <= #1 (RST ? 1'd0 : _rTxSent);
end
always @ (*) begin
_rTxnAck = TXN_ACK;
_rTxnDoneAck = TXN_DONE_ACK;
_rSgErr = SG_ERR;
_rTxReqAck = TX_REQ_ACK;
_rTxSent = TX_SENT;
end
// Wait for a NEW_TXN request. Then request transfers until all the data is sent
// or until the specified length is reached. Then signal TXN_DONE.
always @ (posedge CLK) begin
rMainState <= #1 (RST ? `S_TXPORTWR_MAIN_IDLE : _rMainState);
rOffLast <= #1 _rOffLast;
rWordsEQ0 <= #1 _rWordsEQ0;
rStarted <= #1 _rStarted;
rDoneLen <= #1 (RST ? 0 : _rDoneLen);
rTxErrd <= #1 (RST ? 1'd0 : _rTxErrd);
end
always @ (*) begin
_rMainState = rMainState;
_rOffLast = rOffLast;
_rWordsEQ0 = rWordsEQ0;
_rStarted = rStarted;
_rDoneLen = rDoneLen;
_rTxErrd = rTxErrd;
case (rMainState)
`S_TXPORTWR_MAIN_IDLE: begin // Wait for channel write request
_rStarted = 0;
_rWordsEQ0 = (NEW_TXN_LEN == 0);
_rOffLast = {NEW_TXN_OFF, NEW_TXN_LAST};
if (NEW_TXN)
_rMainState = `S_TXPORTWR_MAIN_CHECK;
end
`S_TXPORTWR_MAIN_CHECK: begin // Continue with transaction?
if (rOffLast[0] | !rWordsEQ0)
_rMainState = `S_TXPORTWR_MAIN_SIG_NEW;
else
_rMainState = `S_TXPORTWR_MAIN_RESET;
end
`S_TXPORTWR_MAIN_SIG_NEW: begin // Signal new write
_rMainState = `S_TXPORTWR_MAIN_NEW_ACK;
end
`S_TXPORTWR_MAIN_NEW_ACK: begin // Wait for acknowledgement
if (rTxnAck) // ACK'd on PC read of TXN length
_rMainState = (rWordsEQ0 ? `S_TXPORTWR_MAIN_SIG_DONE : `S_TXPORTWR_MAIN_WRITE);
end
`S_TXPORTWR_MAIN_WRITE: begin // Start writing and wait for all writes to complete
_rStarted = (rStarted | rTxState[1]); // S_TXPORTWR_TX_BUF
_rTxErrd = (rTxErrd | rSgErr);
if (rTxState[0] & rStarted) // S_TXPORTWR_TX_IDLE
_rMainState = `S_TXPORTWR_MAIN_DONE;
end
`S_TXPORTWR_MAIN_DONE: begin // Wait for the last transaction to complete
if (rDone & rLastDoneRead) begin
_rDoneLen = rSentWords;
_rMainState = `S_TXPORTWR_MAIN_SIG_DONE;
end
end
`S_TXPORTWR_MAIN_SIG_DONE: begin // Signal the done port
_rTxErrd = 0;
_rMainState = `S_TXPORTWR_MAIN_RESET;
end
`S_TXPORTWR_MAIN_RESET: begin // Wait for the channel tx to drop
if (NEW_TXN_DONE)
_rMainState = `S_TXPORTWR_MAIN_IDLE;
end
default: begin
_rMainState = `S_TXPORTWR_MAIN_IDLE;
end
endcase
end
// Manage sending TX requests to the TX engine. Transfers will be limited
// by each scatter gather buffer's size, max payload size, and must not
// cross a (4KB) page boundary. The request is only made if there is sufficient
// data already written to the buffer.
wire [9:0] wLastLen = (NEW_TXN_WORDS_RECVD - rSentWords);
wire [9:0] wAddrLoInv = ~rAddr[11:2];
wire [10:0] wPageRem = (wAddrLoInv + 1'd1);
always @ (posedge CLK) begin
rTxState <= #1 (RST | rSgErr ? `S_TXPORTWR_TX_IDLE : _rTxState);
rSentWords <= #1 (rMainState[0] ? 0 : _rSentWords);
rWords <= #1 _rWords;
rBufWords <= #1 _rBufWords;
rBufWordsInit <= #1 _rBufWordsInit;
rAddr <= #1 _rAddr;
rCarry <= #1 _rCarry;
rValsPropagated <= #1 _rValsPropagated;
rValsProp <= #1 _rValsProp;
rLargeBuf <= #1 _rLargeBuf;
rPageRem <= #1 _rPageRem;
rPageSpill <= #1 _rPageSpill;
rPageSpillInit <= #1 _rPageSpillInit;
rCopyBufWords <= #1 _rCopyBufWords;
rUseInit <= #1 _rUseInit;
rPreLen <= #1 _rPreLen;
rMaxPayloadSize <= #1 _rMaxPayloadSize;
rMaxPayloadShift <= #1 _rMaxPayloadShift;
rMaxPayload <= #1 _rMaxPayload;
rPayloadSpill <= #1 _rPayloadSpill;
rMaxLen <= #1 (RST ? 1'd1 : _rMaxLen);
rLen <= #1 _rLen;
rSendingWords <= #1 _rSendingWords;
rAvail <= #1 _rAvail;
rTxnDone <= #1 _rTxnDone;
rLastLen <= #1 _rLastLen;
rLastLenEQ0 <= #1 _rLastLenEQ0;
rLenEQWords <= #1 _rLenEQWords;
rLenEQBufWords <= #1 _rLenEQBufWords;
end
always @ (*) begin
_rTxState = rTxState;
_rCopyBufWords = rCopyBufWords;
_rUseInit = rUseInit;
_rValsProp = ((rValsProp<<1) | rTxState[3]); // S_TXPORTWR_TX_ADJ_1
_rValsPropagated = (rValsProp == 6'd0);
_rLargeBuf = (SG_ELEM_LEN > rWords);
{_rCarry[0], _rAddr[15:0]} = (rTxState[1] ? SG_ELEM_ADDR[15:0] : (rAddr[15:0] + ({12{rTxState[6]}} & {rLen, 2'd0}))); // S_TXPORTWR_TX_WRITE
{_rCarry[1], _rAddr[31:16]} = (rTxState[1] ? SG_ELEM_ADDR[31:16] : (rAddr[31:16] + rCarry[0]));
{_rCarry[2], _rAddr[47:32]} = (rTxState[1] ? SG_ELEM_ADDR[47:32] : (rAddr[47:32] + rCarry[1]));
_rAddr[63:48] = (rTxState[1] ? SG_ELEM_ADDR[63:48] : (rAddr[63:48] + rCarry[2]));
_rSentWords = (rTxState[7] ? NEW_TXN_WORDS_RECVD : rSentWords) + ({10{rTxState[6]}} & rLen); // S_TXPORTWR_TX_WRITE
_rWords = (NEW_TXN_ACK ? NEW_TXN_LEN : (rWords - ({10{rTxState[6]}} & rLen))); // S_TXPORTWR_TX_WRITE
_rBufWordsInit = (rLargeBuf ? rWords : SG_ELEM_LEN);
_rBufWords = (rCopyBufWords ? rBufWordsInit : rBufWords) - ({10{rTxState[6]}} & rLen); // S_TXPORTWR_TX_WRITE
_rPageRem = wPageRem;
_rPageSpillInit = (rBufWordsInit > wPageRem);
_rPageSpill = (rBufWords > wPageRem);
_rPreLen = ((rPageSpillInit & rUseInit) | (rPageSpill & !rUseInit) ? rPageRem : rBufWords[10:0]);
_rMaxPayloadSize = CONFIG_MAX_PAYLOAD_SIZE;
_rMaxPayloadShift = (rMaxPayloadSize > 3'd4 ? 3'd4 : rMaxPayloadSize);
_rMaxPayload = (6'd32<<rMaxPayloadShift);
_rPayloadSpill = (rPreLen > rMaxPayload);
_rMaxLen = ((rMaxLen & !rValsProp[1]) | rTxState[6]); // S_TXPORTWR_TX_WRITE
_rLen = (rPayloadSpill | rMaxLen ? rMaxPayload : rPreLen[9:0]);
_rSendingWords = rSentWords + rLen;
_rAvail = (NEW_TXN_WORDS_RECVD >= rSendingWords);
_rTxnDone = ((rTxnDone<<1) | NEW_TXN_DONE);
_rLastLen = wLastLen;
_rLastLenEQ0 = (rLastLen == 10'd0);
_rLenEQWords = (rLen == rWords);
_rLenEQBufWords = (rLen == rBufWords);
case (rTxState)
`S_TXPORTWR_TX_IDLE: begin // Wait for channel write request
if (rMainState[4] & !rStarted) // S_TXPORTWR_MAIN_WRITE
_rTxState = `S_TXPORTWR_TX_BUF;
end
`S_TXPORTWR_TX_BUF: begin // Wait for buffer length and address
if (SG_ELEM_RDY)
_rTxState = `S_TXPORTWR_TX_ADJ_0;
end
`S_TXPORTWR_TX_ADJ_0: begin // Fix for large buffer
_rCopyBufWords = 1;
_rTxState = `S_TXPORTWR_TX_ADJ_1;
end
`S_TXPORTWR_TX_ADJ_1: begin // Check for page boundary crossing
_rCopyBufWords = 0;
_rUseInit = rCopyBufWords;
_rTxState = `S_TXPORTWR_TX_ADJ_2;
end
`S_TXPORTWR_TX_ADJ_2: begin // Wait for values to propagate
// Fix for page boundary crossing
// Check for max payload
// Fix for max payload
_rUseInit = 0;
if (rValsProp[2])
_rTxState = `S_TXPORTWR_TX_CHECK_DATA;
end
`S_TXPORTWR_TX_CHECK_DATA: begin // Wait for available data
if (rNotRequesting) begin
if (rAvail)
_rTxState = `S_TXPORTWR_TX_WRITE;
else if (rValsPropagated & rTxnDone[1])
_rTxState = (rLastLenEQ0 ? `S_TXPORTWR_TX_IDLE : `S_TXPORTWR_TX_WRITE_REM);
end
end
`S_TXPORTWR_TX_WRITE: begin // Send len and repeat or finish?
if (rLenEQWords)
_rTxState = `S_TXPORTWR_TX_IDLE;
else if (rLenEQBufWords)
_rTxState = `S_TXPORTWR_TX_BUF;
else
_rTxState = `S_TXPORTWR_TX_ADJ_1;
end
`S_TXPORTWR_TX_WRITE_REM: begin // Send remaining data and finish
_rTxState = `S_TXPORTWR_TX_IDLE;
end
default: begin
_rTxState = `S_TXPORTWR_TX_IDLE;
end
endcase
end
// Request TX transfers separately so that the TX FSM can continue calculating
// the next set of request parameters without having to wait for the TX_REQ_ACK.
always @ (posedge CLK) begin
rAckCount <= #1 (RST ? 10'd0 : _rAckCount);
rNotRequesting <= #1 (RST ? 1'd1 : _rNotRequesting);
rReqAddr <= #1 _rReqAddr;
rReqLen <= #1 _rReqLen;
rReqLast <= #1 _rReqLast;
rDone <= #1 _rDone;
rLastDoneRead <= #1 (RST ? 1'd1 : _rLastDoneRead);
end
always @ (*) begin
// Start signaling when the TX FSM is ready.
if (rTxState[6] | rTxState[7]) // S_TXPORTWR_TX_WRITE
_rNotRequesting = 0;
else
_rNotRequesting = (rNotRequesting | rTxReqAck);
// Pass off the rAddr & rLen when ready and wait for TX_REQ_ACK.
if (rTxState[6]) begin // S_TXPORTWR_TX_WRITE
_rReqAddr = rAddr;
_rReqLen = rLen;
_rReqLast = rLenEQWords;
end
else if (rTxState[7]) begin // S_TXPORTWR_TX_WRITE_REM
_rReqAddr = rAddr;
_rReqLen = rLastLen;
_rReqLast = 1;
end
else begin
_rReqAddr = rReqAddr;
_rReqLen = rReqLen;
_rReqLast = rReqLast;
end
// Track TX_REQ_ACK and TX_SENT to determine when the transaction is over.
_rDone = (rAckCount == 10'd0);
if (rMainState[0]) // S_TXPORTWR_MAIN_IDLE
_rAckCount = 0;
else
_rAckCount = rAckCount + rTxState[6] + rTxState[7] - rTxSent; // S_TXPORTWR_TX_WRITE, S_TXPORTWR_TX_WRITE_REM
// Track when the user reads the actual transfer amount.
_rLastDoneRead = (rMainState[6] ? 1'd0 : (rLastDoneRead | rTxnDoneAck)); // S_TXPORTWR_MAIN_SIG_DONE
end
// Facilitate sending a TXN_DONE when we receive a TXN_ACK after the transaction
// has begun sending. This will happen when the workstation detects that it has
// sent/used all its currently mapped scatter gather elements, but it's not enough
// to complete the transaction. The TXN_DONE will let the workstation know it can
// release the current scatter gather mappings and allocate new ones.
always @ (posedge CLK) begin
rPartialDone <= #1 _rPartialDone;
rReqPartialDone <= #1 (RST ? 1'd0 : _rReqPartialDone);
end
always @ (*) begin
// Signal TXN_DONE after we've recieved the (seemingly superfluous) TXN_ACK,
// we have no outstanding transfer requests, we're not currently requesting a
// transfer, and there are no more scatter gather elements.
_rPartialDone = (rReqPartialDone & rDone & rNotRequesting & SG_ELEM_EMPTY & rTxState[1]); // S_TXPORTWR_TX_BUF
// Keep track of (seemingly superfluous) TXN_ACK requests.
if ((rReqPartialDone & rDone & rNotRequesting & SG_ELEM_EMPTY & rTxState[1]) | rMainState[0]) // S_TXPORTWR_MAIN_IDLE
_rReqPartialDone = 0;
else
_rReqPartialDone = (rReqPartialDone | (rTxnAck & !rMainState[3])); // !S_TXPORTWR_MAIN_NEW_ACK
end
/*
wire [35:0] wControl0;
chipscope_icon_1 cs_icon(
.CONTROL0(wControl0)
);
chipscope_ila_t8_512 a0(
.CLK(CLK),
.CONTROL(wControl0),
.TRIG0({rTxState[6] | rTxState[7] | rTxSent, rAckCount[6:0]}),
.DATA({280'd0,
NEW_TXN_WORDS_RECVD, // 32
rSendingWords, // 32
rAvail, // 1
rNotRequesting, // 1
NEW_TXN_LAST, // 1
NEW_TXN_LEN, // 32
NEW_TXN_OFF, // 31
NEW_TXN, // 1
rAckCount, // 10
rLastDoneRead, // 1
rWords, // 32
rBufWords, // 32
rLen, // 10
rTxState, // 8
rMainState}) // 8
);
*/
endmodule
|
// ----------------------------------------------------------------------
// Copyright (c) 2016, The Regents of the University of California All
// rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// * Neither the name of The Regents of the University of California
// nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL REGENTS OF THE
// UNIVERSITY OF CALIFORNIA BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
// OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
// TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
// ----------------------------------------------------------------------
//----------------------------------------------------------------------------
// Filename: tx_port_writer.v
// Version: 1.00.a
// Verilog Standard: Verilog-2001
// Description: Handles receiving new transaction events and data, and
// making requests to tx engine.
// for the RIFFA channel.
// Author: Matt Jacobsen
// History: @mattj: Version 2.0
//-----------------------------------------------------------------------------
`define S_TXPORTWR_MAIN_IDLE 8'b0000_0001
`define S_TXPORTWR_MAIN_CHECK 8'b0000_0010
`define S_TXPORTWR_MAIN_SIG_NEW 8'b0000_0100
`define S_TXPORTWR_MAIN_NEW_ACK 8'b0000_1000
`define S_TXPORTWR_MAIN_WRITE 8'b0001_0000
`define S_TXPORTWR_MAIN_DONE 8'b0010_0000
`define S_TXPORTWR_MAIN_SIG_DONE 8'b0100_0000
`define S_TXPORTWR_MAIN_RESET 8'b1000_0000
`define S_TXPORTWR_TX_IDLE 8'b0000_0001
`define S_TXPORTWR_TX_BUF 8'b0000_0010
`define S_TXPORTWR_TX_ADJ_0 8'b0000_0100
`define S_TXPORTWR_TX_ADJ_1 8'b0000_1000
`define S_TXPORTWR_TX_ADJ_2 8'b0001_0000
`define S_TXPORTWR_TX_CHECK_DATA 8'b0010_0000
`define S_TXPORTWR_TX_WRITE 8'b0100_0000
`define S_TXPORTWR_TX_WRITE_REM 8'b1000_0000
`timescale 1ns/1ns
module tx_port_writer (
input CLK,
input RST,
input [2:0] CONFIG_MAX_PAYLOAD_SIZE, // Maximum write payload: 000=128B, 001=256B, 010=512B, 011=1024B
output TXN, // Write transaction notification
input TXN_ACK, // Write transaction acknowledged
output [31:0] TXN_LEN, // Write transaction length
output [31:0] TXN_OFF_LAST, // Write transaction offset/last
output [31:0] TXN_DONE_LEN, // Write transaction actual transfer length
output TXN_DONE, // Write transaction done
output TXN_ERR, // Write transaction encountered an error
input TXN_DONE_ACK, // Write transaction actual transfer length read
input NEW_TXN, // Transaction parameters are valid
output NEW_TXN_ACK, // Transaction parameter read, continue
input NEW_TXN_LAST, // Channel last write
input [31:0] NEW_TXN_LEN, // Channel write length (in 32 bit words)
input [30:0] NEW_TXN_OFF, // Channel write offset
input [31:0] NEW_TXN_WORDS_RECVD, // Count of data words received in transaction
input NEW_TXN_DONE, // Transaction is closed
input [63:0] SG_ELEM_ADDR, // Scatter gather element address
input [31:0] SG_ELEM_LEN, // Scatter gather element length (in words)
input SG_ELEM_RDY, // Scatter gather element ready
input SG_ELEM_EMPTY, // Scatter gather elements empty
output SG_ELEM_REN, // Scatter gather element read enable
output SG_RST, // Scatter gather data reset
input SG_ERR, // Scatter gather read encountered an error
output TX_REQ, // Outgoing write request
input TX_REQ_ACK, // Outgoing write request acknowledged
output [63:0] TX_ADDR, // Outgoing write high address
output [9:0] TX_LEN, // Outgoing write length (in 32 bit words)
output TX_LAST, // Outgoing write is last request for transaction
input TX_SENT // Outgoing write complete
);
`include "functions.vh"
(* syn_encoding = "user" *)
(* fsm_encoding = "user" *)
reg [7:0] rMainState=`S_TXPORTWR_MAIN_IDLE, _rMainState=`S_TXPORTWR_MAIN_IDLE;
reg [31:0] rOffLast=0, _rOffLast=0;
reg rWordsEQ0=0, _rWordsEQ0=0;
reg rStarted=0, _rStarted=0;
reg [31:0] rDoneLen=0, _rDoneLen=0;
reg rSgErr=0, _rSgErr=0;
reg rTxErrd=0, _rTxErrd=0;
reg rTxnAck=0, _rTxnAck=0;
(* syn_encoding = "user" *)
(* fsm_encoding = "user" *)
reg [7:0] rTxState=`S_TXPORTWR_TX_IDLE, _rTxState=`S_TXPORTWR_TX_IDLE;
reg [31:0] rSentWords=0, _rSentWords=0;
reg [31:0] rWords=0, _rWords=0;
reg [31:0] rBufWords=0, _rBufWords=0;
reg [31:0] rBufWordsInit=0, _rBufWordsInit=0;
reg rLargeBuf=0, _rLargeBuf=0;
reg [63:0] rAddr=64'd0, _rAddr=64'd0;
reg [2:0] rCarry=0, _rCarry=0;
reg rValsPropagated=0, _rValsPropagated=0;
reg [5:0] rValsProp=0, _rValsProp=0;
reg rCopyBufWords=0, _rCopyBufWords=0;
reg rUseInit=0, _rUseInit=0;
reg [10:0] rPageRem=0, _rPageRem=0;
reg rPageSpill=0, _rPageSpill=0;
reg rPageSpillInit=0, _rPageSpillInit=0;
reg [10:0] rPreLen=0, _rPreLen=0;
reg [2:0] rMaxPayloadSize=0, _rMaxPayloadSize=0;
reg [2:0] rMaxPayloadShift=0, _rMaxPayloadShift=0;
reg [9:0] rMaxPayload=0, _rMaxPayload=0;
reg rPayloadSpill=0, _rPayloadSpill=0;
reg rMaxLen=1, _rMaxLen=1;
reg [9:0] rLen=0, _rLen=0;
reg [31:0] rSendingWords=0, _rSendingWords=0;
reg rAvail=0, _rAvail=0;
reg [1:0] rTxnDone=0, _rTxnDone=0;
reg [9:0] rLastLen=0, _rLastLen=0;
reg rLastLenEQ0=0, _rLastLenEQ0=0;
reg rLenEQWords=0, _rLenEQWords=0;
reg rLenEQBufWords=0, _rLenEQBufWords=0;
reg rNotRequesting=1, _rNotRequesting=1;
reg [63:0] rReqAddr=64'd0, _rReqAddr=64'd0;
reg [9:0] rReqLen=0, _rReqLen=0;
reg rReqLast=0, _rReqLast=0;
reg rTxReqAck=0, _rTxReqAck=0;
reg rDone=0, _rDone=0;
reg [9:0] rAckCount=0, _rAckCount=0;
reg rTxSent=0, _rTxSent=0;
reg rLastDoneRead=1, _rLastDoneRead=1;
reg rTxnDoneAck=0, _rTxnDoneAck=0;
reg rReqPartialDone=0, _rReqPartialDone=0;
reg rPartialDone=0, _rPartialDone=0;
assign NEW_TXN_ACK = rMainState[1]; // S_TXPORTWR_MAIN_CHECK
assign TXN = rMainState[2]; // S_TXPORTWR_MAIN_SIG_NEW
assign TXN_DONE = (rMainState[6] | rPartialDone); // S_TXPORTWR_MAIN_SIG_DONE
assign TXN_LEN = rWords;
assign TXN_OFF_LAST = rOffLast;
assign TXN_DONE_LEN = rDoneLen;
assign TXN_ERR = rTxErrd;
assign SG_ELEM_REN = rTxState[2]; // S_TXPORTWR_TX_ADJ_0
assign SG_RST = rMainState[3]; // S_TXPORTWR_MAIN_NEW_ACK
assign TX_REQ = !rNotRequesting;
assign TX_ADDR = rReqAddr;
assign TX_LEN = rReqLen;
assign TX_LAST = rReqLast;
// Buffer the input signals that come from outside the tx_port.
always @ (posedge CLK) begin
rTxnAck <= #1 (RST ? 1'd0 : _rTxnAck);
rTxnDoneAck <= #1 (RST ? 1'd0 : _rTxnDoneAck);
rSgErr <= #1 (RST ? 1'd0 : _rSgErr);
rTxReqAck <= #1 (RST ? 1'd0 : _rTxReqAck);
rTxSent <= #1 (RST ? 1'd0 : _rTxSent);
end
always @ (*) begin
_rTxnAck = TXN_ACK;
_rTxnDoneAck = TXN_DONE_ACK;
_rSgErr = SG_ERR;
_rTxReqAck = TX_REQ_ACK;
_rTxSent = TX_SENT;
end
// Wait for a NEW_TXN request. Then request transfers until all the data is sent
// or until the specified length is reached. Then signal TXN_DONE.
always @ (posedge CLK) begin
rMainState <= #1 (RST ? `S_TXPORTWR_MAIN_IDLE : _rMainState);
rOffLast <= #1 _rOffLast;
rWordsEQ0 <= #1 _rWordsEQ0;
rStarted <= #1 _rStarted;
rDoneLen <= #1 (RST ? 0 : _rDoneLen);
rTxErrd <= #1 (RST ? 1'd0 : _rTxErrd);
end
always @ (*) begin
_rMainState = rMainState;
_rOffLast = rOffLast;
_rWordsEQ0 = rWordsEQ0;
_rStarted = rStarted;
_rDoneLen = rDoneLen;
_rTxErrd = rTxErrd;
case (rMainState)
`S_TXPORTWR_MAIN_IDLE: begin // Wait for channel write request
_rStarted = 0;
_rWordsEQ0 = (NEW_TXN_LEN == 0);
_rOffLast = {NEW_TXN_OFF, NEW_TXN_LAST};
if (NEW_TXN)
_rMainState = `S_TXPORTWR_MAIN_CHECK;
end
`S_TXPORTWR_MAIN_CHECK: begin // Continue with transaction?
if (rOffLast[0] | !rWordsEQ0)
_rMainState = `S_TXPORTWR_MAIN_SIG_NEW;
else
_rMainState = `S_TXPORTWR_MAIN_RESET;
end
`S_TXPORTWR_MAIN_SIG_NEW: begin // Signal new write
_rMainState = `S_TXPORTWR_MAIN_NEW_ACK;
end
`S_TXPORTWR_MAIN_NEW_ACK: begin // Wait for acknowledgement
if (rTxnAck) // ACK'd on PC read of TXN length
_rMainState = (rWordsEQ0 ? `S_TXPORTWR_MAIN_SIG_DONE : `S_TXPORTWR_MAIN_WRITE);
end
`S_TXPORTWR_MAIN_WRITE: begin // Start writing and wait for all writes to complete
_rStarted = (rStarted | rTxState[1]); // S_TXPORTWR_TX_BUF
_rTxErrd = (rTxErrd | rSgErr);
if (rTxState[0] & rStarted) // S_TXPORTWR_TX_IDLE
_rMainState = `S_TXPORTWR_MAIN_DONE;
end
`S_TXPORTWR_MAIN_DONE: begin // Wait for the last transaction to complete
if (rDone & rLastDoneRead) begin
_rDoneLen = rSentWords;
_rMainState = `S_TXPORTWR_MAIN_SIG_DONE;
end
end
`S_TXPORTWR_MAIN_SIG_DONE: begin // Signal the done port
_rTxErrd = 0;
_rMainState = `S_TXPORTWR_MAIN_RESET;
end
`S_TXPORTWR_MAIN_RESET: begin // Wait for the channel tx to drop
if (NEW_TXN_DONE)
_rMainState = `S_TXPORTWR_MAIN_IDLE;
end
default: begin
_rMainState = `S_TXPORTWR_MAIN_IDLE;
end
endcase
end
// Manage sending TX requests to the TX engine. Transfers will be limited
// by each scatter gather buffer's size, max payload size, and must not
// cross a (4KB) page boundary. The request is only made if there is sufficient
// data already written to the buffer.
wire [9:0] wLastLen = (NEW_TXN_WORDS_RECVD - rSentWords);
wire [9:0] wAddrLoInv = ~rAddr[11:2];
wire [10:0] wPageRem = (wAddrLoInv + 1'd1);
always @ (posedge CLK) begin
rTxState <= #1 (RST | rSgErr ? `S_TXPORTWR_TX_IDLE : _rTxState);
rSentWords <= #1 (rMainState[0] ? 0 : _rSentWords);
rWords <= #1 _rWords;
rBufWords <= #1 _rBufWords;
rBufWordsInit <= #1 _rBufWordsInit;
rAddr <= #1 _rAddr;
rCarry <= #1 _rCarry;
rValsPropagated <= #1 _rValsPropagated;
rValsProp <= #1 _rValsProp;
rLargeBuf <= #1 _rLargeBuf;
rPageRem <= #1 _rPageRem;
rPageSpill <= #1 _rPageSpill;
rPageSpillInit <= #1 _rPageSpillInit;
rCopyBufWords <= #1 _rCopyBufWords;
rUseInit <= #1 _rUseInit;
rPreLen <= #1 _rPreLen;
rMaxPayloadSize <= #1 _rMaxPayloadSize;
rMaxPayloadShift <= #1 _rMaxPayloadShift;
rMaxPayload <= #1 _rMaxPayload;
rPayloadSpill <= #1 _rPayloadSpill;
rMaxLen <= #1 (RST ? 1'd1 : _rMaxLen);
rLen <= #1 _rLen;
rSendingWords <= #1 _rSendingWords;
rAvail <= #1 _rAvail;
rTxnDone <= #1 _rTxnDone;
rLastLen <= #1 _rLastLen;
rLastLenEQ0 <= #1 _rLastLenEQ0;
rLenEQWords <= #1 _rLenEQWords;
rLenEQBufWords <= #1 _rLenEQBufWords;
end
always @ (*) begin
_rTxState = rTxState;
_rCopyBufWords = rCopyBufWords;
_rUseInit = rUseInit;
_rValsProp = ((rValsProp<<1) | rTxState[3]); // S_TXPORTWR_TX_ADJ_1
_rValsPropagated = (rValsProp == 6'd0);
_rLargeBuf = (SG_ELEM_LEN > rWords);
{_rCarry[0], _rAddr[15:0]} = (rTxState[1] ? SG_ELEM_ADDR[15:0] : (rAddr[15:0] + ({12{rTxState[6]}} & {rLen, 2'd0}))); // S_TXPORTWR_TX_WRITE
{_rCarry[1], _rAddr[31:16]} = (rTxState[1] ? SG_ELEM_ADDR[31:16] : (rAddr[31:16] + rCarry[0]));
{_rCarry[2], _rAddr[47:32]} = (rTxState[1] ? SG_ELEM_ADDR[47:32] : (rAddr[47:32] + rCarry[1]));
_rAddr[63:48] = (rTxState[1] ? SG_ELEM_ADDR[63:48] : (rAddr[63:48] + rCarry[2]));
_rSentWords = (rTxState[7] ? NEW_TXN_WORDS_RECVD : rSentWords) + ({10{rTxState[6]}} & rLen); // S_TXPORTWR_TX_WRITE
_rWords = (NEW_TXN_ACK ? NEW_TXN_LEN : (rWords - ({10{rTxState[6]}} & rLen))); // S_TXPORTWR_TX_WRITE
_rBufWordsInit = (rLargeBuf ? rWords : SG_ELEM_LEN);
_rBufWords = (rCopyBufWords ? rBufWordsInit : rBufWords) - ({10{rTxState[6]}} & rLen); // S_TXPORTWR_TX_WRITE
_rPageRem = wPageRem;
_rPageSpillInit = (rBufWordsInit > wPageRem);
_rPageSpill = (rBufWords > wPageRem);
_rPreLen = ((rPageSpillInit & rUseInit) | (rPageSpill & !rUseInit) ? rPageRem : rBufWords[10:0]);
_rMaxPayloadSize = CONFIG_MAX_PAYLOAD_SIZE;
_rMaxPayloadShift = (rMaxPayloadSize > 3'd4 ? 3'd4 : rMaxPayloadSize);
_rMaxPayload = (6'd32<<rMaxPayloadShift);
_rPayloadSpill = (rPreLen > rMaxPayload);
_rMaxLen = ((rMaxLen & !rValsProp[1]) | rTxState[6]); // S_TXPORTWR_TX_WRITE
_rLen = (rPayloadSpill | rMaxLen ? rMaxPayload : rPreLen[9:0]);
_rSendingWords = rSentWords + rLen;
_rAvail = (NEW_TXN_WORDS_RECVD >= rSendingWords);
_rTxnDone = ((rTxnDone<<1) | NEW_TXN_DONE);
_rLastLen = wLastLen;
_rLastLenEQ0 = (rLastLen == 10'd0);
_rLenEQWords = (rLen == rWords);
_rLenEQBufWords = (rLen == rBufWords);
case (rTxState)
`S_TXPORTWR_TX_IDLE: begin // Wait for channel write request
if (rMainState[4] & !rStarted) // S_TXPORTWR_MAIN_WRITE
_rTxState = `S_TXPORTWR_TX_BUF;
end
`S_TXPORTWR_TX_BUF: begin // Wait for buffer length and address
if (SG_ELEM_RDY)
_rTxState = `S_TXPORTWR_TX_ADJ_0;
end
`S_TXPORTWR_TX_ADJ_0: begin // Fix for large buffer
_rCopyBufWords = 1;
_rTxState = `S_TXPORTWR_TX_ADJ_1;
end
`S_TXPORTWR_TX_ADJ_1: begin // Check for page boundary crossing
_rCopyBufWords = 0;
_rUseInit = rCopyBufWords;
_rTxState = `S_TXPORTWR_TX_ADJ_2;
end
`S_TXPORTWR_TX_ADJ_2: begin // Wait for values to propagate
// Fix for page boundary crossing
// Check for max payload
// Fix for max payload
_rUseInit = 0;
if (rValsProp[2])
_rTxState = `S_TXPORTWR_TX_CHECK_DATA;
end
`S_TXPORTWR_TX_CHECK_DATA: begin // Wait for available data
if (rNotRequesting) begin
if (rAvail)
_rTxState = `S_TXPORTWR_TX_WRITE;
else if (rValsPropagated & rTxnDone[1])
_rTxState = (rLastLenEQ0 ? `S_TXPORTWR_TX_IDLE : `S_TXPORTWR_TX_WRITE_REM);
end
end
`S_TXPORTWR_TX_WRITE: begin // Send len and repeat or finish?
if (rLenEQWords)
_rTxState = `S_TXPORTWR_TX_IDLE;
else if (rLenEQBufWords)
_rTxState = `S_TXPORTWR_TX_BUF;
else
_rTxState = `S_TXPORTWR_TX_ADJ_1;
end
`S_TXPORTWR_TX_WRITE_REM: begin // Send remaining data and finish
_rTxState = `S_TXPORTWR_TX_IDLE;
end
default: begin
_rTxState = `S_TXPORTWR_TX_IDLE;
end
endcase
end
// Request TX transfers separately so that the TX FSM can continue calculating
// the next set of request parameters without having to wait for the TX_REQ_ACK.
always @ (posedge CLK) begin
rAckCount <= #1 (RST ? 10'd0 : _rAckCount);
rNotRequesting <= #1 (RST ? 1'd1 : _rNotRequesting);
rReqAddr <= #1 _rReqAddr;
rReqLen <= #1 _rReqLen;
rReqLast <= #1 _rReqLast;
rDone <= #1 _rDone;
rLastDoneRead <= #1 (RST ? 1'd1 : _rLastDoneRead);
end
always @ (*) begin
// Start signaling when the TX FSM is ready.
if (rTxState[6] | rTxState[7]) // S_TXPORTWR_TX_WRITE
_rNotRequesting = 0;
else
_rNotRequesting = (rNotRequesting | rTxReqAck);
// Pass off the rAddr & rLen when ready and wait for TX_REQ_ACK.
if (rTxState[6]) begin // S_TXPORTWR_TX_WRITE
_rReqAddr = rAddr;
_rReqLen = rLen;
_rReqLast = rLenEQWords;
end
else if (rTxState[7]) begin // S_TXPORTWR_TX_WRITE_REM
_rReqAddr = rAddr;
_rReqLen = rLastLen;
_rReqLast = 1;
end
else begin
_rReqAddr = rReqAddr;
_rReqLen = rReqLen;
_rReqLast = rReqLast;
end
// Track TX_REQ_ACK and TX_SENT to determine when the transaction is over.
_rDone = (rAckCount == 10'd0);
if (rMainState[0]) // S_TXPORTWR_MAIN_IDLE
_rAckCount = 0;
else
_rAckCount = rAckCount + rTxState[6] + rTxState[7] - rTxSent; // S_TXPORTWR_TX_WRITE, S_TXPORTWR_TX_WRITE_REM
// Track when the user reads the actual transfer amount.
_rLastDoneRead = (rMainState[6] ? 1'd0 : (rLastDoneRead | rTxnDoneAck)); // S_TXPORTWR_MAIN_SIG_DONE
end
// Facilitate sending a TXN_DONE when we receive a TXN_ACK after the transaction
// has begun sending. This will happen when the workstation detects that it has
// sent/used all its currently mapped scatter gather elements, but it's not enough
// to complete the transaction. The TXN_DONE will let the workstation know it can
// release the current scatter gather mappings and allocate new ones.
always @ (posedge CLK) begin
rPartialDone <= #1 _rPartialDone;
rReqPartialDone <= #1 (RST ? 1'd0 : _rReqPartialDone);
end
always @ (*) begin
// Signal TXN_DONE after we've recieved the (seemingly superfluous) TXN_ACK,
// we have no outstanding transfer requests, we're not currently requesting a
// transfer, and there are no more scatter gather elements.
_rPartialDone = (rReqPartialDone & rDone & rNotRequesting & SG_ELEM_EMPTY & rTxState[1]); // S_TXPORTWR_TX_BUF
// Keep track of (seemingly superfluous) TXN_ACK requests.
if ((rReqPartialDone & rDone & rNotRequesting & SG_ELEM_EMPTY & rTxState[1]) | rMainState[0]) // S_TXPORTWR_MAIN_IDLE
_rReqPartialDone = 0;
else
_rReqPartialDone = (rReqPartialDone | (rTxnAck & !rMainState[3])); // !S_TXPORTWR_MAIN_NEW_ACK
end
/*
wire [35:0] wControl0;
chipscope_icon_1 cs_icon(
.CONTROL0(wControl0)
);
chipscope_ila_t8_512 a0(
.CLK(CLK),
.CONTROL(wControl0),
.TRIG0({rTxState[6] | rTxState[7] | rTxSent, rAckCount[6:0]}),
.DATA({280'd0,
NEW_TXN_WORDS_RECVD, // 32
rSendingWords, // 32
rAvail, // 1
rNotRequesting, // 1
NEW_TXN_LAST, // 1
NEW_TXN_LEN, // 32
NEW_TXN_OFF, // 31
NEW_TXN, // 1
rAckCount, // 10
rLastDoneRead, // 1
rWords, // 32
rBufWords, // 32
rLen, // 10
rTxState, // 8
rMainState}) // 8
);
*/
endmodule
|
// ----------------------------------------------------------------------
// Copyright (c) 2016, The Regents of the University of California All
// rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// * Neither the name of The Regents of the University of California
// nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL REGENTS OF THE
// UNIVERSITY OF CALIFORNIA BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
// OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
// TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
// ----------------------------------------------------------------------
//----------------------------------------------------------------------------
// Filename: rx_port_channel_gate.v
// Version: 1.00.a
// Verilog Standard: Verilog-2001
// Description: Provides cross domain synchronization for the CHNL_RX*
// signals between the CHNL_CLK and CLK domains.
// Author: Matt Jacobsen
// History: @mattj: Version 2.0
//-----------------------------------------------------------------------------
`timescale 1ns/1ns
module rx_port_channel_gate #(
parameter C_DATA_WIDTH = 9'd64
)
(
input RST,
input CLK,
input RX, // Channel read signal (CLK)
output RX_RECVD, // Channel read received signal (CLK)
output RX_ACK_RECVD, // Channel read acknowledgment received signal (CLK)
input RX_LAST, // Channel last read (CLK)
input [31:0] RX_LEN, // Channel read length (CLK)
input [30:0] RX_OFF, // Channel read offset (CLK)
output [31:0] RX_CONSUMED, // Channel words consumed (CLK)
input [C_DATA_WIDTH-1:0] RD_DATA, // FIFO read data (CHNL_CLK)
input RD_EMPTY, // FIFO is empty (CHNL_CLK)
output RD_EN, // FIFO read enable (CHNL_CLK)
input CHNL_CLK, // Channel read clock
output CHNL_RX, // Channel read receive signal (CHNL_CLK)
input CHNL_RX_ACK, // Channle read received signal (CHNL_CLK)
output CHNL_RX_LAST, // Channel last read (CHNL_CLK)
output [31:0] CHNL_RX_LEN, // Channel read length (CHNL_CLK)
output [30:0] CHNL_RX_OFF, // Channel read offset (CHNL_CLK)
output [C_DATA_WIDTH-1:0] CHNL_RX_DATA, // Channel read data (CHNL_CLK)
output CHNL_RX_DATA_VALID, // Channel read data valid (CHNL_CLK)
input CHNL_RX_DATA_REN // Channel read data has been recieved (CHNL_CLK)
);
reg rAckd=0, _rAckd=0;
reg rChnlRxAck=0, _rChnlRxAck=0;
reg [31:0] rConsumed=0, _rConsumed=0;
reg [31:0] rConsumedStable=0, _rConsumedStable=0;
reg [31:0] rConsumedSample=0, _rConsumedSample=0;
reg rCountRead=0, _rCountRead=0;
wire wCountRead;
wire wCountStable;
wire wDataRead = (CHNL_RX_DATA_REN & CHNL_RX_DATA_VALID);
assign RX_CONSUMED = rConsumedSample;
assign RD_EN = CHNL_RX_DATA_REN;
assign CHNL_RX_LAST = RX_LAST;
assign CHNL_RX_LEN = RX_LEN;
assign CHNL_RX_OFF = RX_OFF;
assign CHNL_RX_DATA = RD_DATA;
assign CHNL_RX_DATA_VALID = !RD_EMPTY;
// Buffer the input signals that come from outside the rx_port.
always @ (posedge CHNL_CLK) begin
rChnlRxAck <= #1 (RST ? 1'd0 : _rChnlRxAck);
end
always @ (*) begin
_rChnlRxAck = CHNL_RX_ACK;
end
// Signal receive into the channel domain.
cross_domain_signal rxSig (
.CLK_A(CLK),
.CLK_A_SEND(RX),
.CLK_A_RECV(RX_RECVD),
.CLK_B(CHNL_CLK),
.CLK_B_RECV(CHNL_RX),
.CLK_B_SEND(CHNL_RX)
);
// Signal acknowledgment of receive into the CLK domain.
syncff rxAckSig (.CLK(CLK), .IN_ASYNC(rAckd), .OUT_SYNC(RX_ACK_RECVD));
// Capture CHNL_RX_ACK and reset only after the CHNL_RX drops.
always @ (posedge CHNL_CLK) begin
rAckd <= #1 (RST ? 1'd0 : _rAckd);
end
always @ (*) begin
_rAckd = (CHNL_RX & (rAckd | rChnlRxAck));
end
// Count the words consumed by the channel and pass it into the CLK domain.
always @ (posedge CHNL_CLK) begin
rConsumed <= #1 _rConsumed;
rConsumedStable <= #1 _rConsumedStable;
rCountRead <= #1 (RST ? 1'd0 : _rCountRead);
end
always @ (*) begin
_rConsumed = (!CHNL_RX ? 0 : rConsumed + (wDataRead*(C_DATA_WIDTH/32)));
_rConsumedStable = (wCountRead | rCountRead ? rConsumedStable : rConsumed);
_rCountRead = !wCountRead;
end
always @ (posedge CLK) begin
rConsumedSample <= #1 _rConsumedSample;
end
always @ (*) begin
_rConsumedSample = (wCountStable ? rConsumedStable : rConsumedSample);
end
// Determine when it's safe to update the count in the CLK domain.
cross_domain_signal countSync (
.CLK_A(CHNL_CLK),
.CLK_A_SEND(rCountRead),
.CLK_A_RECV(wCountRead),
.CLK_B(CLK),
.CLK_B_RECV(wCountStable),
.CLK_B_SEND(wCountStable)
);
endmodule
|
// ----------------------------------------------------------------------
// Copyright (c) 2016, The Regents of the University of California All
// rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// * Neither the name of The Regents of the University of California
// nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL REGENTS OF THE
// UNIVERSITY OF CALIFORNIA BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
// OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
// TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
// ----------------------------------------------------------------------
//----------------------------------------------------------------------------
// Filename: rx_port_channel_gate.v
// Version: 1.00.a
// Verilog Standard: Verilog-2001
// Description: Provides cross domain synchronization for the CHNL_RX*
// signals between the CHNL_CLK and CLK domains.
// Author: Matt Jacobsen
// History: @mattj: Version 2.0
//-----------------------------------------------------------------------------
`timescale 1ns/1ns
module rx_port_channel_gate #(
parameter C_DATA_WIDTH = 9'd64
)
(
input RST,
input CLK,
input RX, // Channel read signal (CLK)
output RX_RECVD, // Channel read received signal (CLK)
output RX_ACK_RECVD, // Channel read acknowledgment received signal (CLK)
input RX_LAST, // Channel last read (CLK)
input [31:0] RX_LEN, // Channel read length (CLK)
input [30:0] RX_OFF, // Channel read offset (CLK)
output [31:0] RX_CONSUMED, // Channel words consumed (CLK)
input [C_DATA_WIDTH-1:0] RD_DATA, // FIFO read data (CHNL_CLK)
input RD_EMPTY, // FIFO is empty (CHNL_CLK)
output RD_EN, // FIFO read enable (CHNL_CLK)
input CHNL_CLK, // Channel read clock
output CHNL_RX, // Channel read receive signal (CHNL_CLK)
input CHNL_RX_ACK, // Channle read received signal (CHNL_CLK)
output CHNL_RX_LAST, // Channel last read (CHNL_CLK)
output [31:0] CHNL_RX_LEN, // Channel read length (CHNL_CLK)
output [30:0] CHNL_RX_OFF, // Channel read offset (CHNL_CLK)
output [C_DATA_WIDTH-1:0] CHNL_RX_DATA, // Channel read data (CHNL_CLK)
output CHNL_RX_DATA_VALID, // Channel read data valid (CHNL_CLK)
input CHNL_RX_DATA_REN // Channel read data has been recieved (CHNL_CLK)
);
reg rAckd=0, _rAckd=0;
reg rChnlRxAck=0, _rChnlRxAck=0;
reg [31:0] rConsumed=0, _rConsumed=0;
reg [31:0] rConsumedStable=0, _rConsumedStable=0;
reg [31:0] rConsumedSample=0, _rConsumedSample=0;
reg rCountRead=0, _rCountRead=0;
wire wCountRead;
wire wCountStable;
wire wDataRead = (CHNL_RX_DATA_REN & CHNL_RX_DATA_VALID);
assign RX_CONSUMED = rConsumedSample;
assign RD_EN = CHNL_RX_DATA_REN;
assign CHNL_RX_LAST = RX_LAST;
assign CHNL_RX_LEN = RX_LEN;
assign CHNL_RX_OFF = RX_OFF;
assign CHNL_RX_DATA = RD_DATA;
assign CHNL_RX_DATA_VALID = !RD_EMPTY;
// Buffer the input signals that come from outside the rx_port.
always @ (posedge CHNL_CLK) begin
rChnlRxAck <= #1 (RST ? 1'd0 : _rChnlRxAck);
end
always @ (*) begin
_rChnlRxAck = CHNL_RX_ACK;
end
// Signal receive into the channel domain.
cross_domain_signal rxSig (
.CLK_A(CLK),
.CLK_A_SEND(RX),
.CLK_A_RECV(RX_RECVD),
.CLK_B(CHNL_CLK),
.CLK_B_RECV(CHNL_RX),
.CLK_B_SEND(CHNL_RX)
);
// Signal acknowledgment of receive into the CLK domain.
syncff rxAckSig (.CLK(CLK), .IN_ASYNC(rAckd), .OUT_SYNC(RX_ACK_RECVD));
// Capture CHNL_RX_ACK and reset only after the CHNL_RX drops.
always @ (posedge CHNL_CLK) begin
rAckd <= #1 (RST ? 1'd0 : _rAckd);
end
always @ (*) begin
_rAckd = (CHNL_RX & (rAckd | rChnlRxAck));
end
// Count the words consumed by the channel and pass it into the CLK domain.
always @ (posedge CHNL_CLK) begin
rConsumed <= #1 _rConsumed;
rConsumedStable <= #1 _rConsumedStable;
rCountRead <= #1 (RST ? 1'd0 : _rCountRead);
end
always @ (*) begin
_rConsumed = (!CHNL_RX ? 0 : rConsumed + (wDataRead*(C_DATA_WIDTH/32)));
_rConsumedStable = (wCountRead | rCountRead ? rConsumedStable : rConsumed);
_rCountRead = !wCountRead;
end
always @ (posedge CLK) begin
rConsumedSample <= #1 _rConsumedSample;
end
always @ (*) begin
_rConsumedSample = (wCountStable ? rConsumedStable : rConsumedSample);
end
// Determine when it's safe to update the count in the CLK domain.
cross_domain_signal countSync (
.CLK_A(CHNL_CLK),
.CLK_A_SEND(rCountRead),
.CLK_A_RECV(wCountRead),
.CLK_B(CLK),
.CLK_B_RECV(wCountStable),
.CLK_B_SEND(wCountStable)
);
endmodule
|
// ----------------------------------------------------------------------
// Copyright (c) 2016, The Regents of the University of California All
// rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// * Neither the name of The Regents of the University of California
// nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL REGENTS OF THE
// UNIVERSITY OF CALIFORNIA BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
// OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
// TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
// ----------------------------------------------------------------------
//----------------------------------------------------------------------------
// Filename: rx_port_channel_gate.v
// Version: 1.00.a
// Verilog Standard: Verilog-2001
// Description: Provides cross domain synchronization for the CHNL_RX*
// signals between the CHNL_CLK and CLK domains.
// Author: Matt Jacobsen
// History: @mattj: Version 2.0
//-----------------------------------------------------------------------------
`timescale 1ns/1ns
module rx_port_channel_gate #(
parameter C_DATA_WIDTH = 9'd64
)
(
input RST,
input CLK,
input RX, // Channel read signal (CLK)
output RX_RECVD, // Channel read received signal (CLK)
output RX_ACK_RECVD, // Channel read acknowledgment received signal (CLK)
input RX_LAST, // Channel last read (CLK)
input [31:0] RX_LEN, // Channel read length (CLK)
input [30:0] RX_OFF, // Channel read offset (CLK)
output [31:0] RX_CONSUMED, // Channel words consumed (CLK)
input [C_DATA_WIDTH-1:0] RD_DATA, // FIFO read data (CHNL_CLK)
input RD_EMPTY, // FIFO is empty (CHNL_CLK)
output RD_EN, // FIFO read enable (CHNL_CLK)
input CHNL_CLK, // Channel read clock
output CHNL_RX, // Channel read receive signal (CHNL_CLK)
input CHNL_RX_ACK, // Channle read received signal (CHNL_CLK)
output CHNL_RX_LAST, // Channel last read (CHNL_CLK)
output [31:0] CHNL_RX_LEN, // Channel read length (CHNL_CLK)
output [30:0] CHNL_RX_OFF, // Channel read offset (CHNL_CLK)
output [C_DATA_WIDTH-1:0] CHNL_RX_DATA, // Channel read data (CHNL_CLK)
output CHNL_RX_DATA_VALID, // Channel read data valid (CHNL_CLK)
input CHNL_RX_DATA_REN // Channel read data has been recieved (CHNL_CLK)
);
reg rAckd=0, _rAckd=0;
reg rChnlRxAck=0, _rChnlRxAck=0;
reg [31:0] rConsumed=0, _rConsumed=0;
reg [31:0] rConsumedStable=0, _rConsumedStable=0;
reg [31:0] rConsumedSample=0, _rConsumedSample=0;
reg rCountRead=0, _rCountRead=0;
wire wCountRead;
wire wCountStable;
wire wDataRead = (CHNL_RX_DATA_REN & CHNL_RX_DATA_VALID);
assign RX_CONSUMED = rConsumedSample;
assign RD_EN = CHNL_RX_DATA_REN;
assign CHNL_RX_LAST = RX_LAST;
assign CHNL_RX_LEN = RX_LEN;
assign CHNL_RX_OFF = RX_OFF;
assign CHNL_RX_DATA = RD_DATA;
assign CHNL_RX_DATA_VALID = !RD_EMPTY;
// Buffer the input signals that come from outside the rx_port.
always @ (posedge CHNL_CLK) begin
rChnlRxAck <= #1 (RST ? 1'd0 : _rChnlRxAck);
end
always @ (*) begin
_rChnlRxAck = CHNL_RX_ACK;
end
// Signal receive into the channel domain.
cross_domain_signal rxSig (
.CLK_A(CLK),
.CLK_A_SEND(RX),
.CLK_A_RECV(RX_RECVD),
.CLK_B(CHNL_CLK),
.CLK_B_RECV(CHNL_RX),
.CLK_B_SEND(CHNL_RX)
);
// Signal acknowledgment of receive into the CLK domain.
syncff rxAckSig (.CLK(CLK), .IN_ASYNC(rAckd), .OUT_SYNC(RX_ACK_RECVD));
// Capture CHNL_RX_ACK and reset only after the CHNL_RX drops.
always @ (posedge CHNL_CLK) begin
rAckd <= #1 (RST ? 1'd0 : _rAckd);
end
always @ (*) begin
_rAckd = (CHNL_RX & (rAckd | rChnlRxAck));
end
// Count the words consumed by the channel and pass it into the CLK domain.
always @ (posedge CHNL_CLK) begin
rConsumed <= #1 _rConsumed;
rConsumedStable <= #1 _rConsumedStable;
rCountRead <= #1 (RST ? 1'd0 : _rCountRead);
end
always @ (*) begin
_rConsumed = (!CHNL_RX ? 0 : rConsumed + (wDataRead*(C_DATA_WIDTH/32)));
_rConsumedStable = (wCountRead | rCountRead ? rConsumedStable : rConsumed);
_rCountRead = !wCountRead;
end
always @ (posedge CLK) begin
rConsumedSample <= #1 _rConsumedSample;
end
always @ (*) begin
_rConsumedSample = (wCountStable ? rConsumedStable : rConsumedSample);
end
// Determine when it's safe to update the count in the CLK domain.
cross_domain_signal countSync (
.CLK_A(CHNL_CLK),
.CLK_A_SEND(rCountRead),
.CLK_A_RECV(wCountRead),
.CLK_B(CLK),
.CLK_B_RECV(wCountStable),
.CLK_B_SEND(wCountStable)
);
endmodule
|
//////////////////////////////////////////////////////////////////////
//// ////
//// spi_clgen.v ////
//// ////
//// This file is part of the SPI IP core project ////
//// http://www.opencores.org/projects/spi/ ////
//// ////
//// Author(s): ////
//// - Simon Srot ([email protected]) ////
//// ////
//// All additional information is avaliable in the Readme.txt ////
//// file. ////
//// ////
//////////////////////////////////////////////////////////////////////
//// ////
//// Copyright (C) 2002 Authors ////
//// ////
//// This source file may be used and distributed without ////
//// restriction provided that this copyright statement is not ////
//// removed from the file and that any derivative work contains ////
//// the original copyright notice and the associated disclaimer. ////
//// ////
//// This source file is free software; you can redistribute it ////
//// and/or modify it under the terms of the GNU Lesser General ////
//// Public License as published by the Free Software Foundation; ////
//// either version 2.1 of the License, or (at your option) any ////
//// later version. ////
//// ////
//// This source is distributed in the hope that it will be ////
//// useful, but WITHOUT ANY WARRANTY; without even the implied ////
//// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR ////
//// PURPOSE. See the GNU Lesser General Public License for more ////
//// details. ////
//// ////
//// You should have received a copy of the GNU Lesser General ////
//// Public License along with this source; if not, download it ////
//// from http://www.opencores.org/lgpl.shtml ////
//// ////
//////////////////////////////////////////////////////////////////////
`include "spi_defines.v"
`include "timescale.v"
module spi_clgen (clk_in, rst, go, enable, last_clk, divider, clk_out, pos_edge, neg_edge);
parameter Tp = 1;
input clk_in; // input clock (system clock)
input rst; // reset
input enable; // clock enable
input go; // start transfer
input last_clk; // last clock
input [`SPI_DIVIDER_LEN-1:0] divider; // clock divider (output clock is divided by this value)
output clk_out; // output clock
output pos_edge; // pulse marking positive edge of clk_out
output neg_edge; // pulse marking negative edge of clk_out
reg clk_out;
reg pos_edge;
reg neg_edge;
reg [`SPI_DIVIDER_LEN-1:0] cnt; // clock counter
wire cnt_zero; // conter is equal to zero
wire cnt_one; // conter is equal to one
assign cnt_zero = cnt == {`SPI_DIVIDER_LEN{1'b0}};
assign cnt_one = cnt == {{`SPI_DIVIDER_LEN-1{1'b0}}, 1'b1};
// Counter counts half period
always @(posedge clk_in or posedge rst)
begin
if(rst)
cnt <= #Tp {`SPI_DIVIDER_LEN{1'b1}};
else
begin
if(!enable || cnt_zero)
cnt <= #Tp divider;
else
cnt <= #Tp cnt - {{`SPI_DIVIDER_LEN-1{1'b0}}, 1'b1};
end
end
// clk_out is asserted every other half period
always @(posedge clk_in or posedge rst)
begin
if(rst)
clk_out <= #Tp 1'b0;
else
clk_out <= #Tp (enable && cnt_zero && (!last_clk || clk_out)) ? ~clk_out : clk_out;
end
// Pos and neg edge signals
always @(posedge clk_in or posedge rst)
begin
if(rst)
begin
pos_edge <= #Tp 1'b0;
neg_edge <= #Tp 1'b0;
end
else
begin
pos_edge <= #Tp (enable && !clk_out && cnt_one) || (!(|divider) && clk_out) || (!(|divider) && go && !enable);
neg_edge <= #Tp (enable && clk_out && cnt_one) || (!(|divider) && !clk_out && enable);
end
end
endmodule
|
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 04/27/2016 08:14:07 AM
// Design Name:
// Module Name: FPU_UART
// Project Name:
// Target Devices:
// Tool Versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module FPU_UART
#(parameter W = 32, parameter EW = 8, parameter SW = 23, parameter SWR=26, parameter EWR = 5)//-- Single Precision*/
/*#(parameter W = 64, parameter EW = 11, parameter SW = 52, parameter SWR = 55, parameter EWR = 6) //-- Double Precision */
(
input wire clk,
input wire rst,
output wire TX
);
//local parameters
localparam shift_region = 2'b00;
localparam N = 2; //2 para 32 bits, 3 para 64 bits
localparam op = 1'b0;
localparam d = 0;
localparam r_mode=2'b00;
//signal declaration
wire ready_op;
wire max_tick_address;
wire max_tick_ch;
wire TX_DONE;
wire beg_op;
wire ack_op;
wire load_address;
wire enab_address;
wire enab_ch;
wire load_ch;
wire TX_START;
wire [W-1:0] Data_X;
wire [W-1:0] Data_Y;
wire [W-1:0] final_result_ieee;
wire [7:0] TX_DATA;
wire [9:0] cont_address_sig;
wire [N-1:0] cont_ch;
FSM_test fsm_test_uart
(
.clk(clk),
.rst(rst),
.ready_op(ready_op),
.max_tick_address(max_tick_address),
.max_tick_ch(max_tick_ch),
.TX_DONE(TX_DONE),
.beg_op(beg_op),
.ack_op(ack_op),
.load_address(load_address),
.enab_address(enab_address),
.enab_ch(enab_ch),
.load_ch(load_ch),
.TX_START(TX_START)
);
//Adder-Subtract//////////////////////////////////////////////////////////////////////////////
FPU_Add_Subtract_Function #(.W(W),.EW(EW),.SW(SW),.SWR(SWR),.EWR(EWR)) Add_Subt_uart(
.clk(clk), //System clock
.rst(rst), //System reset
.beg_FSM(beg_op), //Start operation control signal
.ack_FSM(ack_op), //Acknoledge control signal
.Data_X(Data_X), //Data_X
.Data_Y(Data_Y), //Data_Y
.add_subt(op), //1'b0 =Adder, 1'b1=Substract
.r_mode(r_mode), //Rounding control signal. 2'b00=no round, 2'b01= -infinite round , 2'b10 +infinite round
//.overflow_flag,
//.underflow_flag,
.ready(ready_op), //Ready flag
.final_result_ieee(final_result_ieee) //Result of the operation
);//*/
//Multiplication
/*FPU_Multiplication_Function #(.W(W),.EW(EW),.SW(SW)) Multiplication_uart(
.clk(clk),
.rst(rst),
.beg_FSM(beg_op),
.ack_FSM(ack_op),
.Data_MX(Data_X),
.Data_MY(Data_Y),
.round_mode(r_mode),
//.overflow_flag,
//.underflow_flag,
.ready(ready_op),
.final_result_ieee(final_result_ieee)
);
//*/
Uart uart_mod
(
.RST(rst),
.CLK(clk),
.TX_START(TX_START),
.TX_DATA(TX_DATA),
.TX(TX),
.TX_DONE(TX_DONE)
);
///Data file ROM
ROM_test #(.W(W),.N(0)) rom_test_uart_X
(
.address(cont_address_sig),
.data(Data_X)
);
ROM_test #(.W(W),.N(1)) rom_test_uart_Y
(
.address(cont_address_sig),
.data(Data_Y)
);
cont_test #(.W(10)) cont_address
(
.clk(clk),
.rst(rst),
.load(load_address),
.enable(enab_address),
.d(d),
.max_tick(max_tick_address),
.q(cont_address_sig)
);
cont_test #(.W(N)) con_mux_data
(
.clk(clk),
.rst(rst),
.load(load_ch),
.enable(enab_ch),
.d(d),
.max_tick(max_tick_ch),
.q(cont_ch)
);
generate
case(W)
32:
begin
Mux_4x1 mux_32_uart
(
.select(cont_ch),
.ch_0(final_result_ieee[7:0]),
.ch_1(final_result_ieee[15:8]),
.ch_2(final_result_ieee[23:16]),
.ch_3(final_result_ieee[31:24]),
.data_out(TX_DATA)
);
end
64:
begin
Mux_8x1 mux_64_uart
(
.select(cont_ch),
.ch_0(final_result_ieee[7:0]),
.ch_1(final_result_ieee[15:8]),
.ch_2(final_result_ieee[23:16]),
.ch_3(final_result_ieee[31:24]),
.ch_4(final_result_ieee[39:32]),
.ch_5(final_result_ieee[47:40]),
.ch_6(final_result_ieee[55:48]),
.ch_7(final_result_ieee[63:56]),
.data_out(TX_DATA)
);
end
default:
begin
Mux_4x1 mux_32_uart
(
.select(cont_ch),
.ch_0(final_result_ieee[7:0]),
.ch_1(final_result_ieee[15:8]),
.ch_2(final_result_ieee[23:16]),
.ch_3(final_result_ieee[31:24]),
.data_out(TX_DATA)
);
end
endcase
endgenerate
endmodule
|
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 04/27/2016 08:14:07 AM
// Design Name:
// Module Name: FPU_UART
// Project Name:
// Target Devices:
// Tool Versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module FPU_UART
#(parameter W = 32, parameter EW = 8, parameter SW = 23, parameter SWR=26, parameter EWR = 5)//-- Single Precision*/
/*#(parameter W = 64, parameter EW = 11, parameter SW = 52, parameter SWR = 55, parameter EWR = 6) //-- Double Precision */
(
input wire clk,
input wire rst,
output wire TX
);
//local parameters
localparam shift_region = 2'b00;
localparam N = 2; //2 para 32 bits, 3 para 64 bits
localparam op = 1'b0;
localparam d = 0;
localparam r_mode=2'b00;
//signal declaration
wire ready_op;
wire max_tick_address;
wire max_tick_ch;
wire TX_DONE;
wire beg_op;
wire ack_op;
wire load_address;
wire enab_address;
wire enab_ch;
wire load_ch;
wire TX_START;
wire [W-1:0] Data_X;
wire [W-1:0] Data_Y;
wire [W-1:0] final_result_ieee;
wire [7:0] TX_DATA;
wire [9:0] cont_address_sig;
wire [N-1:0] cont_ch;
FSM_test fsm_test_uart
(
.clk(clk),
.rst(rst),
.ready_op(ready_op),
.max_tick_address(max_tick_address),
.max_tick_ch(max_tick_ch),
.TX_DONE(TX_DONE),
.beg_op(beg_op),
.ack_op(ack_op),
.load_address(load_address),
.enab_address(enab_address),
.enab_ch(enab_ch),
.load_ch(load_ch),
.TX_START(TX_START)
);
//Adder-Subtract//////////////////////////////////////////////////////////////////////////////
FPU_Add_Subtract_Function #(.W(W),.EW(EW),.SW(SW),.SWR(SWR),.EWR(EWR)) Add_Subt_uart(
.clk(clk), //System clock
.rst(rst), //System reset
.beg_FSM(beg_op), //Start operation control signal
.ack_FSM(ack_op), //Acknoledge control signal
.Data_X(Data_X), //Data_X
.Data_Y(Data_Y), //Data_Y
.add_subt(op), //1'b0 =Adder, 1'b1=Substract
.r_mode(r_mode), //Rounding control signal. 2'b00=no round, 2'b01= -infinite round , 2'b10 +infinite round
//.overflow_flag,
//.underflow_flag,
.ready(ready_op), //Ready flag
.final_result_ieee(final_result_ieee) //Result of the operation
);//*/
//Multiplication
/*FPU_Multiplication_Function #(.W(W),.EW(EW),.SW(SW)) Multiplication_uart(
.clk(clk),
.rst(rst),
.beg_FSM(beg_op),
.ack_FSM(ack_op),
.Data_MX(Data_X),
.Data_MY(Data_Y),
.round_mode(r_mode),
//.overflow_flag,
//.underflow_flag,
.ready(ready_op),
.final_result_ieee(final_result_ieee)
);
//*/
Uart uart_mod
(
.RST(rst),
.CLK(clk),
.TX_START(TX_START),
.TX_DATA(TX_DATA),
.TX(TX),
.TX_DONE(TX_DONE)
);
///Data file ROM
ROM_test #(.W(W),.N(0)) rom_test_uart_X
(
.address(cont_address_sig),
.data(Data_X)
);
ROM_test #(.W(W),.N(1)) rom_test_uart_Y
(
.address(cont_address_sig),
.data(Data_Y)
);
cont_test #(.W(10)) cont_address
(
.clk(clk),
.rst(rst),
.load(load_address),
.enable(enab_address),
.d(d),
.max_tick(max_tick_address),
.q(cont_address_sig)
);
cont_test #(.W(N)) con_mux_data
(
.clk(clk),
.rst(rst),
.load(load_ch),
.enable(enab_ch),
.d(d),
.max_tick(max_tick_ch),
.q(cont_ch)
);
generate
case(W)
32:
begin
Mux_4x1 mux_32_uart
(
.select(cont_ch),
.ch_0(final_result_ieee[7:0]),
.ch_1(final_result_ieee[15:8]),
.ch_2(final_result_ieee[23:16]),
.ch_3(final_result_ieee[31:24]),
.data_out(TX_DATA)
);
end
64:
begin
Mux_8x1 mux_64_uart
(
.select(cont_ch),
.ch_0(final_result_ieee[7:0]),
.ch_1(final_result_ieee[15:8]),
.ch_2(final_result_ieee[23:16]),
.ch_3(final_result_ieee[31:24]),
.ch_4(final_result_ieee[39:32]),
.ch_5(final_result_ieee[47:40]),
.ch_6(final_result_ieee[55:48]),
.ch_7(final_result_ieee[63:56]),
.data_out(TX_DATA)
);
end
default:
begin
Mux_4x1 mux_32_uart
(
.select(cont_ch),
.ch_0(final_result_ieee[7:0]),
.ch_1(final_result_ieee[15:8]),
.ch_2(final_result_ieee[23:16]),
.ch_3(final_result_ieee[31:24]),
.data_out(TX_DATA)
);
end
endcase
endgenerate
endmodule
|
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 04/27/2016 08:14:07 AM
// Design Name:
// Module Name: FPU_UART
// Project Name:
// Target Devices:
// Tool Versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module FPU_UART
#(parameter W = 32, parameter EW = 8, parameter SW = 23, parameter SWR=26, parameter EWR = 5)//-- Single Precision*/
/*#(parameter W = 64, parameter EW = 11, parameter SW = 52, parameter SWR = 55, parameter EWR = 6) //-- Double Precision */
(
input wire clk,
input wire rst,
output wire TX
);
//local parameters
localparam shift_region = 2'b00;
localparam N = 2; //2 para 32 bits, 3 para 64 bits
localparam op = 1'b0;
localparam d = 0;
localparam r_mode=2'b00;
//signal declaration
wire ready_op;
wire max_tick_address;
wire max_tick_ch;
wire TX_DONE;
wire beg_op;
wire ack_op;
wire load_address;
wire enab_address;
wire enab_ch;
wire load_ch;
wire TX_START;
wire [W-1:0] Data_X;
wire [W-1:0] Data_Y;
wire [W-1:0] final_result_ieee;
wire [7:0] TX_DATA;
wire [9:0] cont_address_sig;
wire [N-1:0] cont_ch;
FSM_test fsm_test_uart
(
.clk(clk),
.rst(rst),
.ready_op(ready_op),
.max_tick_address(max_tick_address),
.max_tick_ch(max_tick_ch),
.TX_DONE(TX_DONE),
.beg_op(beg_op),
.ack_op(ack_op),
.load_address(load_address),
.enab_address(enab_address),
.enab_ch(enab_ch),
.load_ch(load_ch),
.TX_START(TX_START)
);
//Adder-Subtract//////////////////////////////////////////////////////////////////////////////
FPU_Add_Subtract_Function #(.W(W),.EW(EW),.SW(SW),.SWR(SWR),.EWR(EWR)) Add_Subt_uart(
.clk(clk), //System clock
.rst(rst), //System reset
.beg_FSM(beg_op), //Start operation control signal
.ack_FSM(ack_op), //Acknoledge control signal
.Data_X(Data_X), //Data_X
.Data_Y(Data_Y), //Data_Y
.add_subt(op), //1'b0 =Adder, 1'b1=Substract
.r_mode(r_mode), //Rounding control signal. 2'b00=no round, 2'b01= -infinite round , 2'b10 +infinite round
//.overflow_flag,
//.underflow_flag,
.ready(ready_op), //Ready flag
.final_result_ieee(final_result_ieee) //Result of the operation
);//*/
//Multiplication
/*FPU_Multiplication_Function #(.W(W),.EW(EW),.SW(SW)) Multiplication_uart(
.clk(clk),
.rst(rst),
.beg_FSM(beg_op),
.ack_FSM(ack_op),
.Data_MX(Data_X),
.Data_MY(Data_Y),
.round_mode(r_mode),
//.overflow_flag,
//.underflow_flag,
.ready(ready_op),
.final_result_ieee(final_result_ieee)
);
//*/
Uart uart_mod
(
.RST(rst),
.CLK(clk),
.TX_START(TX_START),
.TX_DATA(TX_DATA),
.TX(TX),
.TX_DONE(TX_DONE)
);
///Data file ROM
ROM_test #(.W(W),.N(0)) rom_test_uart_X
(
.address(cont_address_sig),
.data(Data_X)
);
ROM_test #(.W(W),.N(1)) rom_test_uart_Y
(
.address(cont_address_sig),
.data(Data_Y)
);
cont_test #(.W(10)) cont_address
(
.clk(clk),
.rst(rst),
.load(load_address),
.enable(enab_address),
.d(d),
.max_tick(max_tick_address),
.q(cont_address_sig)
);
cont_test #(.W(N)) con_mux_data
(
.clk(clk),
.rst(rst),
.load(load_ch),
.enable(enab_ch),
.d(d),
.max_tick(max_tick_ch),
.q(cont_ch)
);
generate
case(W)
32:
begin
Mux_4x1 mux_32_uart
(
.select(cont_ch),
.ch_0(final_result_ieee[7:0]),
.ch_1(final_result_ieee[15:8]),
.ch_2(final_result_ieee[23:16]),
.ch_3(final_result_ieee[31:24]),
.data_out(TX_DATA)
);
end
64:
begin
Mux_8x1 mux_64_uart
(
.select(cont_ch),
.ch_0(final_result_ieee[7:0]),
.ch_1(final_result_ieee[15:8]),
.ch_2(final_result_ieee[23:16]),
.ch_3(final_result_ieee[31:24]),
.ch_4(final_result_ieee[39:32]),
.ch_5(final_result_ieee[47:40]),
.ch_6(final_result_ieee[55:48]),
.ch_7(final_result_ieee[63:56]),
.data_out(TX_DATA)
);
end
default:
begin
Mux_4x1 mux_32_uart
(
.select(cont_ch),
.ch_0(final_result_ieee[7:0]),
.ch_1(final_result_ieee[15:8]),
.ch_2(final_result_ieee[23:16]),
.ch_3(final_result_ieee[31:24]),
.data_out(TX_DATA)
);
end
endcase
endgenerate
endmodule
|
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 04/27/2016 08:14:07 AM
// Design Name:
// Module Name: FPU_UART
// Project Name:
// Target Devices:
// Tool Versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module FPU_UART
#(parameter W = 32, parameter EW = 8, parameter SW = 23, parameter SWR=26, parameter EWR = 5)//-- Single Precision*/
/*#(parameter W = 64, parameter EW = 11, parameter SW = 52, parameter SWR = 55, parameter EWR = 6) //-- Double Precision */
(
input wire clk,
input wire rst,
output wire TX
);
//local parameters
localparam shift_region = 2'b00;
localparam N = 2; //2 para 32 bits, 3 para 64 bits
localparam op = 1'b0;
localparam d = 0;
localparam r_mode=2'b00;
//signal declaration
wire ready_op;
wire max_tick_address;
wire max_tick_ch;
wire TX_DONE;
wire beg_op;
wire ack_op;
wire load_address;
wire enab_address;
wire enab_ch;
wire load_ch;
wire TX_START;
wire [W-1:0] Data_X;
wire [W-1:0] Data_Y;
wire [W-1:0] final_result_ieee;
wire [7:0] TX_DATA;
wire [9:0] cont_address_sig;
wire [N-1:0] cont_ch;
FSM_test fsm_test_uart
(
.clk(clk),
.rst(rst),
.ready_op(ready_op),
.max_tick_address(max_tick_address),
.max_tick_ch(max_tick_ch),
.TX_DONE(TX_DONE),
.beg_op(beg_op),
.ack_op(ack_op),
.load_address(load_address),
.enab_address(enab_address),
.enab_ch(enab_ch),
.load_ch(load_ch),
.TX_START(TX_START)
);
//Adder-Subtract//////////////////////////////////////////////////////////////////////////////
FPU_Add_Subtract_Function #(.W(W),.EW(EW),.SW(SW),.SWR(SWR),.EWR(EWR)) Add_Subt_uart(
.clk(clk), //System clock
.rst(rst), //System reset
.beg_FSM(beg_op), //Start operation control signal
.ack_FSM(ack_op), //Acknoledge control signal
.Data_X(Data_X), //Data_X
.Data_Y(Data_Y), //Data_Y
.add_subt(op), //1'b0 =Adder, 1'b1=Substract
.r_mode(r_mode), //Rounding control signal. 2'b00=no round, 2'b01= -infinite round , 2'b10 +infinite round
//.overflow_flag,
//.underflow_flag,
.ready(ready_op), //Ready flag
.final_result_ieee(final_result_ieee) //Result of the operation
);//*/
//Multiplication
/*FPU_Multiplication_Function #(.W(W),.EW(EW),.SW(SW)) Multiplication_uart(
.clk(clk),
.rst(rst),
.beg_FSM(beg_op),
.ack_FSM(ack_op),
.Data_MX(Data_X),
.Data_MY(Data_Y),
.round_mode(r_mode),
//.overflow_flag,
//.underflow_flag,
.ready(ready_op),
.final_result_ieee(final_result_ieee)
);
//*/
Uart uart_mod
(
.RST(rst),
.CLK(clk),
.TX_START(TX_START),
.TX_DATA(TX_DATA),
.TX(TX),
.TX_DONE(TX_DONE)
);
///Data file ROM
ROM_test #(.W(W),.N(0)) rom_test_uart_X
(
.address(cont_address_sig),
.data(Data_X)
);
ROM_test #(.W(W),.N(1)) rom_test_uart_Y
(
.address(cont_address_sig),
.data(Data_Y)
);
cont_test #(.W(10)) cont_address
(
.clk(clk),
.rst(rst),
.load(load_address),
.enable(enab_address),
.d(d),
.max_tick(max_tick_address),
.q(cont_address_sig)
);
cont_test #(.W(N)) con_mux_data
(
.clk(clk),
.rst(rst),
.load(load_ch),
.enable(enab_ch),
.d(d),
.max_tick(max_tick_ch),
.q(cont_ch)
);
generate
case(W)
32:
begin
Mux_4x1 mux_32_uart
(
.select(cont_ch),
.ch_0(final_result_ieee[7:0]),
.ch_1(final_result_ieee[15:8]),
.ch_2(final_result_ieee[23:16]),
.ch_3(final_result_ieee[31:24]),
.data_out(TX_DATA)
);
end
64:
begin
Mux_8x1 mux_64_uart
(
.select(cont_ch),
.ch_0(final_result_ieee[7:0]),
.ch_1(final_result_ieee[15:8]),
.ch_2(final_result_ieee[23:16]),
.ch_3(final_result_ieee[31:24]),
.ch_4(final_result_ieee[39:32]),
.ch_5(final_result_ieee[47:40]),
.ch_6(final_result_ieee[55:48]),
.ch_7(final_result_ieee[63:56]),
.data_out(TX_DATA)
);
end
default:
begin
Mux_4x1 mux_32_uart
(
.select(cont_ch),
.ch_0(final_result_ieee[7:0]),
.ch_1(final_result_ieee[15:8]),
.ch_2(final_result_ieee[23:16]),
.ch_3(final_result_ieee[31:24]),
.data_out(TX_DATA)
);
end
endcase
endgenerate
endmodule
|
// megafunction wizard: %ALTMULT_ADD%
// GENERATION: STANDARD
// VERSION: WM1.0
// MODULE: ALTMULT_ADD
// ============================================================
// File Name: sv_mult27.v
// Megafunction Name(s):
// ALTMULT_ADD
//
// Simulation Library Files(s):
// altera_lnsim
// ============================================================
// ************************************************************
// THIS IS A WIZARD-GENERATED FILE. DO NOT EDIT THIS FILE!
//
// 12.1 Build 177 11/07/2012 SJ Full Version
// ************************************************************
//Copyright (C) 1991-2012 Altera Corporation
//Your use of Altera Corporation's design tools, logic functions
//and other software and tools, and its AMPP partner logic
//functions, and any output files from any of the foregoing
//(including device programming or simulation files), and any
//associated documentation or information are expressly subject
//to the terms and conditions of the Altera Program License
//Subscription Agreement, Altera MegaCore Function License
//Agreement, or other applicable license agreement, including,
//without limitation, that your use is for the sole purpose of
//programming logic devices manufactured by Altera and sold by
//Altera or its authorized distributors. Please refer to the
//applicable agreement for further details.
//altmult_add ACCUM_SLOAD_REGISTER="UNREGISTERED" ADDNSUB_MULTIPLIER_PIPELINE_REGISTER1="UNREGISTERED" ADDNSUB_MULTIPLIER_REGISTER1="CLOCK0" CBX_AUTO_BLACKBOX="ALL" COEF0_0=0 COEF0_1=0 COEF0_2=0 COEF0_3=0 COEF0_4=0 COEF0_5=0 COEF0_6=0 COEF0_7=0 COEF1_0=0 COEF1_1=0 COEF1_2=0 COEF1_3=0 COEF1_4=0 COEF1_5=0 COEF1_6=0 COEF1_7=0 COEF2_0=0 COEF2_1=0 COEF2_2=0 COEF2_3=0 COEF2_4=0 COEF2_5=0 COEF2_6=0 COEF2_7=0 COEF3_0=0 COEF3_1=0 COEF3_2=0 COEF3_3=0 COEF3_4=0 COEF3_5=0 COEF3_6=0 COEF3_7=0 COEFSEL0_REGISTER="UNREGISTERED" DEDICATED_MULTIPLIER_CIRCUITRY="AUTO" DEVICE_FAMILY="Stratix V" INPUT_REGISTER_A0="CLOCK0" INPUT_REGISTER_B0="CLOCK0" INPUT_REGISTER_C0="UNREGISTERED" INPUT_SOURCE_A0="DATAA" INPUT_SOURCE_B0="DATAB" LOADCONST_VALUE=64 MULTIPLIER1_DIRECTION="ADD" MULTIPLIER_REGISTER0="UNREGISTERED" NUMBER_OF_MULTIPLIERS=1 OUTPUT_REGISTER="CLOCK0" port_addnsub1="PORT_UNUSED" port_signa="PORT_UNUSED" port_signb="PORT_UNUSED" PREADDER_DIRECTION_0="ADD" PREADDER_DIRECTION_1="ADD" PREADDER_DIRECTION_2="ADD" PREADDER_DIRECTION_3="ADD" PREADDER_MODE="SIMPLE" REPRESENTATION_A="UNSIGNED" REPRESENTATION_B="UNSIGNED" SIGNED_PIPELINE_REGISTER_A="UNREGISTERED" SIGNED_PIPELINE_REGISTER_B="UNREGISTERED" SIGNED_REGISTER_A="CLOCK0" SIGNED_REGISTER_B="CLOCK0" SYSTOLIC_DELAY1="UNREGISTERED" SYSTOLIC_DELAY3="UNREGISTERED" WIDTH_A=27 WIDTH_B=27 WIDTH_RESULT=54 clock0 dataa datab result
//VERSION_BEGIN 12.1 cbx_alt_ded_mult_y 2012:11:07:18:03:20:SJ cbx_altera_mult_add 2012:11:07:18:03:20:SJ cbx_altmult_add 2012:11:07:18:03:20:SJ cbx_cycloneii 2012:11:07:18:03:20:SJ cbx_lpm_add_sub 2012:11:07:18:03:20:SJ cbx_lpm_mult 2012:11:07:18:03:20:SJ cbx_mgl 2012:11:07:18:50:05:SJ cbx_padd 2012:11:07:18:03:20:SJ cbx_parallel_add 2012:11:07:18:03:20:SJ cbx_stratix 2012:11:07:18:03:20:SJ cbx_stratixii 2012:11:07:18:03:20:SJ cbx_util_mgl 2012:11:07:18:03:20:SJ VERSION_END
// synthesis VERILOG_INPUT_VERSION VERILOG_2001
// altera message_off 10463
//synthesis_resources = altera_mult_add 1 dsp_mac 1
//synopsys translate_off
`timescale 1 ps / 1 ps
//synopsys translate_on
module sv_mult27_mult_add_cfq3
(
clock0,
ena0,
dataa,
datab,
result) ;
input clock0;
input ena0;
input [26:0] dataa;
input [26:0] datab;
output [53:0] result;
`ifndef ALTERA_RESERVED_QIS
// synopsys translate_off
`endif
tri1 clock0;
tri0 [26:0] dataa;
tri0 [26:0] datab;
`ifndef ALTERA_RESERVED_QIS
// synopsys translate_on
`endif
wire [53:0] wire_altera_mult_add1_result;
wire ena1;
wire ena2;
wire ena3;
altera_mult_add altera_mult_add1
(
.chainout_sat_overflow(),
.clock0(clock0),
.dataa(dataa),
.datab(datab),
.ena0(ena0),
.ena1(ena1),
.ena2(ena2),
.ena3(ena3),
.mult0_is_saturated(),
.mult1_is_saturated(),
.mult2_is_saturated(),
.mult3_is_saturated(),
.overflow(),
.result(wire_altera_mult_add1_result),
.scanouta(),
.scanoutb(),
.accum_sload(1'b0),
.aclr0(1'b0),
.aclr1(1'b0),
.aclr2(1'b0),
.aclr3(1'b0),
.addnsub1(1'b1),
.addnsub1_round(1'b0),
.addnsub3(1'b1),
.addnsub3_round(1'b0),
.chainin({1{1'b0}}),
.chainout_round(1'b0),
.chainout_saturate(1'b0),
.clock1(1'b1),
.clock2(1'b1),
.clock3(1'b1),
.coefsel0({3{1'b0}}),
.coefsel1({3{1'b0}}),
.coefsel2({3{1'b0}}),
.coefsel3({3{1'b0}}),
.datac({22{1'b0}}),
.mult01_round(1'b0),
.mult01_saturation(1'b0),
.mult23_round(1'b0),
.mult23_saturation(1'b0),
.output_round(1'b0),
.output_saturate(1'b0),
.rotate(1'b0),
.scanina({27{1'b0}}),
.scaninb({27{1'b0}}),
.shift_right(1'b0),
.signa(1'b0),
.signb(1'b0),
.sourcea({1{1'b0}}),
.sourceb({1{1'b0}}),
.zero_chainout(1'b0),
.zero_loopback(1'b0)
);
defparam
altera_mult_add1.accum_direction = "ADD",
altera_mult_add1.accum_sload_aclr = "ACLR0",
altera_mult_add1.accum_sload_pipeline_aclr = "ACLR0",
altera_mult_add1.accum_sload_pipeline_register = "CLOCK0",
altera_mult_add1.accum_sload_register = "UNREGISTERED",
altera_mult_add1.accumulator = "NO",
altera_mult_add1.adder1_rounding = "NO",
altera_mult_add1.adder3_rounding = "NO",
altera_mult_add1.addnsub1_round_aclr = "ACLR0",
altera_mult_add1.addnsub1_round_pipeline_aclr = "ACLR0",
altera_mult_add1.addnsub1_round_pipeline_register = "CLOCK0",
altera_mult_add1.addnsub1_round_register = "CLOCK0",
altera_mult_add1.addnsub3_round_aclr = "ACLR0",
altera_mult_add1.addnsub3_round_pipeline_aclr = "ACLR0",
altera_mult_add1.addnsub3_round_pipeline_register = "CLOCK0",
altera_mult_add1.addnsub3_round_register = "CLOCK0",
altera_mult_add1.addnsub_multiplier_aclr1 = "ACLR0",
altera_mult_add1.addnsub_multiplier_aclr3 = "ACLR0",
altera_mult_add1.addnsub_multiplier_pipeline_aclr1 = "ACLR0",
altera_mult_add1.addnsub_multiplier_pipeline_aclr3 = "ACLR0",
altera_mult_add1.addnsub_multiplier_pipeline_register1 = "UNREGISTERED",
altera_mult_add1.addnsub_multiplier_pipeline_register3 = "CLOCK0",
altera_mult_add1.addnsub_multiplier_register1 = "CLOCK0",
altera_mult_add1.addnsub_multiplier_register3 = "CLOCK0",
altera_mult_add1.chainout_aclr = "ACLR0",
altera_mult_add1.chainout_adder = "NO",
altera_mult_add1.chainout_register = "CLOCK0",
altera_mult_add1.chainout_round_aclr = "ACLR0",
altera_mult_add1.chainout_round_output_aclr = "ACLR0",
altera_mult_add1.chainout_round_output_register = "CLOCK0",
altera_mult_add1.chainout_round_pipeline_aclr = "ACLR0",
altera_mult_add1.chainout_round_pipeline_register = "CLOCK0",
altera_mult_add1.chainout_round_register = "CLOCK0",
altera_mult_add1.chainout_rounding = "NO",
altera_mult_add1.chainout_saturate_aclr = "ACLR0",
altera_mult_add1.chainout_saturate_output_aclr = "ACLR0",
altera_mult_add1.chainout_saturate_output_register = "CLOCK0",
altera_mult_add1.chainout_saturate_pipeline_aclr = "ACLR0",
altera_mult_add1.chainout_saturate_pipeline_register = "CLOCK0",
altera_mult_add1.chainout_saturate_register = "CLOCK0",
altera_mult_add1.chainout_saturation = "NO",
altera_mult_add1.coef0_0 = 0,
altera_mult_add1.coef0_1 = 0,
altera_mult_add1.coef0_2 = 0,
altera_mult_add1.coef0_3 = 0,
altera_mult_add1.coef0_4 = 0,
altera_mult_add1.coef0_5 = 0,
altera_mult_add1.coef0_6 = 0,
altera_mult_add1.coef0_7 = 0,
altera_mult_add1.coef1_0 = 0,
altera_mult_add1.coef1_1 = 0,
altera_mult_add1.coef1_2 = 0,
altera_mult_add1.coef1_3 = 0,
altera_mult_add1.coef1_4 = 0,
altera_mult_add1.coef1_5 = 0,
altera_mult_add1.coef1_6 = 0,
altera_mult_add1.coef1_7 = 0,
altera_mult_add1.coef2_0 = 0,
altera_mult_add1.coef2_1 = 0,
altera_mult_add1.coef2_2 = 0,
altera_mult_add1.coef2_3 = 0,
altera_mult_add1.coef2_4 = 0,
altera_mult_add1.coef2_5 = 0,
altera_mult_add1.coef2_6 = 0,
altera_mult_add1.coef2_7 = 0,
altera_mult_add1.coef3_0 = 0,
altera_mult_add1.coef3_1 = 0,
altera_mult_add1.coef3_2 = 0,
altera_mult_add1.coef3_3 = 0,
altera_mult_add1.coef3_4 = 0,
altera_mult_add1.coef3_5 = 0,
altera_mult_add1.coef3_6 = 0,
altera_mult_add1.coef3_7 = 0,
altera_mult_add1.coefsel0_aclr = "ACLR0",
altera_mult_add1.coefsel0_register = "UNREGISTERED",
altera_mult_add1.coefsel1_aclr = "ACLR0",
altera_mult_add1.coefsel1_register = "CLOCK0",
altera_mult_add1.coefsel2_aclr = "ACLR0",
altera_mult_add1.coefsel2_register = "CLOCK0",
altera_mult_add1.coefsel3_aclr = "ACLR0",
altera_mult_add1.coefsel3_register = "CLOCK0",
altera_mult_add1.dedicated_multiplier_circuitry = "AUTO",
altera_mult_add1.double_accum = "NO",
altera_mult_add1.dsp_block_balancing = "Auto",
altera_mult_add1.extra_latency = 0,
altera_mult_add1.input_aclr_a0 = "ACLR0",
altera_mult_add1.input_aclr_a1 = "ACLR0",
altera_mult_add1.input_aclr_a2 = "ACLR0",
altera_mult_add1.input_aclr_a3 = "ACLR0",
altera_mult_add1.input_aclr_b0 = "ACLR0",
altera_mult_add1.input_aclr_b1 = "ACLR0",
altera_mult_add1.input_aclr_b2 = "ACLR0",
altera_mult_add1.input_aclr_b3 = "ACLR0",
altera_mult_add1.input_aclr_c0 = "ACLR0",
altera_mult_add1.input_aclr_c1 = "ACLR0",
altera_mult_add1.input_aclr_c2 = "ACLR0",
altera_mult_add1.input_aclr_c3 = "ACLR0",
altera_mult_add1.input_register_a0 = "CLOCK0",
altera_mult_add1.input_register_a1 = "CLOCK0",
altera_mult_add1.input_register_a2 = "CLOCK0",
altera_mult_add1.input_register_a3 = "CLOCK0",
altera_mult_add1.input_register_b0 = "CLOCK0",
altera_mult_add1.input_register_b1 = "CLOCK0",
altera_mult_add1.input_register_b2 = "CLOCK0",
altera_mult_add1.input_register_b3 = "CLOCK0",
altera_mult_add1.input_register_c0 = "UNREGISTERED",
altera_mult_add1.input_register_c1 = "CLOCK0",
altera_mult_add1.input_register_c2 = "CLOCK0",
altera_mult_add1.input_register_c3 = "CLOCK0",
altera_mult_add1.input_source_a0 = "DATAA",
altera_mult_add1.input_source_a1 = "DATAA",
altera_mult_add1.input_source_a2 = "DATAA",
altera_mult_add1.input_source_a3 = "DATAA",
altera_mult_add1.input_source_b0 = "DATAB",
altera_mult_add1.input_source_b1 = "DATAB",
altera_mult_add1.input_source_b2 = "DATAB",
altera_mult_add1.input_source_b3 = "DATAB",
altera_mult_add1.loadconst_control_aclr = "ACLR0",
altera_mult_add1.loadconst_control_register = "CLOCK0",
altera_mult_add1.loadconst_value = 64,
altera_mult_add1.mult01_round_aclr = "ACLR0",
altera_mult_add1.mult01_round_register = "CLOCK0",
altera_mult_add1.mult01_saturation_aclr = "ACLR1",
altera_mult_add1.mult01_saturation_register = "CLOCK0",
altera_mult_add1.mult23_round_aclr = "ACLR0",
altera_mult_add1.mult23_round_register = "CLOCK0",
altera_mult_add1.mult23_saturation_aclr = "ACLR0",
altera_mult_add1.mult23_saturation_register = "CLOCK0",
altera_mult_add1.multiplier01_rounding = "NO",
altera_mult_add1.multiplier01_saturation = "NO",
altera_mult_add1.multiplier1_direction = "ADD",
altera_mult_add1.multiplier23_rounding = "NO",
altera_mult_add1.multiplier23_saturation = "NO",
altera_mult_add1.multiplier3_direction = "ADD",
altera_mult_add1.multiplier_aclr0 = "ACLR0",
altera_mult_add1.multiplier_aclr1 = "ACLR0",
altera_mult_add1.multiplier_aclr2 = "ACLR0",
altera_mult_add1.multiplier_aclr3 = "ACLR0",
altera_mult_add1.multiplier_register0 = "UNREGISTERED",
altera_mult_add1.multiplier_register1 = "CLOCK0",
altera_mult_add1.multiplier_register2 = "CLOCK0",
altera_mult_add1.multiplier_register3 = "CLOCK0",
altera_mult_add1.number_of_multipliers = 1,
altera_mult_add1.output_aclr = "ACLR0",
altera_mult_add1.output_register = "CLOCK0",
altera_mult_add1.output_round_aclr = "ACLR0",
altera_mult_add1.output_round_pipeline_aclr = "ACLR0",
altera_mult_add1.output_round_pipeline_register = "CLOCK0",
altera_mult_add1.output_round_register = "CLOCK0",
altera_mult_add1.output_round_type = "NEAREST_INTEGER",
altera_mult_add1.output_rounding = "NO",
altera_mult_add1.output_saturate_aclr = "ACLR0",
altera_mult_add1.output_saturate_pipeline_aclr = "ACLR0",
altera_mult_add1.output_saturate_pipeline_register = "CLOCK0",
altera_mult_add1.output_saturate_register = "CLOCK0",
altera_mult_add1.output_saturate_type = "ASYMMETRIC",
altera_mult_add1.output_saturation = "NO",
altera_mult_add1.port_addnsub1 = "PORT_UNUSED",
altera_mult_add1.port_addnsub3 = "PORT_UNUSED",
altera_mult_add1.port_chainout_sat_is_overflow = "PORT_UNUSED",
altera_mult_add1.port_output_is_overflow = "PORT_UNUSED",
altera_mult_add1.port_signa = "PORT_UNUSED",
altera_mult_add1.port_signb = "PORT_UNUSED",
altera_mult_add1.preadder_direction_0 = "ADD",
altera_mult_add1.preadder_direction_1 = "ADD",
altera_mult_add1.preadder_direction_2 = "ADD",
altera_mult_add1.preadder_direction_3 = "ADD",
altera_mult_add1.preadder_mode = "SIMPLE",
altera_mult_add1.representation_a = "UNSIGNED",
altera_mult_add1.representation_b = "UNSIGNED",
altera_mult_add1.rotate_aclr = "ACLR0",
altera_mult_add1.rotate_output_aclr = "ACLR0",
altera_mult_add1.rotate_output_register = "CLOCK0",
altera_mult_add1.rotate_pipeline_aclr = "ACLR0",
altera_mult_add1.rotate_pipeline_register = "CLOCK0",
altera_mult_add1.rotate_register = "CLOCK0",
altera_mult_add1.scanouta_aclr = "ACLR0",
altera_mult_add1.scanouta_register = "UNREGISTERED",
altera_mult_add1.selected_device_family = "Stratix V",
altera_mult_add1.shift_mode = "NO",
altera_mult_add1.shift_right_aclr = "ACLR0",
altera_mult_add1.shift_right_output_aclr = "ACLR0",
altera_mult_add1.shift_right_output_register = "CLOCK0",
altera_mult_add1.shift_right_pipeline_aclr = "ACLR0",
altera_mult_add1.shift_right_pipeline_register = "CLOCK0",
altera_mult_add1.shift_right_register = "CLOCK0",
altera_mult_add1.signed_aclr_a = "ACLR0",
altera_mult_add1.signed_aclr_b = "ACLR0",
altera_mult_add1.signed_pipeline_aclr_a = "ACLR0",
altera_mult_add1.signed_pipeline_aclr_b = "ACLR0",
altera_mult_add1.signed_pipeline_register_a = "UNREGISTERED",
altera_mult_add1.signed_pipeline_register_b = "UNREGISTERED",
altera_mult_add1.signed_register_a = "CLOCK0",
altera_mult_add1.signed_register_b = "CLOCK0",
altera_mult_add1.systolic_aclr1 = "ACLR0",
altera_mult_add1.systolic_aclr3 = "ACLR0",
altera_mult_add1.systolic_delay1 = "UNREGISTERED",
altera_mult_add1.systolic_delay3 = "UNREGISTERED",
altera_mult_add1.width_a = 27,
altera_mult_add1.width_b = 27,
altera_mult_add1.width_c = 22,
altera_mult_add1.width_chainin = 1,
altera_mult_add1.width_coef = 18,
altera_mult_add1.width_msb = 17,
altera_mult_add1.width_result = 54,
altera_mult_add1.width_saturate_sign = 1,
altera_mult_add1.zero_chainout_output_aclr = "ACLR0",
altera_mult_add1.zero_chainout_output_register = "CLOCK0",
altera_mult_add1.zero_loopback_aclr = "ACLR0",
altera_mult_add1.zero_loopback_output_aclr = "ACLR0",
altera_mult_add1.zero_loopback_output_register = "CLOCK0",
altera_mult_add1.zero_loopback_pipeline_aclr = "ACLR0",
altera_mult_add1.zero_loopback_pipeline_register = "CLOCK0",
altera_mult_add1.zero_loopback_register = "CLOCK0",
altera_mult_add1.lpm_type = "altera_mult_add";
assign
ena1 = 1'b1,
ena2 = 1'b1,
ena3 = 1'b1,
result = wire_altera_mult_add1_result;
endmodule //sv_mult27_mult_add_cfq3
//VALID FILE
// synopsys translate_off
`timescale 1 ps / 1 ps
// synopsys translate_on
module sv_mult27 (
clock0,
ena0,
dataa_0,
datab_0,
result);
input clock0;
input ena0;
input [26:0] dataa_0;
input [26:0] datab_0;
output [53:0] result;
`ifndef ALTERA_RESERVED_QIS
// synopsys translate_off
`endif
tri1 clock0;
tri0 [26:0] dataa_0;
tri0 [26:0] datab_0;
`ifndef ALTERA_RESERVED_QIS
// synopsys translate_on
`endif
wire [53:0] sub_wire0;
wire [53:0] result = sub_wire0[53:0];
sv_mult27_mult_add_cfq3 sv_mult27_mult_add_cfq3_component (
.clock0 (clock0),
.ena0(ena0),
.dataa (dataa_0),
.datab (datab_0),
.result (sub_wire0));
endmodule
// ============================================================
// CNX file retrieval info
// ============================================================
// Retrieval info: PRIVATE: ACCUM_SLOAD_ACLR_SRC_MULT0 NUMERIC "3"
// Retrieval info: PRIVATE: ACCUM_SLOAD_CLK_SRC_MULT0 NUMERIC "0"
// Retrieval info: PRIVATE: ADDNSUB1_ACLR_SRC NUMERIC "2"
// Retrieval info: PRIVATE: ADDNSUB1_CLK_SRC NUMERIC "0"
// Retrieval info: PRIVATE: ADDNSUB1_PIPE_ACLR_SRC NUMERIC "3"
// Retrieval info: PRIVATE: ADDNSUB1_PIPE_CLK_SRC NUMERIC "0"
// Retrieval info: PRIVATE: ADDNSUB1_PIPE_REG STRING "0"
// Retrieval info: PRIVATE: ADDNSUB1_REG STRING "1"
// Retrieval info: PRIVATE: ADDNSUB3_ACLR_SRC NUMERIC "3"
// Retrieval info: PRIVATE: ADDNSUB3_CLK_SRC NUMERIC "0"
// Retrieval info: PRIVATE: ADDNSUB3_PIPE_ACLR_SRC NUMERIC "3"
// Retrieval info: PRIVATE: ADDNSUB3_PIPE_CLK_SRC NUMERIC "0"
// Retrieval info: PRIVATE: ADDNSUB3_PIPE_REG STRING "0"
// Retrieval info: PRIVATE: ADDNSUB3_REG STRING "1"
// Retrieval info: PRIVATE: ADD_ENABLE NUMERIC "0"
// Retrieval info: PRIVATE: ALL_REG_ACLR NUMERIC "0"
// Retrieval info: PRIVATE: A_ACLR_SRC_MULT0 NUMERIC "2"
// Retrieval info: PRIVATE: A_CLK_SRC_MULT0 NUMERIC "0"
// Retrieval info: PRIVATE: B_ACLR_SRC_MULT0 NUMERIC "3"
// Retrieval info: PRIVATE: B_CLK_SRC_MULT0 NUMERIC "0"
// Retrieval info: PRIVATE: C_ACLR_SRC_MULT0 NUMERIC "3"
// Retrieval info: PRIVATE: C_CLK_SRC_MULT0 NUMERIC "0"
// Retrieval info: PRIVATE: ENABLE_PRELOAD_CONSTANT NUMERIC "0"
// Retrieval info: PRIVATE: HAS_MAC STRING "0"
// Retrieval info: PRIVATE: HAS_SAT_ROUND STRING "0"
// Retrieval info: PRIVATE: IMPL_STYLE_DEDICATED NUMERIC "0"
// Retrieval info: PRIVATE: IMPL_STYLE_DEFAULT NUMERIC "1"
// Retrieval info: PRIVATE: IMPL_STYLE_LCELL NUMERIC "0"
// Retrieval info: PRIVATE: INTENDED_DEVICE_FAMILY STRING "Stratix V"
// Retrieval info: PRIVATE: MULT_COEFSEL STRING "0"
// Retrieval info: PRIVATE: MULT_REGA0 NUMERIC "1"
// Retrieval info: PRIVATE: MULT_REGB0 NUMERIC "1"
// Retrieval info: PRIVATE: MULT_REGC NUMERIC "0"
// Retrieval info: PRIVATE: MULT_REGOUT0 NUMERIC "0"
// Retrieval info: PRIVATE: MULT_REG_ACCUM_SLOAD NUMERIC "0"
// Retrieval info: PRIVATE: MULT_REG_SYSTOLIC_DELAY NUMERIC "0"
// Retrieval info: PRIVATE: NUM_MULT STRING "1"
// Retrieval info: PRIVATE: OP1 STRING "Add"
// Retrieval info: PRIVATE: OP3 STRING "Add"
// Retrieval info: PRIVATE: OUTPUT_EXTRA_LAT NUMERIC "0"
// Retrieval info: PRIVATE: OUTPUT_REG_ACLR_SRC NUMERIC "2"
// Retrieval info: PRIVATE: OUTPUT_REG_CLK_SRC NUMERIC "0"
// Retrieval info: PRIVATE: Q_ACLR_SRC_MULT0 NUMERIC "3"
// Retrieval info: PRIVATE: Q_CLK_SRC_MULT0 NUMERIC "0"
// Retrieval info: PRIVATE: REG_OUT NUMERIC "1"
// Retrieval info: PRIVATE: RNFORMAT STRING "54"
// Retrieval info: PRIVATE: RQFORMAT STRING "Q1.15"
// Retrieval info: PRIVATE: RTS_WIDTH STRING "54"
// Retrieval info: PRIVATE: SAME_CONFIG NUMERIC "1"
// Retrieval info: PRIVATE: SAME_CONTROL_SRC_A0 NUMERIC "1"
// Retrieval info: PRIVATE: SAME_CONTROL_SRC_B0 NUMERIC "1"
// Retrieval info: PRIVATE: SCANOUTA NUMERIC "0"
// Retrieval info: PRIVATE: SCANOUTB NUMERIC "0"
// Retrieval info: PRIVATE: SHIFTOUTA_ACLR_SRC NUMERIC "3"
// Retrieval info: PRIVATE: SHIFTOUTA_CLK_SRC NUMERIC "0"
// Retrieval info: PRIVATE: SHIFTOUTA_REG STRING "0"
// Retrieval info: PRIVATE: SIGNA STRING "UNSIGNED"
// Retrieval info: PRIVATE: SIGNA_ACLR_SRC NUMERIC "3"
// Retrieval info: PRIVATE: SIGNA_CLK_SRC NUMERIC "0"
// Retrieval info: PRIVATE: SIGNA_PIPE_ACLR_SRC NUMERIC "3"
// Retrieval info: PRIVATE: SIGNA_PIPE_CLK_SRC NUMERIC "0"
// Retrieval info: PRIVATE: SIGNA_PIPE_REG STRING "0"
// Retrieval info: PRIVATE: SIGNA_REG STRING "1"
// Retrieval info: PRIVATE: SIGNB STRING "UNSIGNED"
// Retrieval info: PRIVATE: SIGNB_ACLR_SRC NUMERIC "3"
// Retrieval info: PRIVATE: SIGNB_CLK_SRC NUMERIC "0"
// Retrieval info: PRIVATE: SIGNB_PIPE_ACLR_SRC NUMERIC "3"
// Retrieval info: PRIVATE: SIGNB_PIPE_CLK_SRC NUMERIC "0"
// Retrieval info: PRIVATE: SIGNB_PIPE_REG STRING "0"
// Retrieval info: PRIVATE: SIGNB_REG STRING "1"
// Retrieval info: PRIVATE: SRCA0 STRING "Multiplier input"
// Retrieval info: PRIVATE: SRCB0 STRING "Multiplier input"
// Retrieval info: PRIVATE: SYNTH_WRAPPER_GEN_POSTFIX STRING "0"
// Retrieval info: PRIVATE: SYSTOLIC_ACLR_SRC_MULT0 NUMERIC "3"
// Retrieval info: PRIVATE: SYSTOLIC_CLK_SRC_MULT0 NUMERIC "0"
// Retrieval info: PRIVATE: WIDTHA STRING "27"
// Retrieval info: PRIVATE: WIDTHB STRING "27"
// Retrieval info: LIBRARY: altera_mf altera_mf.altera_mf_components.all
// Retrieval info: CONSTANT: ACCUM_SLOAD_REGISTER STRING "UNREGISTERED"
// Retrieval info: CONSTANT: ADDNSUB_MULTIPLIER_ACLR1 STRING "UNUSED"
// Retrieval info: CONSTANT: ADDNSUB_MULTIPLIER_PIPELINE_REGISTER1 STRING "UNREGISTERED"
// Retrieval info: CONSTANT: ADDNSUB_MULTIPLIER_REGISTER1 STRING "CLOCK0"
// Retrieval info: CONSTANT: COEF0_0 NUMERIC "0"
// Retrieval info: CONSTANT: COEF0_1 NUMERIC "0"
// Retrieval info: CONSTANT: COEF0_2 NUMERIC "0"
// Retrieval info: CONSTANT: COEF0_3 NUMERIC "0"
// Retrieval info: CONSTANT: COEF0_4 NUMERIC "0"
// Retrieval info: CONSTANT: COEF0_5 NUMERIC "0"
// Retrieval info: CONSTANT: COEF0_6 NUMERIC "0"
// Retrieval info: CONSTANT: COEF0_7 NUMERIC "0"
// Retrieval info: CONSTANT: COEF1_0 NUMERIC "0"
// Retrieval info: CONSTANT: COEF1_1 NUMERIC "0"
// Retrieval info: CONSTANT: COEF1_2 NUMERIC "0"
// Retrieval info: CONSTANT: COEF1_3 NUMERIC "0"
// Retrieval info: CONSTANT: COEF1_4 NUMERIC "0"
// Retrieval info: CONSTANT: COEF1_5 NUMERIC "0"
// Retrieval info: CONSTANT: COEF1_6 NUMERIC "0"
// Retrieval info: CONSTANT: COEF1_7 NUMERIC "0"
// Retrieval info: CONSTANT: COEF2_0 NUMERIC "0"
// Retrieval info: CONSTANT: COEF2_1 NUMERIC "0"
// Retrieval info: CONSTANT: COEF2_2 NUMERIC "0"
// Retrieval info: CONSTANT: COEF2_3 NUMERIC "0"
// Retrieval info: CONSTANT: COEF2_4 NUMERIC "0"
// Retrieval info: CONSTANT: COEF2_5 NUMERIC "0"
// Retrieval info: CONSTANT: COEF2_6 NUMERIC "0"
// Retrieval info: CONSTANT: COEF2_7 NUMERIC "0"
// Retrieval info: CONSTANT: COEF3_0 NUMERIC "0"
// Retrieval info: CONSTANT: COEF3_1 NUMERIC "0"
// Retrieval info: CONSTANT: COEF3_2 NUMERIC "0"
// Retrieval info: CONSTANT: COEF3_3 NUMERIC "0"
// Retrieval info: CONSTANT: COEF3_4 NUMERIC "0"
// Retrieval info: CONSTANT: COEF3_5 NUMERIC "0"
// Retrieval info: CONSTANT: COEF3_6 NUMERIC "0"
// Retrieval info: CONSTANT: COEF3_7 NUMERIC "0"
// Retrieval info: CONSTANT: COEFSEL0_REGISTER STRING "UNREGISTERED"
// Retrieval info: CONSTANT: DEDICATED_MULTIPLIER_CIRCUITRY STRING "AUTO"
// Retrieval info: CONSTANT: INPUT_ACLR_A0 STRING "UNUSED"
// Retrieval info: CONSTANT: INPUT_ACLR_B0 STRING "UNUSED"
// Retrieval info: CONSTANT: INPUT_REGISTER_A0 STRING "CLOCK0"
// Retrieval info: CONSTANT: INPUT_REGISTER_B0 STRING "CLOCK0"
// Retrieval info: CONSTANT: INPUT_REGISTER_C0 STRING "UNREGISTERED"
// Retrieval info: CONSTANT: INPUT_SOURCE_A0 STRING "DATAA"
// Retrieval info: CONSTANT: INPUT_SOURCE_B0 STRING "DATAB"
// Retrieval info: CONSTANT: INTENDED_DEVICE_FAMILY STRING "Stratix V"
// Retrieval info: CONSTANT: LOADCONST_VALUE NUMERIC "64"
// Retrieval info: CONSTANT: LPM_TYPE STRING "altmult_add"
// Retrieval info: CONSTANT: MULTIPLIER1_DIRECTION STRING "ADD"
// Retrieval info: CONSTANT: MULTIPLIER_ACLR0 STRING "UNUSED"
// Retrieval info: CONSTANT: MULTIPLIER_REGISTER0 STRING "UNREGISTERED"
// Retrieval info: CONSTANT: NUMBER_OF_MULTIPLIERS NUMERIC "1"
// Retrieval info: CONSTANT: OUTPUT_ACLR STRING "UNUSED"
// Retrieval info: CONSTANT: OUTPUT_REGISTER STRING "CLOCK0"
// Retrieval info: CONSTANT: PORT_ADDNSUB1 STRING "PORT_UNUSED"
// Retrieval info: CONSTANT: PORT_SIGNA STRING "PORT_UNUSED"
// Retrieval info: CONSTANT: PORT_SIGNB STRING "PORT_UNUSED"
// Retrieval info: CONSTANT: PREADDER_DIRECTION_0 STRING "ADD"
// Retrieval info: CONSTANT: PREADDER_DIRECTION_1 STRING "ADD"
// Retrieval info: CONSTANT: PREADDER_DIRECTION_2 STRING "ADD"
// Retrieval info: CONSTANT: PREADDER_DIRECTION_3 STRING "ADD"
// Retrieval info: CONSTANT: PREADDER_MODE STRING "SIMPLE"
// Retrieval info: CONSTANT: REPRESENTATION_A STRING "UNSIGNED"
// Retrieval info: CONSTANT: REPRESENTATION_B STRING "UNSIGNED"
// Retrieval info: CONSTANT: SIGNED_ACLR_A STRING "UNUSED"
// Retrieval info: CONSTANT: SIGNED_ACLR_B STRING "UNUSED"
// Retrieval info: CONSTANT: SIGNED_PIPELINE_REGISTER_A STRING "UNREGISTERED"
// Retrieval info: CONSTANT: SIGNED_PIPELINE_REGISTER_B STRING "UNREGISTERED"
// Retrieval info: CONSTANT: SIGNED_REGISTER_A STRING "CLOCK0"
// Retrieval info: CONSTANT: SIGNED_REGISTER_B STRING "CLOCK0"
// Retrieval info: CONSTANT: SYSTOLIC_DELAY1 STRING "UNREGISTERED"
// Retrieval info: CONSTANT: SYSTOLIC_DELAY3 STRING "UNREGISTERED"
// Retrieval info: CONSTANT: WIDTH_A NUMERIC "27"
// Retrieval info: CONSTANT: WIDTH_B NUMERIC "27"
// Retrieval info: CONSTANT: WIDTH_RESULT NUMERIC "54"
// Retrieval info: USED_PORT: clock0 0 0 0 0 INPUT VCC "clock0"
// Retrieval info: USED_PORT: dataa_0 0 0 27 0 INPUT GND "dataa_0[26..0]"
// Retrieval info: USED_PORT: datab_0 0 0 27 0 INPUT GND "datab_0[26..0]"
// Retrieval info: USED_PORT: result 0 0 54 0 OUTPUT GND "result[53..0]"
// Retrieval info: CONNECT: @clock0 0 0 0 0 clock0 0 0 0 0
// Retrieval info: CONNECT: @dataa 0 0 27 0 dataa_0 0 0 27 0
// Retrieval info: CONNECT: @datab 0 0 27 0 datab_0 0 0 27 0
// Retrieval info: CONNECT: result 0 0 54 0 @result 0 0 54 0
// Retrieval info: GEN_FILE: TYPE_NORMAL sv_mult27.v TRUE
// Retrieval info: GEN_FILE: TYPE_NORMAL sv_mult27.inc FALSE
// Retrieval info: GEN_FILE: TYPE_NORMAL sv_mult27.cmp FALSE
// Retrieval info: GEN_FILE: TYPE_NORMAL sv_mult27.bsf FALSE
// Retrieval info: GEN_FILE: TYPE_NORMAL sv_mult27_inst.v FALSE
// Retrieval info: GEN_FILE: TYPE_NORMAL sv_mult27_bb.v TRUE
// Retrieval info: LIB_FILE: altera_lnsim
|
// megafunction wizard: %ALTMULT_ADD%
// GENERATION: STANDARD
// VERSION: WM1.0
// MODULE: ALTMULT_ADD
// ============================================================
// File Name: sv_mult27.v
// Megafunction Name(s):
// ALTMULT_ADD
//
// Simulation Library Files(s):
// altera_lnsim
// ============================================================
// ************************************************************
// THIS IS A WIZARD-GENERATED FILE. DO NOT EDIT THIS FILE!
//
// 12.1 Build 177 11/07/2012 SJ Full Version
// ************************************************************
//Copyright (C) 1991-2012 Altera Corporation
//Your use of Altera Corporation's design tools, logic functions
//and other software and tools, and its AMPP partner logic
//functions, and any output files from any of the foregoing
//(including device programming or simulation files), and any
//associated documentation or information are expressly subject
//to the terms and conditions of the Altera Program License
//Subscription Agreement, Altera MegaCore Function License
//Agreement, or other applicable license agreement, including,
//without limitation, that your use is for the sole purpose of
//programming logic devices manufactured by Altera and sold by
//Altera or its authorized distributors. Please refer to the
//applicable agreement for further details.
//altmult_add ACCUM_SLOAD_REGISTER="UNREGISTERED" ADDNSUB_MULTIPLIER_PIPELINE_REGISTER1="UNREGISTERED" ADDNSUB_MULTIPLIER_REGISTER1="CLOCK0" CBX_AUTO_BLACKBOX="ALL" COEF0_0=0 COEF0_1=0 COEF0_2=0 COEF0_3=0 COEF0_4=0 COEF0_5=0 COEF0_6=0 COEF0_7=0 COEF1_0=0 COEF1_1=0 COEF1_2=0 COEF1_3=0 COEF1_4=0 COEF1_5=0 COEF1_6=0 COEF1_7=0 COEF2_0=0 COEF2_1=0 COEF2_2=0 COEF2_3=0 COEF2_4=0 COEF2_5=0 COEF2_6=0 COEF2_7=0 COEF3_0=0 COEF3_1=0 COEF3_2=0 COEF3_3=0 COEF3_4=0 COEF3_5=0 COEF3_6=0 COEF3_7=0 COEFSEL0_REGISTER="UNREGISTERED" DEDICATED_MULTIPLIER_CIRCUITRY="AUTO" DEVICE_FAMILY="Stratix V" INPUT_REGISTER_A0="CLOCK0" INPUT_REGISTER_B0="CLOCK0" INPUT_REGISTER_C0="UNREGISTERED" INPUT_SOURCE_A0="DATAA" INPUT_SOURCE_B0="DATAB" LOADCONST_VALUE=64 MULTIPLIER1_DIRECTION="ADD" MULTIPLIER_REGISTER0="UNREGISTERED" NUMBER_OF_MULTIPLIERS=1 OUTPUT_REGISTER="CLOCK0" port_addnsub1="PORT_UNUSED" port_signa="PORT_UNUSED" port_signb="PORT_UNUSED" PREADDER_DIRECTION_0="ADD" PREADDER_DIRECTION_1="ADD" PREADDER_DIRECTION_2="ADD" PREADDER_DIRECTION_3="ADD" PREADDER_MODE="SIMPLE" REPRESENTATION_A="UNSIGNED" REPRESENTATION_B="UNSIGNED" SIGNED_PIPELINE_REGISTER_A="UNREGISTERED" SIGNED_PIPELINE_REGISTER_B="UNREGISTERED" SIGNED_REGISTER_A="CLOCK0" SIGNED_REGISTER_B="CLOCK0" SYSTOLIC_DELAY1="UNREGISTERED" SYSTOLIC_DELAY3="UNREGISTERED" WIDTH_A=27 WIDTH_B=27 WIDTH_RESULT=54 clock0 dataa datab result
//VERSION_BEGIN 12.1 cbx_alt_ded_mult_y 2012:11:07:18:03:20:SJ cbx_altera_mult_add 2012:11:07:18:03:20:SJ cbx_altmult_add 2012:11:07:18:03:20:SJ cbx_cycloneii 2012:11:07:18:03:20:SJ cbx_lpm_add_sub 2012:11:07:18:03:20:SJ cbx_lpm_mult 2012:11:07:18:03:20:SJ cbx_mgl 2012:11:07:18:50:05:SJ cbx_padd 2012:11:07:18:03:20:SJ cbx_parallel_add 2012:11:07:18:03:20:SJ cbx_stratix 2012:11:07:18:03:20:SJ cbx_stratixii 2012:11:07:18:03:20:SJ cbx_util_mgl 2012:11:07:18:03:20:SJ VERSION_END
// synthesis VERILOG_INPUT_VERSION VERILOG_2001
// altera message_off 10463
//synthesis_resources = altera_mult_add 1 dsp_mac 1
//synopsys translate_off
`timescale 1 ps / 1 ps
//synopsys translate_on
module sv_mult27_mult_add_cfq3
(
clock0,
ena0,
dataa,
datab,
result) ;
input clock0;
input ena0;
input [26:0] dataa;
input [26:0] datab;
output [53:0] result;
`ifndef ALTERA_RESERVED_QIS
// synopsys translate_off
`endif
tri1 clock0;
tri0 [26:0] dataa;
tri0 [26:0] datab;
`ifndef ALTERA_RESERVED_QIS
// synopsys translate_on
`endif
wire [53:0] wire_altera_mult_add1_result;
wire ena1;
wire ena2;
wire ena3;
altera_mult_add altera_mult_add1
(
.chainout_sat_overflow(),
.clock0(clock0),
.dataa(dataa),
.datab(datab),
.ena0(ena0),
.ena1(ena1),
.ena2(ena2),
.ena3(ena3),
.mult0_is_saturated(),
.mult1_is_saturated(),
.mult2_is_saturated(),
.mult3_is_saturated(),
.overflow(),
.result(wire_altera_mult_add1_result),
.scanouta(),
.scanoutb(),
.accum_sload(1'b0),
.aclr0(1'b0),
.aclr1(1'b0),
.aclr2(1'b0),
.aclr3(1'b0),
.addnsub1(1'b1),
.addnsub1_round(1'b0),
.addnsub3(1'b1),
.addnsub3_round(1'b0),
.chainin({1{1'b0}}),
.chainout_round(1'b0),
.chainout_saturate(1'b0),
.clock1(1'b1),
.clock2(1'b1),
.clock3(1'b1),
.coefsel0({3{1'b0}}),
.coefsel1({3{1'b0}}),
.coefsel2({3{1'b0}}),
.coefsel3({3{1'b0}}),
.datac({22{1'b0}}),
.mult01_round(1'b0),
.mult01_saturation(1'b0),
.mult23_round(1'b0),
.mult23_saturation(1'b0),
.output_round(1'b0),
.output_saturate(1'b0),
.rotate(1'b0),
.scanina({27{1'b0}}),
.scaninb({27{1'b0}}),
.shift_right(1'b0),
.signa(1'b0),
.signb(1'b0),
.sourcea({1{1'b0}}),
.sourceb({1{1'b0}}),
.zero_chainout(1'b0),
.zero_loopback(1'b0)
);
defparam
altera_mult_add1.accum_direction = "ADD",
altera_mult_add1.accum_sload_aclr = "ACLR0",
altera_mult_add1.accum_sload_pipeline_aclr = "ACLR0",
altera_mult_add1.accum_sload_pipeline_register = "CLOCK0",
altera_mult_add1.accum_sload_register = "UNREGISTERED",
altera_mult_add1.accumulator = "NO",
altera_mult_add1.adder1_rounding = "NO",
altera_mult_add1.adder3_rounding = "NO",
altera_mult_add1.addnsub1_round_aclr = "ACLR0",
altera_mult_add1.addnsub1_round_pipeline_aclr = "ACLR0",
altera_mult_add1.addnsub1_round_pipeline_register = "CLOCK0",
altera_mult_add1.addnsub1_round_register = "CLOCK0",
altera_mult_add1.addnsub3_round_aclr = "ACLR0",
altera_mult_add1.addnsub3_round_pipeline_aclr = "ACLR0",
altera_mult_add1.addnsub3_round_pipeline_register = "CLOCK0",
altera_mult_add1.addnsub3_round_register = "CLOCK0",
altera_mult_add1.addnsub_multiplier_aclr1 = "ACLR0",
altera_mult_add1.addnsub_multiplier_aclr3 = "ACLR0",
altera_mult_add1.addnsub_multiplier_pipeline_aclr1 = "ACLR0",
altera_mult_add1.addnsub_multiplier_pipeline_aclr3 = "ACLR0",
altera_mult_add1.addnsub_multiplier_pipeline_register1 = "UNREGISTERED",
altera_mult_add1.addnsub_multiplier_pipeline_register3 = "CLOCK0",
altera_mult_add1.addnsub_multiplier_register1 = "CLOCK0",
altera_mult_add1.addnsub_multiplier_register3 = "CLOCK0",
altera_mult_add1.chainout_aclr = "ACLR0",
altera_mult_add1.chainout_adder = "NO",
altera_mult_add1.chainout_register = "CLOCK0",
altera_mult_add1.chainout_round_aclr = "ACLR0",
altera_mult_add1.chainout_round_output_aclr = "ACLR0",
altera_mult_add1.chainout_round_output_register = "CLOCK0",
altera_mult_add1.chainout_round_pipeline_aclr = "ACLR0",
altera_mult_add1.chainout_round_pipeline_register = "CLOCK0",
altera_mult_add1.chainout_round_register = "CLOCK0",
altera_mult_add1.chainout_rounding = "NO",
altera_mult_add1.chainout_saturate_aclr = "ACLR0",
altera_mult_add1.chainout_saturate_output_aclr = "ACLR0",
altera_mult_add1.chainout_saturate_output_register = "CLOCK0",
altera_mult_add1.chainout_saturate_pipeline_aclr = "ACLR0",
altera_mult_add1.chainout_saturate_pipeline_register = "CLOCK0",
altera_mult_add1.chainout_saturate_register = "CLOCK0",
altera_mult_add1.chainout_saturation = "NO",
altera_mult_add1.coef0_0 = 0,
altera_mult_add1.coef0_1 = 0,
altera_mult_add1.coef0_2 = 0,
altera_mult_add1.coef0_3 = 0,
altera_mult_add1.coef0_4 = 0,
altera_mult_add1.coef0_5 = 0,
altera_mult_add1.coef0_6 = 0,
altera_mult_add1.coef0_7 = 0,
altera_mult_add1.coef1_0 = 0,
altera_mult_add1.coef1_1 = 0,
altera_mult_add1.coef1_2 = 0,
altera_mult_add1.coef1_3 = 0,
altera_mult_add1.coef1_4 = 0,
altera_mult_add1.coef1_5 = 0,
altera_mult_add1.coef1_6 = 0,
altera_mult_add1.coef1_7 = 0,
altera_mult_add1.coef2_0 = 0,
altera_mult_add1.coef2_1 = 0,
altera_mult_add1.coef2_2 = 0,
altera_mult_add1.coef2_3 = 0,
altera_mult_add1.coef2_4 = 0,
altera_mult_add1.coef2_5 = 0,
altera_mult_add1.coef2_6 = 0,
altera_mult_add1.coef2_7 = 0,
altera_mult_add1.coef3_0 = 0,
altera_mult_add1.coef3_1 = 0,
altera_mult_add1.coef3_2 = 0,
altera_mult_add1.coef3_3 = 0,
altera_mult_add1.coef3_4 = 0,
altera_mult_add1.coef3_5 = 0,
altera_mult_add1.coef3_6 = 0,
altera_mult_add1.coef3_7 = 0,
altera_mult_add1.coefsel0_aclr = "ACLR0",
altera_mult_add1.coefsel0_register = "UNREGISTERED",
altera_mult_add1.coefsel1_aclr = "ACLR0",
altera_mult_add1.coefsel1_register = "CLOCK0",
altera_mult_add1.coefsel2_aclr = "ACLR0",
altera_mult_add1.coefsel2_register = "CLOCK0",
altera_mult_add1.coefsel3_aclr = "ACLR0",
altera_mult_add1.coefsel3_register = "CLOCK0",
altera_mult_add1.dedicated_multiplier_circuitry = "AUTO",
altera_mult_add1.double_accum = "NO",
altera_mult_add1.dsp_block_balancing = "Auto",
altera_mult_add1.extra_latency = 0,
altera_mult_add1.input_aclr_a0 = "ACLR0",
altera_mult_add1.input_aclr_a1 = "ACLR0",
altera_mult_add1.input_aclr_a2 = "ACLR0",
altera_mult_add1.input_aclr_a3 = "ACLR0",
altera_mult_add1.input_aclr_b0 = "ACLR0",
altera_mult_add1.input_aclr_b1 = "ACLR0",
altera_mult_add1.input_aclr_b2 = "ACLR0",
altera_mult_add1.input_aclr_b3 = "ACLR0",
altera_mult_add1.input_aclr_c0 = "ACLR0",
altera_mult_add1.input_aclr_c1 = "ACLR0",
altera_mult_add1.input_aclr_c2 = "ACLR0",
altera_mult_add1.input_aclr_c3 = "ACLR0",
altera_mult_add1.input_register_a0 = "CLOCK0",
altera_mult_add1.input_register_a1 = "CLOCK0",
altera_mult_add1.input_register_a2 = "CLOCK0",
altera_mult_add1.input_register_a3 = "CLOCK0",
altera_mult_add1.input_register_b0 = "CLOCK0",
altera_mult_add1.input_register_b1 = "CLOCK0",
altera_mult_add1.input_register_b2 = "CLOCK0",
altera_mult_add1.input_register_b3 = "CLOCK0",
altera_mult_add1.input_register_c0 = "UNREGISTERED",
altera_mult_add1.input_register_c1 = "CLOCK0",
altera_mult_add1.input_register_c2 = "CLOCK0",
altera_mult_add1.input_register_c3 = "CLOCK0",
altera_mult_add1.input_source_a0 = "DATAA",
altera_mult_add1.input_source_a1 = "DATAA",
altera_mult_add1.input_source_a2 = "DATAA",
altera_mult_add1.input_source_a3 = "DATAA",
altera_mult_add1.input_source_b0 = "DATAB",
altera_mult_add1.input_source_b1 = "DATAB",
altera_mult_add1.input_source_b2 = "DATAB",
altera_mult_add1.input_source_b3 = "DATAB",
altera_mult_add1.loadconst_control_aclr = "ACLR0",
altera_mult_add1.loadconst_control_register = "CLOCK0",
altera_mult_add1.loadconst_value = 64,
altera_mult_add1.mult01_round_aclr = "ACLR0",
altera_mult_add1.mult01_round_register = "CLOCK0",
altera_mult_add1.mult01_saturation_aclr = "ACLR1",
altera_mult_add1.mult01_saturation_register = "CLOCK0",
altera_mult_add1.mult23_round_aclr = "ACLR0",
altera_mult_add1.mult23_round_register = "CLOCK0",
altera_mult_add1.mult23_saturation_aclr = "ACLR0",
altera_mult_add1.mult23_saturation_register = "CLOCK0",
altera_mult_add1.multiplier01_rounding = "NO",
altera_mult_add1.multiplier01_saturation = "NO",
altera_mult_add1.multiplier1_direction = "ADD",
altera_mult_add1.multiplier23_rounding = "NO",
altera_mult_add1.multiplier23_saturation = "NO",
altera_mult_add1.multiplier3_direction = "ADD",
altera_mult_add1.multiplier_aclr0 = "ACLR0",
altera_mult_add1.multiplier_aclr1 = "ACLR0",
altera_mult_add1.multiplier_aclr2 = "ACLR0",
altera_mult_add1.multiplier_aclr3 = "ACLR0",
altera_mult_add1.multiplier_register0 = "UNREGISTERED",
altera_mult_add1.multiplier_register1 = "CLOCK0",
altera_mult_add1.multiplier_register2 = "CLOCK0",
altera_mult_add1.multiplier_register3 = "CLOCK0",
altera_mult_add1.number_of_multipliers = 1,
altera_mult_add1.output_aclr = "ACLR0",
altera_mult_add1.output_register = "CLOCK0",
altera_mult_add1.output_round_aclr = "ACLR0",
altera_mult_add1.output_round_pipeline_aclr = "ACLR0",
altera_mult_add1.output_round_pipeline_register = "CLOCK0",
altera_mult_add1.output_round_register = "CLOCK0",
altera_mult_add1.output_round_type = "NEAREST_INTEGER",
altera_mult_add1.output_rounding = "NO",
altera_mult_add1.output_saturate_aclr = "ACLR0",
altera_mult_add1.output_saturate_pipeline_aclr = "ACLR0",
altera_mult_add1.output_saturate_pipeline_register = "CLOCK0",
altera_mult_add1.output_saturate_register = "CLOCK0",
altera_mult_add1.output_saturate_type = "ASYMMETRIC",
altera_mult_add1.output_saturation = "NO",
altera_mult_add1.port_addnsub1 = "PORT_UNUSED",
altera_mult_add1.port_addnsub3 = "PORT_UNUSED",
altera_mult_add1.port_chainout_sat_is_overflow = "PORT_UNUSED",
altera_mult_add1.port_output_is_overflow = "PORT_UNUSED",
altera_mult_add1.port_signa = "PORT_UNUSED",
altera_mult_add1.port_signb = "PORT_UNUSED",
altera_mult_add1.preadder_direction_0 = "ADD",
altera_mult_add1.preadder_direction_1 = "ADD",
altera_mult_add1.preadder_direction_2 = "ADD",
altera_mult_add1.preadder_direction_3 = "ADD",
altera_mult_add1.preadder_mode = "SIMPLE",
altera_mult_add1.representation_a = "UNSIGNED",
altera_mult_add1.representation_b = "UNSIGNED",
altera_mult_add1.rotate_aclr = "ACLR0",
altera_mult_add1.rotate_output_aclr = "ACLR0",
altera_mult_add1.rotate_output_register = "CLOCK0",
altera_mult_add1.rotate_pipeline_aclr = "ACLR0",
altera_mult_add1.rotate_pipeline_register = "CLOCK0",
altera_mult_add1.rotate_register = "CLOCK0",
altera_mult_add1.scanouta_aclr = "ACLR0",
altera_mult_add1.scanouta_register = "UNREGISTERED",
altera_mult_add1.selected_device_family = "Stratix V",
altera_mult_add1.shift_mode = "NO",
altera_mult_add1.shift_right_aclr = "ACLR0",
altera_mult_add1.shift_right_output_aclr = "ACLR0",
altera_mult_add1.shift_right_output_register = "CLOCK0",
altera_mult_add1.shift_right_pipeline_aclr = "ACLR0",
altera_mult_add1.shift_right_pipeline_register = "CLOCK0",
altera_mult_add1.shift_right_register = "CLOCK0",
altera_mult_add1.signed_aclr_a = "ACLR0",
altera_mult_add1.signed_aclr_b = "ACLR0",
altera_mult_add1.signed_pipeline_aclr_a = "ACLR0",
altera_mult_add1.signed_pipeline_aclr_b = "ACLR0",
altera_mult_add1.signed_pipeline_register_a = "UNREGISTERED",
altera_mult_add1.signed_pipeline_register_b = "UNREGISTERED",
altera_mult_add1.signed_register_a = "CLOCK0",
altera_mult_add1.signed_register_b = "CLOCK0",
altera_mult_add1.systolic_aclr1 = "ACLR0",
altera_mult_add1.systolic_aclr3 = "ACLR0",
altera_mult_add1.systolic_delay1 = "UNREGISTERED",
altera_mult_add1.systolic_delay3 = "UNREGISTERED",
altera_mult_add1.width_a = 27,
altera_mult_add1.width_b = 27,
altera_mult_add1.width_c = 22,
altera_mult_add1.width_chainin = 1,
altera_mult_add1.width_coef = 18,
altera_mult_add1.width_msb = 17,
altera_mult_add1.width_result = 54,
altera_mult_add1.width_saturate_sign = 1,
altera_mult_add1.zero_chainout_output_aclr = "ACLR0",
altera_mult_add1.zero_chainout_output_register = "CLOCK0",
altera_mult_add1.zero_loopback_aclr = "ACLR0",
altera_mult_add1.zero_loopback_output_aclr = "ACLR0",
altera_mult_add1.zero_loopback_output_register = "CLOCK0",
altera_mult_add1.zero_loopback_pipeline_aclr = "ACLR0",
altera_mult_add1.zero_loopback_pipeline_register = "CLOCK0",
altera_mult_add1.zero_loopback_register = "CLOCK0",
altera_mult_add1.lpm_type = "altera_mult_add";
assign
ena1 = 1'b1,
ena2 = 1'b1,
ena3 = 1'b1,
result = wire_altera_mult_add1_result;
endmodule //sv_mult27_mult_add_cfq3
//VALID FILE
// synopsys translate_off
`timescale 1 ps / 1 ps
// synopsys translate_on
module sv_mult27 (
clock0,
ena0,
dataa_0,
datab_0,
result);
input clock0;
input ena0;
input [26:0] dataa_0;
input [26:0] datab_0;
output [53:0] result;
`ifndef ALTERA_RESERVED_QIS
// synopsys translate_off
`endif
tri1 clock0;
tri0 [26:0] dataa_0;
tri0 [26:0] datab_0;
`ifndef ALTERA_RESERVED_QIS
// synopsys translate_on
`endif
wire [53:0] sub_wire0;
wire [53:0] result = sub_wire0[53:0];
sv_mult27_mult_add_cfq3 sv_mult27_mult_add_cfq3_component (
.clock0 (clock0),
.ena0(ena0),
.dataa (dataa_0),
.datab (datab_0),
.result (sub_wire0));
endmodule
// ============================================================
// CNX file retrieval info
// ============================================================
// Retrieval info: PRIVATE: ACCUM_SLOAD_ACLR_SRC_MULT0 NUMERIC "3"
// Retrieval info: PRIVATE: ACCUM_SLOAD_CLK_SRC_MULT0 NUMERIC "0"
// Retrieval info: PRIVATE: ADDNSUB1_ACLR_SRC NUMERIC "2"
// Retrieval info: PRIVATE: ADDNSUB1_CLK_SRC NUMERIC "0"
// Retrieval info: PRIVATE: ADDNSUB1_PIPE_ACLR_SRC NUMERIC "3"
// Retrieval info: PRIVATE: ADDNSUB1_PIPE_CLK_SRC NUMERIC "0"
// Retrieval info: PRIVATE: ADDNSUB1_PIPE_REG STRING "0"
// Retrieval info: PRIVATE: ADDNSUB1_REG STRING "1"
// Retrieval info: PRIVATE: ADDNSUB3_ACLR_SRC NUMERIC "3"
// Retrieval info: PRIVATE: ADDNSUB3_CLK_SRC NUMERIC "0"
// Retrieval info: PRIVATE: ADDNSUB3_PIPE_ACLR_SRC NUMERIC "3"
// Retrieval info: PRIVATE: ADDNSUB3_PIPE_CLK_SRC NUMERIC "0"
// Retrieval info: PRIVATE: ADDNSUB3_PIPE_REG STRING "0"
// Retrieval info: PRIVATE: ADDNSUB3_REG STRING "1"
// Retrieval info: PRIVATE: ADD_ENABLE NUMERIC "0"
// Retrieval info: PRIVATE: ALL_REG_ACLR NUMERIC "0"
// Retrieval info: PRIVATE: A_ACLR_SRC_MULT0 NUMERIC "2"
// Retrieval info: PRIVATE: A_CLK_SRC_MULT0 NUMERIC "0"
// Retrieval info: PRIVATE: B_ACLR_SRC_MULT0 NUMERIC "3"
// Retrieval info: PRIVATE: B_CLK_SRC_MULT0 NUMERIC "0"
// Retrieval info: PRIVATE: C_ACLR_SRC_MULT0 NUMERIC "3"
// Retrieval info: PRIVATE: C_CLK_SRC_MULT0 NUMERIC "0"
// Retrieval info: PRIVATE: ENABLE_PRELOAD_CONSTANT NUMERIC "0"
// Retrieval info: PRIVATE: HAS_MAC STRING "0"
// Retrieval info: PRIVATE: HAS_SAT_ROUND STRING "0"
// Retrieval info: PRIVATE: IMPL_STYLE_DEDICATED NUMERIC "0"
// Retrieval info: PRIVATE: IMPL_STYLE_DEFAULT NUMERIC "1"
// Retrieval info: PRIVATE: IMPL_STYLE_LCELL NUMERIC "0"
// Retrieval info: PRIVATE: INTENDED_DEVICE_FAMILY STRING "Stratix V"
// Retrieval info: PRIVATE: MULT_COEFSEL STRING "0"
// Retrieval info: PRIVATE: MULT_REGA0 NUMERIC "1"
// Retrieval info: PRIVATE: MULT_REGB0 NUMERIC "1"
// Retrieval info: PRIVATE: MULT_REGC NUMERIC "0"
// Retrieval info: PRIVATE: MULT_REGOUT0 NUMERIC "0"
// Retrieval info: PRIVATE: MULT_REG_ACCUM_SLOAD NUMERIC "0"
// Retrieval info: PRIVATE: MULT_REG_SYSTOLIC_DELAY NUMERIC "0"
// Retrieval info: PRIVATE: NUM_MULT STRING "1"
// Retrieval info: PRIVATE: OP1 STRING "Add"
// Retrieval info: PRIVATE: OP3 STRING "Add"
// Retrieval info: PRIVATE: OUTPUT_EXTRA_LAT NUMERIC "0"
// Retrieval info: PRIVATE: OUTPUT_REG_ACLR_SRC NUMERIC "2"
// Retrieval info: PRIVATE: OUTPUT_REG_CLK_SRC NUMERIC "0"
// Retrieval info: PRIVATE: Q_ACLR_SRC_MULT0 NUMERIC "3"
// Retrieval info: PRIVATE: Q_CLK_SRC_MULT0 NUMERIC "0"
// Retrieval info: PRIVATE: REG_OUT NUMERIC "1"
// Retrieval info: PRIVATE: RNFORMAT STRING "54"
// Retrieval info: PRIVATE: RQFORMAT STRING "Q1.15"
// Retrieval info: PRIVATE: RTS_WIDTH STRING "54"
// Retrieval info: PRIVATE: SAME_CONFIG NUMERIC "1"
// Retrieval info: PRIVATE: SAME_CONTROL_SRC_A0 NUMERIC "1"
// Retrieval info: PRIVATE: SAME_CONTROL_SRC_B0 NUMERIC "1"
// Retrieval info: PRIVATE: SCANOUTA NUMERIC "0"
// Retrieval info: PRIVATE: SCANOUTB NUMERIC "0"
// Retrieval info: PRIVATE: SHIFTOUTA_ACLR_SRC NUMERIC "3"
// Retrieval info: PRIVATE: SHIFTOUTA_CLK_SRC NUMERIC "0"
// Retrieval info: PRIVATE: SHIFTOUTA_REG STRING "0"
// Retrieval info: PRIVATE: SIGNA STRING "UNSIGNED"
// Retrieval info: PRIVATE: SIGNA_ACLR_SRC NUMERIC "3"
// Retrieval info: PRIVATE: SIGNA_CLK_SRC NUMERIC "0"
// Retrieval info: PRIVATE: SIGNA_PIPE_ACLR_SRC NUMERIC "3"
// Retrieval info: PRIVATE: SIGNA_PIPE_CLK_SRC NUMERIC "0"
// Retrieval info: PRIVATE: SIGNA_PIPE_REG STRING "0"
// Retrieval info: PRIVATE: SIGNA_REG STRING "1"
// Retrieval info: PRIVATE: SIGNB STRING "UNSIGNED"
// Retrieval info: PRIVATE: SIGNB_ACLR_SRC NUMERIC "3"
// Retrieval info: PRIVATE: SIGNB_CLK_SRC NUMERIC "0"
// Retrieval info: PRIVATE: SIGNB_PIPE_ACLR_SRC NUMERIC "3"
// Retrieval info: PRIVATE: SIGNB_PIPE_CLK_SRC NUMERIC "0"
// Retrieval info: PRIVATE: SIGNB_PIPE_REG STRING "0"
// Retrieval info: PRIVATE: SIGNB_REG STRING "1"
// Retrieval info: PRIVATE: SRCA0 STRING "Multiplier input"
// Retrieval info: PRIVATE: SRCB0 STRING "Multiplier input"
// Retrieval info: PRIVATE: SYNTH_WRAPPER_GEN_POSTFIX STRING "0"
// Retrieval info: PRIVATE: SYSTOLIC_ACLR_SRC_MULT0 NUMERIC "3"
// Retrieval info: PRIVATE: SYSTOLIC_CLK_SRC_MULT0 NUMERIC "0"
// Retrieval info: PRIVATE: WIDTHA STRING "27"
// Retrieval info: PRIVATE: WIDTHB STRING "27"
// Retrieval info: LIBRARY: altera_mf altera_mf.altera_mf_components.all
// Retrieval info: CONSTANT: ACCUM_SLOAD_REGISTER STRING "UNREGISTERED"
// Retrieval info: CONSTANT: ADDNSUB_MULTIPLIER_ACLR1 STRING "UNUSED"
// Retrieval info: CONSTANT: ADDNSUB_MULTIPLIER_PIPELINE_REGISTER1 STRING "UNREGISTERED"
// Retrieval info: CONSTANT: ADDNSUB_MULTIPLIER_REGISTER1 STRING "CLOCK0"
// Retrieval info: CONSTANT: COEF0_0 NUMERIC "0"
// Retrieval info: CONSTANT: COEF0_1 NUMERIC "0"
// Retrieval info: CONSTANT: COEF0_2 NUMERIC "0"
// Retrieval info: CONSTANT: COEF0_3 NUMERIC "0"
// Retrieval info: CONSTANT: COEF0_4 NUMERIC "0"
// Retrieval info: CONSTANT: COEF0_5 NUMERIC "0"
// Retrieval info: CONSTANT: COEF0_6 NUMERIC "0"
// Retrieval info: CONSTANT: COEF0_7 NUMERIC "0"
// Retrieval info: CONSTANT: COEF1_0 NUMERIC "0"
// Retrieval info: CONSTANT: COEF1_1 NUMERIC "0"
// Retrieval info: CONSTANT: COEF1_2 NUMERIC "0"
// Retrieval info: CONSTANT: COEF1_3 NUMERIC "0"
// Retrieval info: CONSTANT: COEF1_4 NUMERIC "0"
// Retrieval info: CONSTANT: COEF1_5 NUMERIC "0"
// Retrieval info: CONSTANT: COEF1_6 NUMERIC "0"
// Retrieval info: CONSTANT: COEF1_7 NUMERIC "0"
// Retrieval info: CONSTANT: COEF2_0 NUMERIC "0"
// Retrieval info: CONSTANT: COEF2_1 NUMERIC "0"
// Retrieval info: CONSTANT: COEF2_2 NUMERIC "0"
// Retrieval info: CONSTANT: COEF2_3 NUMERIC "0"
// Retrieval info: CONSTANT: COEF2_4 NUMERIC "0"
// Retrieval info: CONSTANT: COEF2_5 NUMERIC "0"
// Retrieval info: CONSTANT: COEF2_6 NUMERIC "0"
// Retrieval info: CONSTANT: COEF2_7 NUMERIC "0"
// Retrieval info: CONSTANT: COEF3_0 NUMERIC "0"
// Retrieval info: CONSTANT: COEF3_1 NUMERIC "0"
// Retrieval info: CONSTANT: COEF3_2 NUMERIC "0"
// Retrieval info: CONSTANT: COEF3_3 NUMERIC "0"
// Retrieval info: CONSTANT: COEF3_4 NUMERIC "0"
// Retrieval info: CONSTANT: COEF3_5 NUMERIC "0"
// Retrieval info: CONSTANT: COEF3_6 NUMERIC "0"
// Retrieval info: CONSTANT: COEF3_7 NUMERIC "0"
// Retrieval info: CONSTANT: COEFSEL0_REGISTER STRING "UNREGISTERED"
// Retrieval info: CONSTANT: DEDICATED_MULTIPLIER_CIRCUITRY STRING "AUTO"
// Retrieval info: CONSTANT: INPUT_ACLR_A0 STRING "UNUSED"
// Retrieval info: CONSTANT: INPUT_ACLR_B0 STRING "UNUSED"
// Retrieval info: CONSTANT: INPUT_REGISTER_A0 STRING "CLOCK0"
// Retrieval info: CONSTANT: INPUT_REGISTER_B0 STRING "CLOCK0"
// Retrieval info: CONSTANT: INPUT_REGISTER_C0 STRING "UNREGISTERED"
// Retrieval info: CONSTANT: INPUT_SOURCE_A0 STRING "DATAA"
// Retrieval info: CONSTANT: INPUT_SOURCE_B0 STRING "DATAB"
// Retrieval info: CONSTANT: INTENDED_DEVICE_FAMILY STRING "Stratix V"
// Retrieval info: CONSTANT: LOADCONST_VALUE NUMERIC "64"
// Retrieval info: CONSTANT: LPM_TYPE STRING "altmult_add"
// Retrieval info: CONSTANT: MULTIPLIER1_DIRECTION STRING "ADD"
// Retrieval info: CONSTANT: MULTIPLIER_ACLR0 STRING "UNUSED"
// Retrieval info: CONSTANT: MULTIPLIER_REGISTER0 STRING "UNREGISTERED"
// Retrieval info: CONSTANT: NUMBER_OF_MULTIPLIERS NUMERIC "1"
// Retrieval info: CONSTANT: OUTPUT_ACLR STRING "UNUSED"
// Retrieval info: CONSTANT: OUTPUT_REGISTER STRING "CLOCK0"
// Retrieval info: CONSTANT: PORT_ADDNSUB1 STRING "PORT_UNUSED"
// Retrieval info: CONSTANT: PORT_SIGNA STRING "PORT_UNUSED"
// Retrieval info: CONSTANT: PORT_SIGNB STRING "PORT_UNUSED"
// Retrieval info: CONSTANT: PREADDER_DIRECTION_0 STRING "ADD"
// Retrieval info: CONSTANT: PREADDER_DIRECTION_1 STRING "ADD"
// Retrieval info: CONSTANT: PREADDER_DIRECTION_2 STRING "ADD"
// Retrieval info: CONSTANT: PREADDER_DIRECTION_3 STRING "ADD"
// Retrieval info: CONSTANT: PREADDER_MODE STRING "SIMPLE"
// Retrieval info: CONSTANT: REPRESENTATION_A STRING "UNSIGNED"
// Retrieval info: CONSTANT: REPRESENTATION_B STRING "UNSIGNED"
// Retrieval info: CONSTANT: SIGNED_ACLR_A STRING "UNUSED"
// Retrieval info: CONSTANT: SIGNED_ACLR_B STRING "UNUSED"
// Retrieval info: CONSTANT: SIGNED_PIPELINE_REGISTER_A STRING "UNREGISTERED"
// Retrieval info: CONSTANT: SIGNED_PIPELINE_REGISTER_B STRING "UNREGISTERED"
// Retrieval info: CONSTANT: SIGNED_REGISTER_A STRING "CLOCK0"
// Retrieval info: CONSTANT: SIGNED_REGISTER_B STRING "CLOCK0"
// Retrieval info: CONSTANT: SYSTOLIC_DELAY1 STRING "UNREGISTERED"
// Retrieval info: CONSTANT: SYSTOLIC_DELAY3 STRING "UNREGISTERED"
// Retrieval info: CONSTANT: WIDTH_A NUMERIC "27"
// Retrieval info: CONSTANT: WIDTH_B NUMERIC "27"
// Retrieval info: CONSTANT: WIDTH_RESULT NUMERIC "54"
// Retrieval info: USED_PORT: clock0 0 0 0 0 INPUT VCC "clock0"
// Retrieval info: USED_PORT: dataa_0 0 0 27 0 INPUT GND "dataa_0[26..0]"
// Retrieval info: USED_PORT: datab_0 0 0 27 0 INPUT GND "datab_0[26..0]"
// Retrieval info: USED_PORT: result 0 0 54 0 OUTPUT GND "result[53..0]"
// Retrieval info: CONNECT: @clock0 0 0 0 0 clock0 0 0 0 0
// Retrieval info: CONNECT: @dataa 0 0 27 0 dataa_0 0 0 27 0
// Retrieval info: CONNECT: @datab 0 0 27 0 datab_0 0 0 27 0
// Retrieval info: CONNECT: result 0 0 54 0 @result 0 0 54 0
// Retrieval info: GEN_FILE: TYPE_NORMAL sv_mult27.v TRUE
// Retrieval info: GEN_FILE: TYPE_NORMAL sv_mult27.inc FALSE
// Retrieval info: GEN_FILE: TYPE_NORMAL sv_mult27.cmp FALSE
// Retrieval info: GEN_FILE: TYPE_NORMAL sv_mult27.bsf FALSE
// Retrieval info: GEN_FILE: TYPE_NORMAL sv_mult27_inst.v FALSE
// Retrieval info: GEN_FILE: TYPE_NORMAL sv_mult27_bb.v TRUE
// Retrieval info: LIB_FILE: altera_lnsim
|
//*****************************************************************************
// (c) Copyright 2008 - 2013 Xilinx, Inc. All rights reserved.
//
// This file contains confidential and proprietary information
// of Xilinx, Inc. and is protected under U.S. and
// international copyright and other intellectual property
// laws.
//
// DISCLAIMER
// This disclaimer is not a license and does not grant any
// rights to the materials distributed herewith. Except as
// otherwise provided in a valid license issued to you by
// Xilinx, and to the maximum extent permitted by applicable
// law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND
// WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES
// AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
// BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-
// INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and
// (2) Xilinx shall not be liable (whether in contract or tort,
// including negligence, or under any other theory of
// liability) for any loss or damage of any kind or nature
// related to, arising under or in connection with these
// materials, including for any direct, or any indirect,
// special, incidental, or consequential loss or damage
// (including loss of data, profits, goodwill, or any type of
// loss or damage suffered as a result of any action brought
// by a third party) even if such damage or loss was
// reasonably foreseeable or Xilinx had been advised of the
// possibility of the same.
//
// CRITICAL APPLICATIONS
// Xilinx products are not designed or intended to be fail-
// safe, or for use in any application requiring fail-safe
// performance, such as life-support or safety devices or
// systems, Class III medical devices, nuclear facilities,
// applications related to the deployment of airbags, or any
// other applications that could lead to death, personal
// injury, or severe property or environmental damage
// (individually and collectively, "Critical
// Applications"). Customer assumes the sole risk and
// liability of any use of Xilinx products in Critical
// Applications, subject only to applicable laws and
// regulations governing limitations on product liability.
//
// THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS
// PART OF THIS FILE AT ALL TIMES.
//
//*****************************************************************************
// ____ ____
// / /\/ /
// /___/ \ / Vendor : Xilinx
// \ \ \/ Version : %version
// \ \ Application : MIG
// / / Filename : ddr_mc_phy_wrapper.v
// /___/ /\ Date Last Modified : $date$
// \ \ / \ Date Created : Oct 10 2010
// \___\/\___\
//
//Device : 7 Series
//Design Name : DDR3 SDRAM
//Purpose : Wrapper file that encompasses the MC_PHY module
// instantiation and handles the vector remapping between
// the MC_PHY ports and the user's DDR3 ports. Vector
// remapping affects DDR3 control, address, and DQ/DQS/DM.
//Reference :
//Revision History :
//*****************************************************************************
`timescale 1 ps / 1 ps
module mig_7series_v1_9_ddr_mc_phy_wrapper #
(
parameter TCQ = 100, // Register delay (simulation only)
parameter tCK = 2500, // ps
parameter BANK_TYPE = "HP_IO", // # = "HP_IO", "HPL_IO", "HR_IO", "HRL_IO"
parameter DATA_IO_PRIM_TYPE = "DEFAULT", // # = "HP_LP", "HR_LP", "DEFAULT"
parameter DATA_IO_IDLE_PWRDWN = "ON", // "ON" or "OFF"
parameter IODELAY_GRP = "IODELAY_MIG",
parameter nCK_PER_CLK = 4, // Memory:Logic clock ratio
parameter nCS_PER_RANK = 1, // # of unique CS outputs per rank
parameter BANK_WIDTH = 3, // # of bank address
parameter CKE_WIDTH = 1, // # of clock enable outputs
parameter CS_WIDTH = 1, // # of chip select
parameter CK_WIDTH = 1, // # of CK
parameter CWL = 5, // CAS Write latency
parameter DDR2_DQSN_ENABLE = "YES", // Enable differential DQS for DDR2
parameter DM_WIDTH = 8, // # of data mask
parameter DQ_WIDTH = 16, // # of data bits
parameter DQS_CNT_WIDTH = 3, // ceil(log2(DQS_WIDTH))
parameter DQS_WIDTH = 8, // # of strobe pairs
parameter DRAM_TYPE = "DDR3", // DRAM type (DDR2, DDR3)
parameter RANKS = 4, // # of ranks
parameter ODT_WIDTH = 1, // # of ODT outputs
parameter REG_CTRL = "OFF", // "ON" for registered DIMM
parameter ROW_WIDTH = 16, // # of row/column address
parameter USE_CS_PORT = 1, // Support chip select output
parameter USE_DM_PORT = 1, // Support data mask output
parameter USE_ODT_PORT = 1, // Support ODT output
parameter IBUF_LPWR_MODE = "OFF", // input buffer low power option
parameter LP_DDR_CK_WIDTH = 2,
// Hard PHY parameters
parameter PHYCTL_CMD_FIFO = "FALSE",
parameter DATA_CTL_B0 = 4'hc,
parameter DATA_CTL_B1 = 4'hf,
parameter DATA_CTL_B2 = 4'hf,
parameter DATA_CTL_B3 = 4'hf,
parameter DATA_CTL_B4 = 4'hf,
parameter BYTE_LANES_B0 = 4'b1111,
parameter BYTE_LANES_B1 = 4'b0000,
parameter BYTE_LANES_B2 = 4'b0000,
parameter BYTE_LANES_B3 = 4'b0000,
parameter BYTE_LANES_B4 = 4'b0000,
parameter PHY_0_BITLANES = 48'h0000_0000_0000,
parameter PHY_1_BITLANES = 48'h0000_0000_0000,
parameter PHY_2_BITLANES = 48'h0000_0000_0000,
// Parameters calculated outside of this block
parameter HIGHEST_BANK = 3, // Highest I/O bank index
parameter HIGHEST_LANE = 12, // Highest byte lane index
// ** Pin mapping parameters
// Parameters for mapping between hard PHY and physical DDR3 signals
// There are 2 classes of parameters:
// - DQS_BYTE_MAP, CK_BYTE_MAP, CKE_ODT_BYTE_MAP: These consist of
// 8-bit elements. Each element indicates the bank and byte lane
// location of that particular signal. The bit lane in this case
// doesn't need to be specified, either because there's only one
// pin pair in each byte lane that the DQS or CK pair can be
// located at, or in the case of CKE_ODT_BYTE_MAP, only the byte
// lane needs to be specified in order to determine which byte
// lane generates the RCLK (Note that CKE, and ODT must be located
// in the same bank, thus only one element in CKE_ODT_BYTE_MAP)
// [7:4] = bank # (0-4)
// [3:0] = byte lane # (0-3)
// - All other MAP parameters: These consist of 12-bit elements. Each
// element indicates the bank, byte lane, and bit lane location of
// that particular signal:
// [11:8] = bank # (0-4)
// [7:4] = byte lane # (0-3)
// [3:0] = bit lane # (0-11)
// Note that not all elements in all parameters will be used - it
// depends on the actual widths of the DDR3 buses. The parameters are
// structured to support a maximum of:
// - DQS groups: 18
// - data mask bits: 18
// In addition, the default parameter size of some of the parameters will
// support a certain number of bits, however, this can be expanded at
// compile time by expanding the width of the vector passed into this
// parameter
// - chip selects: 10
// - bank bits: 3
// - address bits: 16
parameter CK_BYTE_MAP
= 144'h00_00_00_00_00_00_00_00_00_00_00_00_00_00_00_00_00_00,
parameter ADDR_MAP
= 192'h000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000,
parameter BANK_MAP = 36'h000_000_000,
parameter CAS_MAP = 12'h000,
parameter CKE_ODT_BYTE_MAP = 8'h00,
parameter CKE_MAP = 96'h000_000_000_000_000_000_000_000,
parameter ODT_MAP = 96'h000_000_000_000_000_000_000_000,
parameter CKE_ODT_AUX = "FALSE",
parameter CS_MAP = 120'h000_000_000_000_000_000_000_000_000_000,
parameter PARITY_MAP = 12'h000,
parameter RAS_MAP = 12'h000,
parameter WE_MAP = 12'h000,
parameter DQS_BYTE_MAP
= 144'h00_00_00_00_00_00_00_00_00_00_00_00_00_00_00_00_00_00,
// DATAx_MAP parameter is used for byte lane X in the design
parameter DATA0_MAP = 96'h000_000_000_000_000_000_000_000,
parameter DATA1_MAP = 96'h000_000_000_000_000_000_000_000,
parameter DATA2_MAP = 96'h000_000_000_000_000_000_000_000,
parameter DATA3_MAP = 96'h000_000_000_000_000_000_000_000,
parameter DATA4_MAP = 96'h000_000_000_000_000_000_000_000,
parameter DATA5_MAP = 96'h000_000_000_000_000_000_000_000,
parameter DATA6_MAP = 96'h000_000_000_000_000_000_000_000,
parameter DATA7_MAP = 96'h000_000_000_000_000_000_000_000,
parameter DATA8_MAP = 96'h000_000_000_000_000_000_000_000,
parameter DATA9_MAP = 96'h000_000_000_000_000_000_000_000,
parameter DATA10_MAP = 96'h000_000_000_000_000_000_000_000,
parameter DATA11_MAP = 96'h000_000_000_000_000_000_000_000,
parameter DATA12_MAP = 96'h000_000_000_000_000_000_000_000,
parameter DATA13_MAP = 96'h000_000_000_000_000_000_000_000,
parameter DATA14_MAP = 96'h000_000_000_000_000_000_000_000,
parameter DATA15_MAP = 96'h000_000_000_000_000_000_000_000,
parameter DATA16_MAP = 96'h000_000_000_000_000_000_000_000,
parameter DATA17_MAP = 96'h000_000_000_000_000_000_000_000,
// MASK0_MAP used for bytes [8:0], MASK1_MAP for bytes [17:9]
parameter MASK0_MAP = 108'h000_000_000_000_000_000_000_000_000,
parameter MASK1_MAP = 108'h000_000_000_000_000_000_000_000_000,
// Simulation options
parameter SIM_CAL_OPTION = "NONE",
// The PHY_CONTROL primitive in the bank where PLL exists is declared
// as the Master PHY_CONTROL.
parameter MASTER_PHY_CTL = 1
)
(
input rst,
input clk,
input freq_refclk,
input mem_refclk,
input pll_lock,
input sync_pulse,
input idelayctrl_refclk,
input phy_cmd_wr_en,
input phy_data_wr_en,
input [31:0] phy_ctl_wd,
input phy_ctl_wr,
input phy_if_empty_def,
input phy_if_reset,
input [5:0] data_offset_1,
input [5:0] data_offset_2,
input [3:0] aux_in_1,
input [3:0] aux_in_2,
output [4:0] idelaye2_init_val,
output [5:0] oclkdelay_init_val,
output if_empty,
output phy_ctl_full,
output phy_cmd_full,
output phy_data_full,
output phy_pre_data_a_full,
output [(CK_WIDTH * LP_DDR_CK_WIDTH)-1:0] ddr_clk,
output phy_mc_go,
input phy_write_calib,
input phy_read_calib,
input calib_in_common,
input [5:0] calib_sel,
input [HIGHEST_BANK-1:0] calib_zero_inputs,
input [HIGHEST_BANK-1:0] calib_zero_ctrl,
input [2:0] po_fine_enable,
input [2:0] po_coarse_enable,
input [2:0] po_fine_inc,
input [2:0] po_coarse_inc,
input po_counter_load_en,
input po_counter_read_en,
input [2:0] po_sel_fine_oclk_delay,
input [8:0] po_counter_load_val,
output [8:0] po_counter_read_val,
output [5:0] pi_counter_read_val,
input [HIGHEST_BANK-1:0] pi_rst_dqs_find,
input pi_fine_enable,
input pi_fine_inc,
input pi_counter_load_en,
input [5:0] pi_counter_load_val,
input idelay_ce,
input idelay_inc,
input idelay_ld,
input idle,
output pi_phase_locked,
output pi_phase_locked_all,
output pi_dqs_found,
output pi_dqs_found_all,
output pi_dqs_out_of_range,
// From/to calibration logic/soft PHY
input phy_init_data_sel,
input [nCK_PER_CLK*ROW_WIDTH-1:0] mux_address,
input [nCK_PER_CLK*BANK_WIDTH-1:0] mux_bank,
input [nCK_PER_CLK-1:0] mux_cas_n,
input [CS_WIDTH*nCS_PER_RANK*nCK_PER_CLK-1:0] mux_cs_n,
input [nCK_PER_CLK-1:0] mux_ras_n,
input [1:0] mux_odt,
input [nCK_PER_CLK-1:0] mux_cke,
input [nCK_PER_CLK-1:0] mux_we_n,
input [nCK_PER_CLK-1:0] parity_in,
input [2*nCK_PER_CLK*DQ_WIDTH-1:0] mux_wrdata,
input [2*nCK_PER_CLK*(DQ_WIDTH/8)-1:0] mux_wrdata_mask,
input mux_reset_n,
output [2*nCK_PER_CLK*DQ_WIDTH-1:0] rd_data,
// Memory I/F
output [ROW_WIDTH-1:0] ddr_addr,
output [BANK_WIDTH-1:0] ddr_ba,
output ddr_cas_n,
output [CKE_WIDTH-1:0] ddr_cke,
output [CS_WIDTH*nCS_PER_RANK-1:0] ddr_cs_n,
output [DM_WIDTH-1:0] ddr_dm,
output [ODT_WIDTH-1:0] ddr_odt,
output ddr_parity,
output ddr_ras_n,
output ddr_we_n,
output ddr_reset_n,
inout [DQ_WIDTH-1:0] ddr_dq,
inout [DQS_WIDTH-1:0] ddr_dqs,
inout [DQS_WIDTH-1:0] ddr_dqs_n
,input dbg_pi_counter_read_en
,output ref_dll_lock
,input rst_phaser_ref
,output [11:0] dbg_pi_phase_locked_phy4lanes
,output [11:0] dbg_pi_dqs_found_lanes_phy4lanes
);
function [71:0] generate_bytelanes_ddr_ck;
input [143:0] ck_byte_map;
integer v ;
begin
generate_bytelanes_ddr_ck = 'b0 ;
for (v = 0; v < CK_WIDTH; v = v + 1) begin
if ((CK_BYTE_MAP[((v*8)+4)+:4]) == 2)
generate_bytelanes_ddr_ck[48+(4*v)+1*(CK_BYTE_MAP[(v*8)+:4])] = 1'b1;
else if ((CK_BYTE_MAP[((v*8)+4)+:4]) == 1)
generate_bytelanes_ddr_ck[24+(4*v)+1*(CK_BYTE_MAP[(v*8)+:4])] = 1'b1;
else
generate_bytelanes_ddr_ck[4*v+1*(CK_BYTE_MAP[(v*8)+:4])] = 1'b1;
end
end
endfunction
function [(2*CK_WIDTH*8)-1:0] generate_ddr_ck_map;
input [143:0] ck_byte_map;
integer g;
begin
generate_ddr_ck_map = 'b0 ;
for(g = 0 ; g < CK_WIDTH ; g= g + 1) begin
generate_ddr_ck_map[(g*2*8)+:8] = (ck_byte_map[(g*8)+:4] == 4'd0) ? "A" :
(ck_byte_map[(g*8)+:4] == 4'd1) ? "B" :
(ck_byte_map[(g*8)+:4] == 4'd2) ? "C" : "D" ;
generate_ddr_ck_map[(((g*2)+1)*8)+:8] = (ck_byte_map[((g*8)+4)+:4] == 4'd0) ? "0" :
(ck_byte_map[((g*8)+4)+:4] == 4'd1) ? "1" : "2" ; //each STRING charater takes 0 location
end
end
endfunction
// Enable low power mode for input buffer
localparam IBUF_LOW_PWR
= (IBUF_LPWR_MODE == "OFF") ? "FALSE" :
((IBUF_LPWR_MODE == "ON") ? "TRUE" : "ILLEGAL");
// Ratio of data to strobe
localparam DQ_PER_DQS = DQ_WIDTH / DQS_WIDTH;
// number of data phases per internal clock
localparam PHASE_PER_CLK = 2*nCK_PER_CLK;
// used to determine routing to OUT_FIFO for control/address for 2:1
// vs. 4:1 memory:internal clock ratio modes
localparam PHASE_DIV = 4 / nCK_PER_CLK;
localparam CLK_PERIOD = tCK * nCK_PER_CLK;
// Create an aggregate parameters for data mapping to reduce # of generate
// statements required in remapping code. Need to account for the case
// when the DQ:DQS ratio is not 8:1 - in this case, each DATAx_MAP
// parameter will have fewer than 8 elements used
localparam FULL_DATA_MAP = {DATA17_MAP[12*DQ_PER_DQS-1:0],
DATA16_MAP[12*DQ_PER_DQS-1:0],
DATA15_MAP[12*DQ_PER_DQS-1:0],
DATA14_MAP[12*DQ_PER_DQS-1:0],
DATA13_MAP[12*DQ_PER_DQS-1:0],
DATA12_MAP[12*DQ_PER_DQS-1:0],
DATA11_MAP[12*DQ_PER_DQS-1:0],
DATA10_MAP[12*DQ_PER_DQS-1:0],
DATA9_MAP[12*DQ_PER_DQS-1:0],
DATA8_MAP[12*DQ_PER_DQS-1:0],
DATA7_MAP[12*DQ_PER_DQS-1:0],
DATA6_MAP[12*DQ_PER_DQS-1:0],
DATA5_MAP[12*DQ_PER_DQS-1:0],
DATA4_MAP[12*DQ_PER_DQS-1:0],
DATA3_MAP[12*DQ_PER_DQS-1:0],
DATA2_MAP[12*DQ_PER_DQS-1:0],
DATA1_MAP[12*DQ_PER_DQS-1:0],
DATA0_MAP[12*DQ_PER_DQS-1:0]};
// Same deal, but for data mask mapping
localparam FULL_MASK_MAP = {MASK1_MAP, MASK0_MAP};
localparam TMP_BYTELANES_DDR_CK = generate_bytelanes_ddr_ck(CK_BYTE_MAP) ;
localparam TMP_GENERATE_DDR_CK_MAP = generate_ddr_ck_map(CK_BYTE_MAP) ;
// Temporary parameters to determine which bank is outputting the CK/CK#
// Eventually there will be support for multiple CK/CK# output
//localparam TMP_DDR_CLK_SELECT_BANK = (CK_BYTE_MAP[7:4]);
//// Temporary method to force MC_PHY to generate ODDR associated with
//// CK/CK# output only for a single byte lane in the design. All banks
//// that won't be generating the CK/CK# will have "UNUSED" as their
//// PHY_GENERATE_DDR_CK parameter
//localparam TMP_PHY_0_GENERATE_DDR_CK
// = (TMP_DDR_CLK_SELECT_BANK != 0) ? "UNUSED" :
// ((CK_BYTE_MAP[1:0] == 2'b00) ? "A" :
// ((CK_BYTE_MAP[1:0] == 2'b01) ? "B" :
// ((CK_BYTE_MAP[1:0] == 2'b10) ? "C" : "D")));
//localparam TMP_PHY_1_GENERATE_DDR_CK
// = (TMP_DDR_CLK_SELECT_BANK != 1) ? "UNUSED" :
// ((CK_BYTE_MAP[1:0] == 2'b00) ? "A" :
// ((CK_BYTE_MAP[1:0] == 2'b01) ? "B" :
// ((CK_BYTE_MAP[1:0] == 2'b10) ? "C" : "D")));
//localparam TMP_PHY_2_GENERATE_DDR_CK
// = (TMP_DDR_CLK_SELECT_BANK != 2) ? "UNUSED" :
// ((CK_BYTE_MAP[1:0] == 2'b00) ? "A" :
// ((CK_BYTE_MAP[1:0] == 2'b01) ? "B" :
// ((CK_BYTE_MAP[1:0] == 2'b10) ? "C" : "D")));
// Function to generate MC_PHY parameters PHY_BITLANES_OUTONLYx
// which indicates which bit lanes in data byte lanes are
// output-only bitlanes (e.g. used specifically for data mask outputs)
function [143:0] calc_phy_bitlanes_outonly;
input [215:0] data_mask_in;
integer z;
begin
calc_phy_bitlanes_outonly = 'b0;
// Only enable BITLANES parameters for data masks if, well, if
// the data masks are actually enabled
if (USE_DM_PORT == 1)
for (z = 0; z < DM_WIDTH; z = z + 1)
calc_phy_bitlanes_outonly[48*data_mask_in[(12*z+8)+:3] +
12*data_mask_in[(12*z+4)+:2] +
data_mask_in[12*z+:4]] = 1'b1;
end
endfunction
localparam PHY_BITLANES_OUTONLY = calc_phy_bitlanes_outonly(FULL_MASK_MAP);
localparam PHY_0_BITLANES_OUTONLY = PHY_BITLANES_OUTONLY[47:0];
localparam PHY_1_BITLANES_OUTONLY = PHY_BITLANES_OUTONLY[95:48];
localparam PHY_2_BITLANES_OUTONLY = PHY_BITLANES_OUTONLY[143:96];
// Determine which bank and byte lane generates the RCLK used to clock
// out the auxilliary (ODT, CKE) outputs
localparam CKE_ODT_RCLK_SELECT_BANK_AUX_ON
= (CKE_ODT_BYTE_MAP[7:4] == 4'h0) ? 0 :
((CKE_ODT_BYTE_MAP[7:4] == 4'h1) ? 1 :
((CKE_ODT_BYTE_MAP[7:4] == 4'h2) ? 2 :
((CKE_ODT_BYTE_MAP[7:4] == 4'h3) ? 3 :
((CKE_ODT_BYTE_MAP[7:4] == 4'h4) ? 4 : -1))));
localparam CKE_ODT_RCLK_SELECT_LANE_AUX_ON
= (CKE_ODT_BYTE_MAP[3:0] == 4'h0) ? "A" :
((CKE_ODT_BYTE_MAP[3:0] == 4'h1) ? "B" :
((CKE_ODT_BYTE_MAP[3:0] == 4'h2) ? "C" :
((CKE_ODT_BYTE_MAP[3:0] == 4'h3) ? "D" : "ILLEGAL")));
localparam CKE_ODT_RCLK_SELECT_BANK_AUX_OFF
= (CKE_MAP[11:8] == 4'h0) ? 0 :
((CKE_MAP[11:8] == 4'h1) ? 1 :
((CKE_MAP[11:8] == 4'h2) ? 2 :
((CKE_MAP[11:8] == 4'h3) ? 3 :
((CKE_MAP[11:8] == 4'h4) ? 4 : -1))));
localparam CKE_ODT_RCLK_SELECT_LANE_AUX_OFF
= (CKE_MAP[7:4] == 4'h0) ? "A" :
((CKE_MAP[7:4] == 4'h1) ? "B" :
((CKE_MAP[7:4] == 4'h2) ? "C" :
((CKE_MAP[7:4] == 4'h3) ? "D" : "ILLEGAL")));
localparam CKE_ODT_RCLK_SELECT_BANK = (CKE_ODT_AUX == "TRUE") ? CKE_ODT_RCLK_SELECT_BANK_AUX_ON : CKE_ODT_RCLK_SELECT_BANK_AUX_OFF ;
localparam CKE_ODT_RCLK_SELECT_LANE = (CKE_ODT_AUX == "TRUE") ? CKE_ODT_RCLK_SELECT_LANE_AUX_ON : CKE_ODT_RCLK_SELECT_LANE_AUX_OFF ;
//***************************************************************************
// OCLKDELAYED tap setting calculation:
// Parameters for calculating amount of phase shifting output clock to
// achieve 90 degree offset between DQS and DQ on writes
//***************************************************************************
//90 deg equivalent to 0.25 for MEM_RefClk <= 300 MHz
// and 1.25 for Mem_RefClk > 300 MHz
localparam PO_OCLKDELAY_INV = (((SIM_CAL_OPTION == "NONE") && (tCK > 2500)) || (tCK >= 3333)) ? "FALSE" : "TRUE";
//DIV1: MemRefClk >= 400 MHz, DIV2: 200 <= MemRefClk < 400,
//DIV4: MemRefClk < 200 MHz
localparam PHY_0_A_PI_FREQ_REF_DIV = tCK > 5000 ? "DIV4" :
tCK > 2500 ? "DIV2": "NONE";
localparam FREQ_REF_DIV = (PHY_0_A_PI_FREQ_REF_DIV == "DIV4" ? 4 :
PHY_0_A_PI_FREQ_REF_DIV == "DIV2" ? 2 : 1);
// Intrinsic delay between OCLK and OCLK_DELAYED Phaser Output
localparam real INT_DELAY = 0.4392/FREQ_REF_DIV + 100.0/tCK;
// Whether OCLK_DELAY output comes inverted or not
localparam real HALF_CYCLE_DELAY = 0.5*(PO_OCLKDELAY_INV == "TRUE" ? 1 : 0);
// Phaser-Out Stage3 Tap delay for 90 deg shift.
// Maximum tap delay is FreqRefClk period distributed over 64 taps
// localparam real TAP_DELAY = MC_OCLK_DELAY/64/FREQ_REF_DIV;
localparam real MC_OCLK_DELAY = ((PO_OCLKDELAY_INV == "TRUE" ? 1.25 : 0.25) -
(INT_DELAY + HALF_CYCLE_DELAY))
* 63 * FREQ_REF_DIV;
//localparam integer PHY_0_A_PO_OCLK_DELAY = MC_OCLK_DELAY;
localparam integer PHY_0_A_PO_OCLK_DELAY_HW
= (tCK > 2273) ? 34 :
(tCK > 2000) ? 33 :
(tCK > 1724) ? 32 :
(tCK > 1515) ? 31 :
(tCK > 1315) ? 30 :
(tCK > 1136) ? 29 :
(tCK > 1021) ? 28 : 27;
// Note that simulation requires a different value than in H/W because of the
// difference in the way delays are modeled
localparam integer PHY_0_A_PO_OCLK_DELAY = (SIM_CAL_OPTION == "NONE") ?
((tCK > 2500) ? 8 :
(DRAM_TYPE == "DDR3") ? PHY_0_A_PO_OCLK_DELAY_HW : 30) :
MC_OCLK_DELAY;
// Initial DQ IDELAY value
localparam PHY_0_A_IDELAYE2_IDELAY_VALUE = (SIM_CAL_OPTION != "FAST_CAL") ? 0 :
(tCK < 1000) ? 0 :
(tCK < 1330) ? 0 :
(tCK < 2300) ? 0 :
(tCK < 2500) ? 2 : 0;
//localparam PHY_0_A_IDELAYE2_IDELAY_VALUE = 0;
// Aux_out parameters RD_CMD_OFFSET = CL+2? and WR_CMD_OFFSET = CWL+3?
localparam PHY_0_RD_CMD_OFFSET_0 = 10;
localparam PHY_0_RD_CMD_OFFSET_1 = 10;
localparam PHY_0_RD_CMD_OFFSET_2 = 10;
localparam PHY_0_RD_CMD_OFFSET_3 = 10;
// 4:1 and 2:1 have WR_CMD_OFFSET values for ODT timing
localparam PHY_0_WR_CMD_OFFSET_0 = (nCK_PER_CLK == 4) ? 8 : 4;
localparam PHY_0_WR_CMD_OFFSET_1 = (nCK_PER_CLK == 4) ? 8 : 4;
localparam PHY_0_WR_CMD_OFFSET_2 = (nCK_PER_CLK == 4) ? 8 : 4;
localparam PHY_0_WR_CMD_OFFSET_3 = (nCK_PER_CLK == 4) ? 8 : 4;
// 4:1 and 2:1 have different values
localparam PHY_0_WR_DURATION_0 = 7;
localparam PHY_0_WR_DURATION_1 = 7;
localparam PHY_0_WR_DURATION_2 = 7;
localparam PHY_0_WR_DURATION_3 = 7;
// Aux_out parameters for toggle mode (CKE)
localparam CWL_M = (REG_CTRL == "ON") ? CWL + 1 : CWL;
localparam PHY_0_CMD_OFFSET = (nCK_PER_CLK == 4) ? (CWL_M % 2) ? 8 : 9 :
(CWL < 7) ?
4 + ((CWL_M % 2) ? 0 : 1) :
5 + ((CWL_M % 2) ? 0 : 1);
// temporary parameter to enable/disable PHY PC counters. In both 4:1 and
// 2:1 cases, this should be disabled. For now, enable for 4:1 mode to
// avoid making too many changes at once.
localparam PHY_COUNT_EN = (nCK_PER_CLK == 4) ? "TRUE" : "FALSE";
wire [((HIGHEST_LANE+3)/4)*4-1:0] aux_out;
wire [HIGHEST_LANE-1:0] mem_dqs_in;
wire [HIGHEST_LANE-1:0] mem_dqs_out;
wire [HIGHEST_LANE-1:0] mem_dqs_ts;
wire [HIGHEST_LANE*10-1:0] mem_dq_in;
wire [HIGHEST_LANE*12-1:0] mem_dq_out;
wire [HIGHEST_LANE*12-1:0] mem_dq_ts;
wire [DQ_WIDTH-1:0] in_dq;
wire [DQS_WIDTH-1:0] in_dqs;
wire [ROW_WIDTH-1:0] out_addr;
wire [BANK_WIDTH-1:0] out_ba;
wire out_cas_n;
wire [CS_WIDTH*nCS_PER_RANK-1:0] out_cs_n;
wire [DM_WIDTH-1:0] out_dm;
wire [ODT_WIDTH -1:0] out_odt;
wire [CKE_WIDTH -1 :0] out_cke ;
wire [DQ_WIDTH-1:0] out_dq;
wire [DQS_WIDTH-1:0] out_dqs;
wire out_parity;
wire out_ras_n;
wire out_we_n;
wire [HIGHEST_LANE*80-1:0] phy_din;
wire [HIGHEST_LANE*80-1:0] phy_dout;
wire phy_rd_en;
wire [DM_WIDTH-1:0] ts_dm;
wire [DQ_WIDTH-1:0] ts_dq;
wire [DQS_WIDTH-1:0] ts_dqs;
reg [31:0] phy_ctl_wd_i1;
reg [31:0] phy_ctl_wd_i2;
reg phy_ctl_wr_i1;
reg phy_ctl_wr_i2;
reg [5:0] data_offset_1_i1;
reg [5:0] data_offset_1_i2;
reg [5:0] data_offset_2_i1;
reg [5:0] data_offset_2_i2;
wire [31:0] phy_ctl_wd_temp;
wire phy_ctl_wr_temp;
wire [5:0] data_offset_1_temp;
wire [5:0] data_offset_2_temp;
wire [5:0] data_offset_1_of;
wire [5:0] data_offset_2_of;
wire [31:0] phy_ctl_wd_of;
(* keep = "true", max_fanout = 3 *) wire phy_ctl_wr_of /* synthesis syn_maxfan = 1 */;
wire [3:0] phy_ctl_full_temp;
wire data_io_idle_pwrdwn;
// Always read from input data FIFOs when not empty
assign phy_rd_en = !if_empty;
// IDELAYE2 initial value
assign idelaye2_init_val = PHY_0_A_IDELAYE2_IDELAY_VALUE;
assign oclkdelay_init_val = PHY_0_A_PO_OCLK_DELAY;
// Idle powerdown when there are no pending reads in the MC
assign data_io_idle_pwrdwn = DATA_IO_IDLE_PWRDWN == "ON" ? idle : 1'b0;
//***************************************************************************
// Auxiliary output steering
//***************************************************************************
// For a 4 rank I/F the aux_out[3:0] from the addr/ctl bank will be
// mapped to ddr_odt and the aux_out[7:4] from one of the data banks
// will map to ddr_cke. For I/Fs less than 4 the aux_out[3:0] from the
// addr/ctl bank would bank would map to both ddr_odt and ddr_cke.
generate
if(CKE_ODT_AUX == "TRUE")begin:cke_thru_auxpins
if (CKE_WIDTH == 1) begin : gen_cke
// Explicitly instantiate OBUF to ensure that these are present
// in the netlist. Typically this is not required since NGDBUILD
// at the top-level knows to infer an I/O/IOBUF and therefore a
// top-level LOC constraint can be attached to that pin. This does
// not work when a hierarchical flow is used and the LOC is applied
// at the individual core-level UCF
OBUF u_cke_obuf
(
.I (aux_out[4*CKE_ODT_RCLK_SELECT_BANK]),
.O (ddr_cke)
);
end else begin: gen_2rank_cke
OBUF u_cke0_obuf
(
.I (aux_out[4*CKE_ODT_RCLK_SELECT_BANK]),
.O (ddr_cke[0])
);
OBUF u_cke1_obuf
(
.I (aux_out[4*CKE_ODT_RCLK_SELECT_BANK+2]),
.O (ddr_cke[1])
);
end
end
endgenerate
generate
if(CKE_ODT_AUX == "TRUE")begin:odt_thru_auxpins
if (USE_ODT_PORT == 1) begin : gen_use_odt
// Explicitly instantiate OBUF to ensure that these are present
// in the netlist. Typically this is not required since NGDBUILD
// at the top-level knows to infer an I/O/IOBUF and therefore a
// top-level LOC constraint can be attached to that pin. This does
// not work when a hierarchical flow is used and the LOC is applied
// at the individual core-level UCF
OBUF u_odt_obuf
(
.I (aux_out[4*CKE_ODT_RCLK_SELECT_BANK+1]),
.O (ddr_odt[0])
);
if (ODT_WIDTH == 2 && RANKS == 1) begin: gen_2port_odt
OBUF u_odt1_obuf
(
.I (aux_out[4*CKE_ODT_RCLK_SELECT_BANK+2]),
.O (ddr_odt[1])
);
end else if (ODT_WIDTH == 2 && RANKS == 2) begin: gen_2rank_odt
OBUF u_odt1_obuf
(
.I (aux_out[4*CKE_ODT_RCLK_SELECT_BANK+3]),
.O (ddr_odt[1])
);
end else if (ODT_WIDTH == 3 && RANKS == 1) begin: gen_3port_odt
OBUF u_odt1_obuf
(
.I (aux_out[4*CKE_ODT_RCLK_SELECT_BANK+2]),
.O (ddr_odt[1])
);
OBUF u_odt2_obuf
(
.I (aux_out[4*CKE_ODT_RCLK_SELECT_BANK+3]),
.O (ddr_odt[2])
);
end
end else begin
assign ddr_odt = 'b0;
end
end
endgenerate
//***************************************************************************
// Read data bit steering
//***************************************************************************
// Transpose elements of rd_data_map to form final read data output:
// phy_din elements are grouped according to "physical bit" - e.g.
// for nCK_PER_CLK = 4, there are 8 data phases transfered per physical
// bit per clock cycle:
// = {dq0_fall3, dq0_rise3, dq0_fall2, dq0_rise2,
// dq0_fall1, dq0_rise1, dq0_fall0, dq0_rise0}
// whereas rd_data is are grouped according to "phase" - e.g.
// = {dq7_rise0, dq6_rise0, dq5_rise0, dq4_rise0,
// dq3_rise0, dq2_rise0, dq1_rise0, dq0_rise0}
// therefore rd_data is formed by transposing phy_din - e.g.
// for nCK_PER_CLK = 4, and DQ_WIDTH = 16, and assuming MC_PHY
// bit_lane[0] maps to DQ[0], and bit_lane[1] maps to DQ[1], then
// the assignments for bits of rd_data corresponding to DQ[1:0]
// would be:
// {rd_data[112], rd_data[96], rd_data[80], rd_data[64],
// rd_data[48], rd_data[32], rd_data[16], rd_data[0]} = phy_din[7:0]
// {rd_data[113], rd_data[97], rd_data[81], rd_data[65],
// rd_data[49], rd_data[33], rd_data[17], rd_data[1]} = phy_din[15:8]
generate
genvar i, j;
for (i = 0; i < DQ_WIDTH; i = i + 1) begin: gen_loop_rd_data_1
for (j = 0; j < PHASE_PER_CLK; j = j + 1) begin: gen_loop_rd_data_2
assign rd_data[DQ_WIDTH*j + i]
= phy_din[(320*FULL_DATA_MAP[(12*i+8)+:3]+
80*FULL_DATA_MAP[(12*i+4)+:2] +
8*FULL_DATA_MAP[12*i+:4]) + j];
end
end
endgenerate
//***************************************************************************
// Control/address
//***************************************************************************
assign out_cas_n
= mem_dq_out[48*CAS_MAP[10:8] + 12*CAS_MAP[5:4] + CAS_MAP[3:0]];
generate
// if signal placed on bit lanes [0-9]
if (CAS_MAP[3:0] < 4'hA) begin: gen_cas_lt10
// Determine routing based on clock ratio mode. If running in 4:1
// mode, then all four bits from logic are used. If 2:1 mode, only
// 2-bits are provided by logic, and each bit is repeated 2x to form
// 4-bit input to IN_FIFO, e.g.
// 4:1 mode: phy_dout[] = {in[3], in[2], in[1], in[0]}
// 2:1 mode: phy_dout[] = {in[1], in[1], in[0], in[0]}
assign phy_dout[(320*CAS_MAP[10:8] + 80*CAS_MAP[5:4] +
8*CAS_MAP[3:0])+:4]
= {mux_cas_n[3/PHASE_DIV], mux_cas_n[2/PHASE_DIV],
mux_cas_n[1/PHASE_DIV], mux_cas_n[0]};
end else begin: gen_cas_ge10
// If signal is placed in bit lane [10] or [11], route to upper
// nibble of phy_dout lane [5] or [6] respectively (in this case
// phy_dout lane [5, 6] are multiplexed to take input for two
// different SDR signals - this is how bits[10,11] need to be
// provided to the OUT_FIFO
assign phy_dout[(320*CAS_MAP[10:8] + 80*CAS_MAP[5:4] +
8*(CAS_MAP[3:0]-5) + 4)+:4]
= {mux_cas_n[3/PHASE_DIV], mux_cas_n[2/PHASE_DIV],
mux_cas_n[1/PHASE_DIV], mux_cas_n[0]};
end
endgenerate
assign out_ras_n
= mem_dq_out[48*RAS_MAP[10:8] + 12*RAS_MAP[5:4] + RAS_MAP[3:0]];
generate
if (RAS_MAP[3:0] < 4'hA) begin: gen_ras_lt10
assign phy_dout[(320*RAS_MAP[10:8] + 80*RAS_MAP[5:4] +
8*RAS_MAP[3:0])+:4]
= {mux_ras_n[3/PHASE_DIV], mux_ras_n[2/PHASE_DIV],
mux_ras_n[1/PHASE_DIV], mux_ras_n[0]};
end else begin: gen_ras_ge10
assign phy_dout[(320*RAS_MAP[10:8] + 80*RAS_MAP[5:4] +
8*(RAS_MAP[3:0]-5) + 4)+:4]
= {mux_ras_n[3/PHASE_DIV], mux_ras_n[2/PHASE_DIV],
mux_ras_n[1/PHASE_DIV], mux_ras_n[0]};
end
endgenerate
assign out_we_n
= mem_dq_out[48*WE_MAP[10:8] + 12*WE_MAP[5:4] + WE_MAP[3:0]];
generate
if (WE_MAP[3:0] < 4'hA) begin: gen_we_lt10
assign phy_dout[(320*WE_MAP[10:8] + 80*WE_MAP[5:4] +
8*WE_MAP[3:0])+:4]
= {mux_we_n[3/PHASE_DIV], mux_we_n[2/PHASE_DIV],
mux_we_n[1/PHASE_DIV], mux_we_n[0]};
end else begin: gen_we_ge10
assign phy_dout[(320*WE_MAP[10:8] + 80*WE_MAP[5:4] +
8*(WE_MAP[3:0]-5) + 4)+:4]
= {mux_we_n[3/PHASE_DIV], mux_we_n[2/PHASE_DIV],
mux_we_n[1/PHASE_DIV], mux_we_n[0]};
end
endgenerate
generate
if (REG_CTRL == "ON") begin: gen_parity_out
// Generate addr/ctrl parity output only for DDR3 and DDR2 registered DIMMs
assign out_parity
= mem_dq_out[48*PARITY_MAP[10:8] + 12*PARITY_MAP[5:4] +
PARITY_MAP[3:0]];
if (PARITY_MAP[3:0] < 4'hA) begin: gen_lt10
assign phy_dout[(320*PARITY_MAP[10:8] + 80*PARITY_MAP[5:4] +
8*PARITY_MAP[3:0])+:4]
= {parity_in[3/PHASE_DIV], parity_in[2/PHASE_DIV],
parity_in[1/PHASE_DIV], parity_in[0]};
end else begin: gen_ge10
assign phy_dout[(320*PARITY_MAP[10:8] + 80*PARITY_MAP[5:4] +
8*(PARITY_MAP[3:0]-5) + 4)+:4]
= {parity_in[3/PHASE_DIV], parity_in[2/PHASE_DIV],
parity_in[1/PHASE_DIV], parity_in[0]};
end
end
endgenerate
//*****************************************************************
generate
genvar m, n,x;
//*****************************************************************
// Control/address (multi-bit) buses
//*****************************************************************
// Row/Column address
for (m = 0; m < ROW_WIDTH; m = m + 1) begin: gen_addr_out
assign out_addr[m]
= mem_dq_out[48*ADDR_MAP[(12*m+8)+:3] +
12*ADDR_MAP[(12*m+4)+:2] +
ADDR_MAP[12*m+:4]];
if (ADDR_MAP[12*m+:4] < 4'hA) begin: gen_lt10
// For multi-bit buses, we also have to deal with transposition
// when going from the logic-side control bus to phy_dout
for (n = 0; n < 4; n = n + 1) begin: loop_xpose
assign phy_dout[320*ADDR_MAP[(12*m+8)+:3] +
80*ADDR_MAP[(12*m+4)+:2] +
8*ADDR_MAP[12*m+:4] + n]
= mux_address[ROW_WIDTH*(n/PHASE_DIV) + m];
end
end else begin: gen_ge10
for (n = 0; n < 4; n = n + 1) begin: loop_xpose
assign phy_dout[320*ADDR_MAP[(12*m+8)+:3] +
80*ADDR_MAP[(12*m+4)+:2] +
8*(ADDR_MAP[12*m+:4]-5) + 4 + n]
= mux_address[ROW_WIDTH*(n/PHASE_DIV) + m];
end
end
end
// Bank address
for (m = 0; m < BANK_WIDTH; m = m + 1) begin: gen_ba_out
assign out_ba[m]
= mem_dq_out[48*BANK_MAP[(12*m+8)+:3] +
12*BANK_MAP[(12*m+4)+:2] +
BANK_MAP[12*m+:4]];
if (BANK_MAP[12*m+:4] < 4'hA) begin: gen_lt10
for (n = 0; n < 4; n = n + 1) begin: loop_xpose
assign phy_dout[320*BANK_MAP[(12*m+8)+:3] +
80*BANK_MAP[(12*m+4)+:2] +
8*BANK_MAP[12*m+:4] + n]
= mux_bank[BANK_WIDTH*(n/PHASE_DIV) + m];
end
end else begin: gen_ge10
for (n = 0; n < 4; n = n + 1) begin: loop_xpose
assign phy_dout[320*BANK_MAP[(12*m+8)+:3] +
80*BANK_MAP[(12*m+4)+:2] +
8*(BANK_MAP[12*m+:4]-5) + 4 + n]
= mux_bank[BANK_WIDTH*(n/PHASE_DIV) + m];
end
end
end
// Chip select
if (USE_CS_PORT == 1) begin: gen_cs_n_out
for (m = 0; m < CS_WIDTH*nCS_PER_RANK; m = m + 1) begin: gen_cs_out
assign out_cs_n[m]
= mem_dq_out[48*CS_MAP[(12*m+8)+:3] +
12*CS_MAP[(12*m+4)+:2] +
CS_MAP[12*m+:4]];
if (CS_MAP[12*m+:4] < 4'hA) begin: gen_lt10
for (n = 0; n < 4; n = n + 1) begin: loop_xpose
assign phy_dout[320*CS_MAP[(12*m+8)+:3] +
80*CS_MAP[(12*m+4)+:2] +
8*CS_MAP[12*m+:4] + n]
= mux_cs_n[CS_WIDTH*nCS_PER_RANK*(n/PHASE_DIV) + m];
end
end else begin: gen_ge10
for (n = 0; n < 4; n = n + 1) begin: loop_xpose
assign phy_dout[320*CS_MAP[(12*m+8)+:3] +
80*CS_MAP[(12*m+4)+:2] +
8*(CS_MAP[12*m+:4]-5) + 4 + n]
= mux_cs_n[CS_WIDTH*nCS_PER_RANK*(n/PHASE_DIV) + m];
end
end
end
end
if(CKE_ODT_AUX == "FALSE") begin
// ODT_ports
wire [ODT_WIDTH*nCK_PER_CLK -1 :0] mux_odt_remap ;
if(RANKS == 1) begin
for(x =0 ; x < nCK_PER_CLK ; x = x+1) begin
assign mux_odt_remap[(x*ODT_WIDTH)+:ODT_WIDTH] = {ODT_WIDTH{mux_odt[0]}} ;
end
end else begin
for(x =0 ; x < 2*nCK_PER_CLK ; x = x+2) begin
assign mux_odt_remap[(x*ODT_WIDTH/RANKS)+:ODT_WIDTH/RANKS] = {ODT_WIDTH/RANKS{mux_odt[0]}} ;
assign mux_odt_remap[((x*ODT_WIDTH/RANKS)+(ODT_WIDTH/RANKS))+:ODT_WIDTH/RANKS] = {ODT_WIDTH/RANKS{mux_odt[1]}} ;
end
end
if (USE_ODT_PORT == 1) begin: gen_odt_out
for (m = 0; m < ODT_WIDTH; m = m + 1) begin: gen_odt_out_1
assign out_odt[m]
= mem_dq_out[48*ODT_MAP[(12*m+8)+:3] +
12*ODT_MAP[(12*m+4)+:2] +
ODT_MAP[12*m+:4]];
if (ODT_MAP[12*m+:4] < 4'hA) begin: gen_lt10
for (n = 0; n < 4; n = n + 1) begin: loop_xpose
assign phy_dout[320*ODT_MAP[(12*m+8)+:3] +
80*ODT_MAP[(12*m+4)+:2] +
8*ODT_MAP[12*m+:4] + n]
= mux_odt_remap[ODT_WIDTH*(n/PHASE_DIV) + m];
end
end else begin: gen_ge10
for (n = 0; n < 4; n = n + 1) begin: loop_xpose
assign phy_dout[320*ODT_MAP[(12*m+8)+:3] +
80*ODT_MAP[(12*m+4)+:2] +
8*(ODT_MAP[12*m+:4]-5) + 4 + n]
= mux_odt_remap[ODT_WIDTH*(n/PHASE_DIV) + m];
end
end
end
end
wire [CKE_WIDTH*nCK_PER_CLK -1:0] mux_cke_remap ;
for(x = 0 ; x < nCK_PER_CLK ; x = x +1) begin
assign mux_cke_remap[(x*CKE_WIDTH)+:CKE_WIDTH] = {CKE_WIDTH{mux_cke[x]}} ;
end
for (m = 0; m < CKE_WIDTH; m = m + 1) begin: gen_cke_out
assign out_cke[m]
= mem_dq_out[48*CKE_MAP[(12*m+8)+:3] +
12*CKE_MAP[(12*m+4)+:2] +
CKE_MAP[12*m+:4]];
if (CKE_MAP[12*m+:4] < 4'hA) begin: gen_lt10
for (n = 0; n < 4; n = n + 1) begin: loop_xpose
assign phy_dout[320*CKE_MAP[(12*m+8)+:3] +
80*CKE_MAP[(12*m+4)+:2] +
8*CKE_MAP[12*m+:4] + n]
= mux_cke_remap[CKE_WIDTH*(n/PHASE_DIV) + m];
end
end else begin: gen_ge10
for (n = 0; n < 4; n = n + 1) begin: loop_xpose
assign phy_dout[320*CKE_MAP[(12*m+8)+:3] +
80*CKE_MAP[(12*m+4)+:2] +
8*(CKE_MAP[12*m+:4]-5) + 4 + n]
= mux_cke_remap[CKE_WIDTH*(n/PHASE_DIV) + m];
end
end
end
end
//*****************************************************************
// Data mask
//*****************************************************************
if (USE_DM_PORT == 1) begin: gen_dm_out
for (m = 0; m < DM_WIDTH; m = m + 1) begin: gen_dm_out
assign out_dm[m]
= mem_dq_out[48*FULL_MASK_MAP[(12*m+8)+:3] +
12*FULL_MASK_MAP[(12*m+4)+:2] +
FULL_MASK_MAP[12*m+:4]];
assign ts_dm[m]
= mem_dq_ts[48*FULL_MASK_MAP[(12*m+8)+:3] +
12*FULL_MASK_MAP[(12*m+4)+:2] +
FULL_MASK_MAP[12*m+:4]];
for (n = 0; n < PHASE_PER_CLK; n = n + 1) begin: loop_xpose
assign phy_dout[320*FULL_MASK_MAP[(12*m+8)+:3] +
80*FULL_MASK_MAP[(12*m+4)+:2] +
8*FULL_MASK_MAP[12*m+:4] + n]
= mux_wrdata_mask[DM_WIDTH*n + m];
end
end
end
//*****************************************************************
// Input and output DQ
//*****************************************************************
for (m = 0; m < DQ_WIDTH; m = m + 1) begin: gen_dq_inout
// to MC_PHY
assign mem_dq_in[40*FULL_DATA_MAP[(12*m+8)+:3] +
10*FULL_DATA_MAP[(12*m+4)+:2] +
FULL_DATA_MAP[12*m+:4]]
= in_dq[m];
// to I/O buffers
assign out_dq[m]
= mem_dq_out[48*FULL_DATA_MAP[(12*m+8)+:3] +
12*FULL_DATA_MAP[(12*m+4)+:2] +
FULL_DATA_MAP[12*m+:4]];
assign ts_dq[m]
= mem_dq_ts[48*FULL_DATA_MAP[(12*m+8)+:3] +
12*FULL_DATA_MAP[(12*m+4)+:2] +
FULL_DATA_MAP[12*m+:4]];
for (n = 0; n < PHASE_PER_CLK; n = n + 1) begin: loop_xpose
assign phy_dout[320*FULL_DATA_MAP[(12*m+8)+:3] +
80*FULL_DATA_MAP[(12*m+4)+:2] +
8*FULL_DATA_MAP[12*m+:4] + n]
= mux_wrdata[DQ_WIDTH*n + m];
end
end
//*****************************************************************
// Input and output DQS
//*****************************************************************
for (m = 0; m < DQS_WIDTH; m = m + 1) begin: gen_dqs_inout
// to MC_PHY
assign mem_dqs_in[4*DQS_BYTE_MAP[(8*m+4)+:3] + DQS_BYTE_MAP[(8*m)+:2]]
= in_dqs[m];
// to I/O buffers
assign out_dqs[m]
= mem_dqs_out[4*DQS_BYTE_MAP[(8*m+4)+:3] + DQS_BYTE_MAP[(8*m)+:2]];
assign ts_dqs[m]
= mem_dqs_ts[4*DQS_BYTE_MAP[(8*m+4)+:3] + DQS_BYTE_MAP[(8*m)+:2]];
end
endgenerate
//***************************************************************************
// Memory I/F output and I/O buffer instantiation
//***************************************************************************
// Note on instantiation - generally at the minimum, it's not required to
// instantiate the output buffers - they can be inferred by the synthesis
// tool, and there aren't any attributes that need to be associated with
// them. Consider as a future option to take out the OBUF instantiations
OBUF u_cas_n_obuf
(
.I (out_cas_n),
.O (ddr_cas_n)
);
OBUF u_ras_n_obuf
(
.I (out_ras_n),
.O (ddr_ras_n)
);
OBUF u_we_n_obuf
(
.I (out_we_n),
.O (ddr_we_n)
);
generate
genvar p;
for (p = 0; p < ROW_WIDTH; p = p + 1) begin: gen_addr_obuf
OBUF u_addr_obuf
(
.I (out_addr[p]),
.O (ddr_addr[p])
);
end
for (p = 0; p < BANK_WIDTH; p = p + 1) begin: gen_bank_obuf
OBUF u_bank_obuf
(
.I (out_ba[p]),
.O (ddr_ba[p])
);
end
if (USE_CS_PORT == 1) begin: gen_cs_n_obuf
for (p = 0; p < CS_WIDTH*nCS_PER_RANK; p = p + 1) begin: gen_cs_obuf
OBUF u_cs_n_obuf
(
.I (out_cs_n[p]),
.O (ddr_cs_n[p])
);
end
end
if(CKE_ODT_AUX == "FALSE")begin:cke_odt_thru_outfifo
if (USE_ODT_PORT== 1) begin: gen_odt_obuf
for (p = 0; p < ODT_WIDTH; p = p + 1) begin: gen_odt_obuf
OBUF u_cs_n_obuf
(
.I (out_odt[p]),
.O (ddr_odt[p])
);
end
end
for (p = 0; p < CKE_WIDTH; p = p + 1) begin: gen_cke_obuf
OBUF u_cs_n_obuf
(
.I (out_cke[p]),
.O (ddr_cke[p])
);
end
end
if (REG_CTRL == "ON") begin: gen_parity_obuf
// Generate addr/ctrl parity output only for DDR3 registered DIMMs
OBUF u_parity_obuf
(
.I (out_parity),
.O (ddr_parity)
);
end else begin: gen_parity_tieoff
assign ddr_parity = 1'b0;
end
if ((DRAM_TYPE == "DDR3") || (REG_CTRL == "ON")) begin: gen_reset_obuf
// Generate reset output only for DDR3 and DDR2 RDIMMs
OBUF u_reset_obuf
(
.I (mux_reset_n),
.O (ddr_reset_n)
);
end else begin: gen_reset_tieoff
assign ddr_reset_n = 1'b1;
end
if (USE_DM_PORT == 1) begin: gen_dm_obuf
for (p = 0; p < DM_WIDTH; p = p + 1) begin: loop_dm
OBUFT u_dm_obuf
(
.I (out_dm[p]),
.T (ts_dm[p]),
.O (ddr_dm[p])
);
end
end else begin: gen_dm_tieoff
assign ddr_dm = 'b0;
end
if (DATA_IO_PRIM_TYPE == "HP_LP") begin: gen_dq_iobuf_HP
for (p = 0; p < DQ_WIDTH; p = p + 1) begin: gen_dq_iobuf
IOBUF_DCIEN #
(
.IBUF_LOW_PWR (IBUF_LOW_PWR)
)
u_iobuf_dq
(
.DCITERMDISABLE (data_io_idle_pwrdwn),
.IBUFDISABLE (data_io_idle_pwrdwn),
.I (out_dq[p]),
.T (ts_dq[p]),
.O (in_dq[p]),
.IO (ddr_dq[p])
);
end
end else if (DATA_IO_PRIM_TYPE == "HR_LP") begin: gen_dq_iobuf_HR
for (p = 0; p < DQ_WIDTH; p = p + 1) begin: gen_dq_iobuf
IOBUF_INTERMDISABLE #
(
.IBUF_LOW_PWR (IBUF_LOW_PWR)
)
u_iobuf_dq
(
.INTERMDISABLE (data_io_idle_pwrdwn),
.IBUFDISABLE (data_io_idle_pwrdwn),
.I (out_dq[p]),
.T (ts_dq[p]),
.O (in_dq[p]),
.IO (ddr_dq[p])
);
end
end else begin: gen_dq_iobuf_default
for (p = 0; p < DQ_WIDTH; p = p + 1) begin: gen_dq_iobuf
IOBUF #
(
.IBUF_LOW_PWR (IBUF_LOW_PWR)
)
u_iobuf_dq
(
.I (out_dq[p]),
.T (ts_dq[p]),
.O (in_dq[p]),
.IO (ddr_dq[p])
);
end
end
if (DATA_IO_PRIM_TYPE == "HP_LP") begin: gen_dqs_iobuf_HP
for (p = 0; p < DQS_WIDTH; p = p + 1) begin: gen_dqs_iobuf
if ((DRAM_TYPE == "DDR2") &&
(DDR2_DQSN_ENABLE != "YES")) begin: gen_ddr2_dqs_se
IOBUF_DCIEN #
(
.IBUF_LOW_PWR (IBUF_LOW_PWR)
)
u_iobuf_dqs
(
.DCITERMDISABLE (data_io_idle_pwrdwn),
.IBUFDISABLE (data_io_idle_pwrdwn),
.I (out_dqs[p]),
.T (ts_dqs[p]),
.O (in_dqs[p]),
.IO (ddr_dqs[p])
);
assign ddr_dqs_n[p] = 1'b0;
end else begin: gen_dqs_diff
IOBUFDS_DCIEN #
(
.IBUF_LOW_PWR (IBUF_LOW_PWR),
.DQS_BIAS ("TRUE")
)
u_iobuf_dqs
(
.DCITERMDISABLE (data_io_idle_pwrdwn),
.IBUFDISABLE (data_io_idle_pwrdwn),
.I (out_dqs[p]),
.T (ts_dqs[p]),
.O (in_dqs[p]),
.IO (ddr_dqs[p]),
.IOB (ddr_dqs_n[p])
);
end
end
end else if (DATA_IO_PRIM_TYPE == "HR_LP") begin: gen_dqs_iobuf_HR
for (p = 0; p < DQS_WIDTH; p = p + 1) begin: gen_dqs_iobuf
if ((DRAM_TYPE == "DDR2") &&
(DDR2_DQSN_ENABLE != "YES")) begin: gen_ddr2_dqs_se
IOBUF_INTERMDISABLE #
(
.IBUF_LOW_PWR (IBUF_LOW_PWR)
)
u_iobuf_dqs
(
.INTERMDISABLE (data_io_idle_pwrdwn),
.IBUFDISABLE (data_io_idle_pwrdwn),
.I (out_dqs[p]),
.T (ts_dqs[p]),
.O (in_dqs[p]),
.IO (ddr_dqs[p])
);
assign ddr_dqs_n[p] = 1'b0;
end else begin: gen_dqs_diff
IOBUFDS_INTERMDISABLE #
(
.IBUF_LOW_PWR (IBUF_LOW_PWR),
.DQS_BIAS ("TRUE")
)
u_iobuf_dqs
(
.INTERMDISABLE (data_io_idle_pwrdwn),
.IBUFDISABLE (data_io_idle_pwrdwn),
.I (out_dqs[p]),
.T (ts_dqs[p]),
.O (in_dqs[p]),
.IO (ddr_dqs[p]),
.IOB (ddr_dqs_n[p])
);
end
end
end else begin: gen_dqs_iobuf_default
for (p = 0; p < DQS_WIDTH; p = p + 1) begin: gen_dqs_iobuf
if ((DRAM_TYPE == "DDR2") &&
(DDR2_DQSN_ENABLE != "YES")) begin: gen_ddr2_dqs_se
IOBUF #
(
.IBUF_LOW_PWR (IBUF_LOW_PWR)
)
u_iobuf_dqs
(
.I (out_dqs[p]),
.T (ts_dqs[p]),
.O (in_dqs[p]),
.IO (ddr_dqs[p])
);
assign ddr_dqs_n[p] = 1'b0;
end else begin: gen_dqs_diff
IOBUFDS #
(
.IBUF_LOW_PWR (IBUF_LOW_PWR),
.DQS_BIAS ("TRUE")
)
u_iobuf_dqs
(
.I (out_dqs[p]),
.T (ts_dqs[p]),
.O (in_dqs[p]),
.IO (ddr_dqs[p]),
.IOB (ddr_dqs_n[p])
);
end
end
end
endgenerate
always @(posedge clk) begin
phy_ctl_wd_i1 <= #TCQ phy_ctl_wd;
phy_ctl_wr_i1 <= #TCQ phy_ctl_wr;
phy_ctl_wd_i2 <= #TCQ phy_ctl_wd_i1;
phy_ctl_wr_i2 <= #TCQ phy_ctl_wr_i1;
data_offset_1_i1 <= #TCQ data_offset_1;
data_offset_1_i2 <= #TCQ data_offset_1_i1;
data_offset_2_i1 <= #TCQ data_offset_2;
data_offset_2_i2 <= #TCQ data_offset_2_i1;
end
// 2 cycles of command delay needed for 4;1 mode. 2:1 mode does not need it.
// 2:1 mode the command goes through pre fifo
assign phy_ctl_wd_temp = (nCK_PER_CLK == 4) ? phy_ctl_wd_i2 : phy_ctl_wd_of;
assign phy_ctl_wr_temp = (nCK_PER_CLK == 4) ? phy_ctl_wr_i2 : phy_ctl_wr_of;
assign data_offset_1_temp = (nCK_PER_CLK == 4) ? data_offset_1_i2 : data_offset_1_of;
assign data_offset_2_temp = (nCK_PER_CLK == 4) ? data_offset_2_i2 : data_offset_2_of;
generate
begin
mig_7series_v1_9_ddr_of_pre_fifo #
(
.TCQ (25),
.DEPTH (8),
.WIDTH (32)
)
phy_ctl_pre_fifo_0
(
.clk (clk),
.rst (rst),
.full_in (phy_ctl_full_temp[1]),
.wr_en_in (phy_ctl_wr),
.d_in (phy_ctl_wd),
.wr_en_out (phy_ctl_wr_of),
.d_out (phy_ctl_wd_of)
);
mig_7series_v1_9_ddr_of_pre_fifo #
(
.TCQ (25),
.DEPTH (8),
.WIDTH (6)
)
phy_ctl_pre_fifo_1
(
.clk (clk),
.rst (rst),
.full_in (phy_ctl_full_temp[2]),
.wr_en_in (phy_ctl_wr),
.d_in (data_offset_1),
.wr_en_out (),
.d_out (data_offset_1_of)
);
mig_7series_v1_9_ddr_of_pre_fifo #
(
.TCQ (25),
.DEPTH (8),
.WIDTH (6)
)
phy_ctl_pre_fifo_2
(
.clk (clk),
.rst (rst),
.full_in (phy_ctl_full_temp[3]),
.wr_en_in (phy_ctl_wr),
.d_in (data_offset_2),
.wr_en_out (),
.d_out (data_offset_2_of)
);
end
endgenerate
//***************************************************************************
// Hard PHY instantiation
//***************************************************************************
assign phy_ctl_full = phy_ctl_full_temp[0];
mig_7series_v1_9_ddr_mc_phy #
(
.BYTE_LANES_B0 (BYTE_LANES_B0),
.BYTE_LANES_B1 (BYTE_LANES_B1),
.BYTE_LANES_B2 (BYTE_LANES_B2),
.BYTE_LANES_B3 (BYTE_LANES_B3),
.BYTE_LANES_B4 (BYTE_LANES_B4),
.DATA_CTL_B0 (DATA_CTL_B0),
.DATA_CTL_B1 (DATA_CTL_B1),
.DATA_CTL_B2 (DATA_CTL_B2),
.DATA_CTL_B3 (DATA_CTL_B3),
.DATA_CTL_B4 (DATA_CTL_B4),
.PHY_0_BITLANES (PHY_0_BITLANES),
.PHY_1_BITLANES (PHY_1_BITLANES),
.PHY_2_BITLANES (PHY_2_BITLANES),
.PHY_0_BITLANES_OUTONLY (PHY_0_BITLANES_OUTONLY),
.PHY_1_BITLANES_OUTONLY (PHY_1_BITLANES_OUTONLY),
.PHY_2_BITLANES_OUTONLY (PHY_2_BITLANES_OUTONLY),
.RCLK_SELECT_BANK (CKE_ODT_RCLK_SELECT_BANK),
.RCLK_SELECT_LANE (CKE_ODT_RCLK_SELECT_LANE),
//.CKE_ODT_AUX (CKE_ODT_AUX),
.GENERATE_DDR_CK_MAP (TMP_GENERATE_DDR_CK_MAP),
.BYTELANES_DDR_CK (TMP_BYTELANES_DDR_CK),
.NUM_DDR_CK (CK_WIDTH),
.LP_DDR_CK_WIDTH (LP_DDR_CK_WIDTH),
.PO_CTL_COARSE_BYPASS ("FALSE"),
.PHYCTL_CMD_FIFO ("FALSE"),
.PHY_CLK_RATIO (nCK_PER_CLK),
.MASTER_PHY_CTL (MASTER_PHY_CTL),
.PHY_FOUR_WINDOW_CLOCKS (63),
.PHY_EVENTS_DELAY (18),
.PHY_COUNT_EN ("FALSE"), //PHY_COUNT_EN
.PHY_SYNC_MODE ("FALSE"),
.SYNTHESIS ((SIM_CAL_OPTION == "NONE") ? "TRUE" : "FALSE"),
.PHY_DISABLE_SEQ_MATCH ("TRUE"), //"TRUE"
.PHY_0_GENERATE_IDELAYCTRL ("FALSE"),
.PHY_0_A_PI_FREQ_REF_DIV (PHY_0_A_PI_FREQ_REF_DIV),
.PHY_0_CMD_OFFSET (PHY_0_CMD_OFFSET), //for CKE
.PHY_0_RD_CMD_OFFSET_0 (PHY_0_RD_CMD_OFFSET_0),
.PHY_0_RD_CMD_OFFSET_1 (PHY_0_RD_CMD_OFFSET_1),
.PHY_0_RD_CMD_OFFSET_2 (PHY_0_RD_CMD_OFFSET_2),
.PHY_0_RD_CMD_OFFSET_3 (PHY_0_RD_CMD_OFFSET_3),
.PHY_0_RD_DURATION_0 (6),
.PHY_0_RD_DURATION_1 (6),
.PHY_0_RD_DURATION_2 (6),
.PHY_0_RD_DURATION_3 (6),
.PHY_0_WR_CMD_OFFSET_0 (PHY_0_WR_CMD_OFFSET_0),
.PHY_0_WR_CMD_OFFSET_1 (PHY_0_WR_CMD_OFFSET_1),
.PHY_0_WR_CMD_OFFSET_2 (PHY_0_WR_CMD_OFFSET_2),
.PHY_0_WR_CMD_OFFSET_3 (PHY_0_WR_CMD_OFFSET_3),
.PHY_0_WR_DURATION_0 (PHY_0_WR_DURATION_0),
.PHY_0_WR_DURATION_1 (PHY_0_WR_DURATION_1),
.PHY_0_WR_DURATION_2 (PHY_0_WR_DURATION_2),
.PHY_0_WR_DURATION_3 (PHY_0_WR_DURATION_3),
.PHY_0_AO_TOGGLE ((RANKS == 1) ? 1 : 5),
.PHY_0_A_PO_OCLK_DELAY (PHY_0_A_PO_OCLK_DELAY),
.PHY_0_B_PO_OCLK_DELAY (PHY_0_A_PO_OCLK_DELAY),
.PHY_0_C_PO_OCLK_DELAY (PHY_0_A_PO_OCLK_DELAY),
.PHY_0_D_PO_OCLK_DELAY (PHY_0_A_PO_OCLK_DELAY),
.PHY_0_A_PO_OCLKDELAY_INV (PO_OCLKDELAY_INV),
.PHY_0_A_IDELAYE2_IDELAY_VALUE (PHY_0_A_IDELAYE2_IDELAY_VALUE),
.PHY_0_B_IDELAYE2_IDELAY_VALUE (PHY_0_A_IDELAYE2_IDELAY_VALUE),
.PHY_0_C_IDELAYE2_IDELAY_VALUE (PHY_0_A_IDELAYE2_IDELAY_VALUE),
.PHY_0_D_IDELAYE2_IDELAY_VALUE (PHY_0_A_IDELAYE2_IDELAY_VALUE),
.PHY_1_GENERATE_IDELAYCTRL ("FALSE"),
//.PHY_1_GENERATE_DDR_CK (TMP_PHY_1_GENERATE_DDR_CK),
//.PHY_1_NUM_DDR_CK (1),
.PHY_1_A_PO_OCLK_DELAY (PHY_0_A_PO_OCLK_DELAY),
.PHY_1_B_PO_OCLK_DELAY (PHY_0_A_PO_OCLK_DELAY),
.PHY_1_C_PO_OCLK_DELAY (PHY_0_A_PO_OCLK_DELAY),
.PHY_1_D_PO_OCLK_DELAY (PHY_0_A_PO_OCLK_DELAY),
.PHY_1_A_IDELAYE2_IDELAY_VALUE (PHY_0_A_IDELAYE2_IDELAY_VALUE),
.PHY_1_B_IDELAYE2_IDELAY_VALUE (PHY_0_A_IDELAYE2_IDELAY_VALUE),
.PHY_1_C_IDELAYE2_IDELAY_VALUE (PHY_0_A_IDELAYE2_IDELAY_VALUE),
.PHY_1_D_IDELAYE2_IDELAY_VALUE (PHY_0_A_IDELAYE2_IDELAY_VALUE),
.PHY_2_GENERATE_IDELAYCTRL ("FALSE"),
//.PHY_2_GENERATE_DDR_CK (TMP_PHY_2_GENERATE_DDR_CK),
//.PHY_2_NUM_DDR_CK (1),
.PHY_2_A_PO_OCLK_DELAY (PHY_0_A_PO_OCLK_DELAY),
.PHY_2_B_PO_OCLK_DELAY (PHY_0_A_PO_OCLK_DELAY),
.PHY_2_C_PO_OCLK_DELAY (PHY_0_A_PO_OCLK_DELAY),
.PHY_2_D_PO_OCLK_DELAY (PHY_0_A_PO_OCLK_DELAY),
.PHY_2_A_IDELAYE2_IDELAY_VALUE (PHY_0_A_IDELAYE2_IDELAY_VALUE),
.PHY_2_B_IDELAYE2_IDELAY_VALUE (PHY_0_A_IDELAYE2_IDELAY_VALUE),
.PHY_2_C_IDELAYE2_IDELAY_VALUE (PHY_0_A_IDELAYE2_IDELAY_VALUE),
.PHY_2_D_IDELAYE2_IDELAY_VALUE (PHY_0_A_IDELAYE2_IDELAY_VALUE),
.TCK (tCK),
.PHY_0_IODELAY_GRP (IODELAY_GRP)
,.PHY_1_IODELAY_GRP (IODELAY_GRP)
,.PHY_2_IODELAY_GRP (IODELAY_GRP)
,.BANK_TYPE (BANK_TYPE)
,.CKE_ODT_AUX (CKE_ODT_AUX)
)
u_ddr_mc_phy
(
.rst (rst),
// Don't use MC_PHY to generate DDR_RESET_N output. Instead
// generate this output outside of MC_PHY (and synchronous to CLK)
.ddr_rst_in_n (1'b1),
.phy_clk (clk),
.freq_refclk (freq_refclk),
.mem_refclk (mem_refclk),
// Remove later - always same connection as phy_clk port
.mem_refclk_div4 (clk),
.pll_lock (pll_lock),
.auxout_clk (),
.sync_pulse (sync_pulse),
// IDELAYCTRL instantiated outside of mc_phy module
.idelayctrl_refclk (),
.phy_dout (phy_dout),
.phy_cmd_wr_en (phy_cmd_wr_en),
.phy_data_wr_en (phy_data_wr_en),
.phy_rd_en (phy_rd_en),
.phy_ctl_wd (phy_ctl_wd_temp),
.phy_ctl_wr (phy_ctl_wr_temp),
.if_empty_def (phy_if_empty_def),
.if_rst (phy_if_reset),
.phyGo ('b1),
.aux_in_1 (aux_in_1),
.aux_in_2 (aux_in_2),
// No support yet for different data offsets for different I/O banks
// (possible use in supporting wider range of skew among bytes)
.data_offset_1 (data_offset_1_temp),
.data_offset_2 (data_offset_2_temp),
.cke_in (),
.if_a_empty (),
.if_empty (if_empty),
.if_empty_or (),
.if_empty_and (),
.of_ctl_a_full (),
// .of_data_a_full (phy_data_full),
.of_ctl_full (phy_cmd_full),
.of_data_full (),
.pre_data_a_full (phy_pre_data_a_full),
.idelay_ld (idelay_ld),
.idelay_ce (idelay_ce),
.idelay_inc (idelay_inc),
.input_sink (),
.phy_din (phy_din),
.phy_ctl_a_full (),
.phy_ctl_full (phy_ctl_full_temp),
.mem_dq_out (mem_dq_out),
.mem_dq_ts (mem_dq_ts),
.mem_dq_in (mem_dq_in),
.mem_dqs_out (mem_dqs_out),
.mem_dqs_ts (mem_dqs_ts),
.mem_dqs_in (mem_dqs_in),
.aux_out (aux_out),
.phy_ctl_ready (),
.rst_out (),
.ddr_clk (ddr_clk),
//.rclk (),
.mcGo (phy_mc_go),
.phy_write_calib (phy_write_calib),
.phy_read_calib (phy_read_calib),
.calib_sel (calib_sel),
.calib_in_common (calib_in_common),
.calib_zero_inputs (calib_zero_inputs),
.calib_zero_ctrl (calib_zero_ctrl),
.calib_zero_lanes ('b0),
.po_fine_enable (po_fine_enable),
.po_coarse_enable (po_coarse_enable),
.po_fine_inc (po_fine_inc),
.po_coarse_inc (po_coarse_inc),
.po_counter_load_en (po_counter_load_en),
.po_sel_fine_oclk_delay (po_sel_fine_oclk_delay),
.po_counter_load_val (po_counter_load_val),
.po_counter_read_en (po_counter_read_en),
.po_coarse_overflow (),
.po_fine_overflow (),
.po_counter_read_val (po_counter_read_val),
.pi_rst_dqs_find (pi_rst_dqs_find),
.pi_fine_enable (pi_fine_enable),
.pi_fine_inc (pi_fine_inc),
.pi_counter_load_en (pi_counter_load_en),
.pi_counter_read_en (dbg_pi_counter_read_en),
.pi_counter_load_val (pi_counter_load_val),
.pi_fine_overflow (),
.pi_counter_read_val (pi_counter_read_val),
.pi_phase_locked (pi_phase_locked),
.pi_phase_locked_all (pi_phase_locked_all),
.pi_dqs_found (),
.pi_dqs_found_any (pi_dqs_found),
.pi_dqs_found_all (pi_dqs_found_all),
.pi_dqs_found_lanes (dbg_pi_dqs_found_lanes_phy4lanes),
// Currently not being used. May be used in future if periodic
// reads become a requirement. This output could be used to signal
// a catastrophic failure in read capture and the need for
// re-calibration.
.pi_dqs_out_of_range (pi_dqs_out_of_range)
,.ref_dll_lock (ref_dll_lock)
,.pi_phase_locked_lanes (dbg_pi_phase_locked_phy4lanes)
// ,.rst_phaser_ref (rst_phaser_ref)
);
endmodule
|
//*****************************************************************************
// (c) Copyright 2008 - 2013 Xilinx, Inc. All rights reserved.
//
// This file contains confidential and proprietary information
// of Xilinx, Inc. and is protected under U.S. and
// international copyright and other intellectual property
// laws.
//
// DISCLAIMER
// This disclaimer is not a license and does not grant any
// rights to the materials distributed herewith. Except as
// otherwise provided in a valid license issued to you by
// Xilinx, and to the maximum extent permitted by applicable
// law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND
// WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES
// AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
// BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-
// INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and
// (2) Xilinx shall not be liable (whether in contract or tort,
// including negligence, or under any other theory of
// liability) for any loss or damage of any kind or nature
// related to, arising under or in connection with these
// materials, including for any direct, or any indirect,
// special, incidental, or consequential loss or damage
// (including loss of data, profits, goodwill, or any type of
// loss or damage suffered as a result of any action brought
// by a third party) even if such damage or loss was
// reasonably foreseeable or Xilinx had been advised of the
// possibility of the same.
//
// CRITICAL APPLICATIONS
// Xilinx products are not designed or intended to be fail-
// safe, or for use in any application requiring fail-safe
// performance, such as life-support or safety devices or
// systems, Class III medical devices, nuclear facilities,
// applications related to the deployment of airbags, or any
// other applications that could lead to death, personal
// injury, or severe property or environmental damage
// (individually and collectively, "Critical
// Applications"). Customer assumes the sole risk and
// liability of any use of Xilinx products in Critical
// Applications, subject only to applicable laws and
// regulations governing limitations on product liability.
//
// THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS
// PART OF THIS FILE AT ALL TIMES.
//
//*****************************************************************************
// ____ ____
// / /\/ /
// /___/ \ / Vendor : Xilinx
// \ \ \/ Version : %version
// \ \ Application : MIG
// / / Filename : ddr_mc_phy_wrapper.v
// /___/ /\ Date Last Modified : $date$
// \ \ / \ Date Created : Oct 10 2010
// \___\/\___\
//
//Device : 7 Series
//Design Name : DDR3 SDRAM
//Purpose : Wrapper file that encompasses the MC_PHY module
// instantiation and handles the vector remapping between
// the MC_PHY ports and the user's DDR3 ports. Vector
// remapping affects DDR3 control, address, and DQ/DQS/DM.
//Reference :
//Revision History :
//*****************************************************************************
`timescale 1 ps / 1 ps
module mig_7series_v1_9_ddr_mc_phy_wrapper #
(
parameter TCQ = 100, // Register delay (simulation only)
parameter tCK = 2500, // ps
parameter BANK_TYPE = "HP_IO", // # = "HP_IO", "HPL_IO", "HR_IO", "HRL_IO"
parameter DATA_IO_PRIM_TYPE = "DEFAULT", // # = "HP_LP", "HR_LP", "DEFAULT"
parameter DATA_IO_IDLE_PWRDWN = "ON", // "ON" or "OFF"
parameter IODELAY_GRP = "IODELAY_MIG",
parameter nCK_PER_CLK = 4, // Memory:Logic clock ratio
parameter nCS_PER_RANK = 1, // # of unique CS outputs per rank
parameter BANK_WIDTH = 3, // # of bank address
parameter CKE_WIDTH = 1, // # of clock enable outputs
parameter CS_WIDTH = 1, // # of chip select
parameter CK_WIDTH = 1, // # of CK
parameter CWL = 5, // CAS Write latency
parameter DDR2_DQSN_ENABLE = "YES", // Enable differential DQS for DDR2
parameter DM_WIDTH = 8, // # of data mask
parameter DQ_WIDTH = 16, // # of data bits
parameter DQS_CNT_WIDTH = 3, // ceil(log2(DQS_WIDTH))
parameter DQS_WIDTH = 8, // # of strobe pairs
parameter DRAM_TYPE = "DDR3", // DRAM type (DDR2, DDR3)
parameter RANKS = 4, // # of ranks
parameter ODT_WIDTH = 1, // # of ODT outputs
parameter REG_CTRL = "OFF", // "ON" for registered DIMM
parameter ROW_WIDTH = 16, // # of row/column address
parameter USE_CS_PORT = 1, // Support chip select output
parameter USE_DM_PORT = 1, // Support data mask output
parameter USE_ODT_PORT = 1, // Support ODT output
parameter IBUF_LPWR_MODE = "OFF", // input buffer low power option
parameter LP_DDR_CK_WIDTH = 2,
// Hard PHY parameters
parameter PHYCTL_CMD_FIFO = "FALSE",
parameter DATA_CTL_B0 = 4'hc,
parameter DATA_CTL_B1 = 4'hf,
parameter DATA_CTL_B2 = 4'hf,
parameter DATA_CTL_B3 = 4'hf,
parameter DATA_CTL_B4 = 4'hf,
parameter BYTE_LANES_B0 = 4'b1111,
parameter BYTE_LANES_B1 = 4'b0000,
parameter BYTE_LANES_B2 = 4'b0000,
parameter BYTE_LANES_B3 = 4'b0000,
parameter BYTE_LANES_B4 = 4'b0000,
parameter PHY_0_BITLANES = 48'h0000_0000_0000,
parameter PHY_1_BITLANES = 48'h0000_0000_0000,
parameter PHY_2_BITLANES = 48'h0000_0000_0000,
// Parameters calculated outside of this block
parameter HIGHEST_BANK = 3, // Highest I/O bank index
parameter HIGHEST_LANE = 12, // Highest byte lane index
// ** Pin mapping parameters
// Parameters for mapping between hard PHY and physical DDR3 signals
// There are 2 classes of parameters:
// - DQS_BYTE_MAP, CK_BYTE_MAP, CKE_ODT_BYTE_MAP: These consist of
// 8-bit elements. Each element indicates the bank and byte lane
// location of that particular signal. The bit lane in this case
// doesn't need to be specified, either because there's only one
// pin pair in each byte lane that the DQS or CK pair can be
// located at, or in the case of CKE_ODT_BYTE_MAP, only the byte
// lane needs to be specified in order to determine which byte
// lane generates the RCLK (Note that CKE, and ODT must be located
// in the same bank, thus only one element in CKE_ODT_BYTE_MAP)
// [7:4] = bank # (0-4)
// [3:0] = byte lane # (0-3)
// - All other MAP parameters: These consist of 12-bit elements. Each
// element indicates the bank, byte lane, and bit lane location of
// that particular signal:
// [11:8] = bank # (0-4)
// [7:4] = byte lane # (0-3)
// [3:0] = bit lane # (0-11)
// Note that not all elements in all parameters will be used - it
// depends on the actual widths of the DDR3 buses. The parameters are
// structured to support a maximum of:
// - DQS groups: 18
// - data mask bits: 18
// In addition, the default parameter size of some of the parameters will
// support a certain number of bits, however, this can be expanded at
// compile time by expanding the width of the vector passed into this
// parameter
// - chip selects: 10
// - bank bits: 3
// - address bits: 16
parameter CK_BYTE_MAP
= 144'h00_00_00_00_00_00_00_00_00_00_00_00_00_00_00_00_00_00,
parameter ADDR_MAP
= 192'h000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000,
parameter BANK_MAP = 36'h000_000_000,
parameter CAS_MAP = 12'h000,
parameter CKE_ODT_BYTE_MAP = 8'h00,
parameter CKE_MAP = 96'h000_000_000_000_000_000_000_000,
parameter ODT_MAP = 96'h000_000_000_000_000_000_000_000,
parameter CKE_ODT_AUX = "FALSE",
parameter CS_MAP = 120'h000_000_000_000_000_000_000_000_000_000,
parameter PARITY_MAP = 12'h000,
parameter RAS_MAP = 12'h000,
parameter WE_MAP = 12'h000,
parameter DQS_BYTE_MAP
= 144'h00_00_00_00_00_00_00_00_00_00_00_00_00_00_00_00_00_00,
// DATAx_MAP parameter is used for byte lane X in the design
parameter DATA0_MAP = 96'h000_000_000_000_000_000_000_000,
parameter DATA1_MAP = 96'h000_000_000_000_000_000_000_000,
parameter DATA2_MAP = 96'h000_000_000_000_000_000_000_000,
parameter DATA3_MAP = 96'h000_000_000_000_000_000_000_000,
parameter DATA4_MAP = 96'h000_000_000_000_000_000_000_000,
parameter DATA5_MAP = 96'h000_000_000_000_000_000_000_000,
parameter DATA6_MAP = 96'h000_000_000_000_000_000_000_000,
parameter DATA7_MAP = 96'h000_000_000_000_000_000_000_000,
parameter DATA8_MAP = 96'h000_000_000_000_000_000_000_000,
parameter DATA9_MAP = 96'h000_000_000_000_000_000_000_000,
parameter DATA10_MAP = 96'h000_000_000_000_000_000_000_000,
parameter DATA11_MAP = 96'h000_000_000_000_000_000_000_000,
parameter DATA12_MAP = 96'h000_000_000_000_000_000_000_000,
parameter DATA13_MAP = 96'h000_000_000_000_000_000_000_000,
parameter DATA14_MAP = 96'h000_000_000_000_000_000_000_000,
parameter DATA15_MAP = 96'h000_000_000_000_000_000_000_000,
parameter DATA16_MAP = 96'h000_000_000_000_000_000_000_000,
parameter DATA17_MAP = 96'h000_000_000_000_000_000_000_000,
// MASK0_MAP used for bytes [8:0], MASK1_MAP for bytes [17:9]
parameter MASK0_MAP = 108'h000_000_000_000_000_000_000_000_000,
parameter MASK1_MAP = 108'h000_000_000_000_000_000_000_000_000,
// Simulation options
parameter SIM_CAL_OPTION = "NONE",
// The PHY_CONTROL primitive in the bank where PLL exists is declared
// as the Master PHY_CONTROL.
parameter MASTER_PHY_CTL = 1
)
(
input rst,
input clk,
input freq_refclk,
input mem_refclk,
input pll_lock,
input sync_pulse,
input idelayctrl_refclk,
input phy_cmd_wr_en,
input phy_data_wr_en,
input [31:0] phy_ctl_wd,
input phy_ctl_wr,
input phy_if_empty_def,
input phy_if_reset,
input [5:0] data_offset_1,
input [5:0] data_offset_2,
input [3:0] aux_in_1,
input [3:0] aux_in_2,
output [4:0] idelaye2_init_val,
output [5:0] oclkdelay_init_val,
output if_empty,
output phy_ctl_full,
output phy_cmd_full,
output phy_data_full,
output phy_pre_data_a_full,
output [(CK_WIDTH * LP_DDR_CK_WIDTH)-1:0] ddr_clk,
output phy_mc_go,
input phy_write_calib,
input phy_read_calib,
input calib_in_common,
input [5:0] calib_sel,
input [HIGHEST_BANK-1:0] calib_zero_inputs,
input [HIGHEST_BANK-1:0] calib_zero_ctrl,
input [2:0] po_fine_enable,
input [2:0] po_coarse_enable,
input [2:0] po_fine_inc,
input [2:0] po_coarse_inc,
input po_counter_load_en,
input po_counter_read_en,
input [2:0] po_sel_fine_oclk_delay,
input [8:0] po_counter_load_val,
output [8:0] po_counter_read_val,
output [5:0] pi_counter_read_val,
input [HIGHEST_BANK-1:0] pi_rst_dqs_find,
input pi_fine_enable,
input pi_fine_inc,
input pi_counter_load_en,
input [5:0] pi_counter_load_val,
input idelay_ce,
input idelay_inc,
input idelay_ld,
input idle,
output pi_phase_locked,
output pi_phase_locked_all,
output pi_dqs_found,
output pi_dqs_found_all,
output pi_dqs_out_of_range,
// From/to calibration logic/soft PHY
input phy_init_data_sel,
input [nCK_PER_CLK*ROW_WIDTH-1:0] mux_address,
input [nCK_PER_CLK*BANK_WIDTH-1:0] mux_bank,
input [nCK_PER_CLK-1:0] mux_cas_n,
input [CS_WIDTH*nCS_PER_RANK*nCK_PER_CLK-1:0] mux_cs_n,
input [nCK_PER_CLK-1:0] mux_ras_n,
input [1:0] mux_odt,
input [nCK_PER_CLK-1:0] mux_cke,
input [nCK_PER_CLK-1:0] mux_we_n,
input [nCK_PER_CLK-1:0] parity_in,
input [2*nCK_PER_CLK*DQ_WIDTH-1:0] mux_wrdata,
input [2*nCK_PER_CLK*(DQ_WIDTH/8)-1:0] mux_wrdata_mask,
input mux_reset_n,
output [2*nCK_PER_CLK*DQ_WIDTH-1:0] rd_data,
// Memory I/F
output [ROW_WIDTH-1:0] ddr_addr,
output [BANK_WIDTH-1:0] ddr_ba,
output ddr_cas_n,
output [CKE_WIDTH-1:0] ddr_cke,
output [CS_WIDTH*nCS_PER_RANK-1:0] ddr_cs_n,
output [DM_WIDTH-1:0] ddr_dm,
output [ODT_WIDTH-1:0] ddr_odt,
output ddr_parity,
output ddr_ras_n,
output ddr_we_n,
output ddr_reset_n,
inout [DQ_WIDTH-1:0] ddr_dq,
inout [DQS_WIDTH-1:0] ddr_dqs,
inout [DQS_WIDTH-1:0] ddr_dqs_n
,input dbg_pi_counter_read_en
,output ref_dll_lock
,input rst_phaser_ref
,output [11:0] dbg_pi_phase_locked_phy4lanes
,output [11:0] dbg_pi_dqs_found_lanes_phy4lanes
);
function [71:0] generate_bytelanes_ddr_ck;
input [143:0] ck_byte_map;
integer v ;
begin
generate_bytelanes_ddr_ck = 'b0 ;
for (v = 0; v < CK_WIDTH; v = v + 1) begin
if ((CK_BYTE_MAP[((v*8)+4)+:4]) == 2)
generate_bytelanes_ddr_ck[48+(4*v)+1*(CK_BYTE_MAP[(v*8)+:4])] = 1'b1;
else if ((CK_BYTE_MAP[((v*8)+4)+:4]) == 1)
generate_bytelanes_ddr_ck[24+(4*v)+1*(CK_BYTE_MAP[(v*8)+:4])] = 1'b1;
else
generate_bytelanes_ddr_ck[4*v+1*(CK_BYTE_MAP[(v*8)+:4])] = 1'b1;
end
end
endfunction
function [(2*CK_WIDTH*8)-1:0] generate_ddr_ck_map;
input [143:0] ck_byte_map;
integer g;
begin
generate_ddr_ck_map = 'b0 ;
for(g = 0 ; g < CK_WIDTH ; g= g + 1) begin
generate_ddr_ck_map[(g*2*8)+:8] = (ck_byte_map[(g*8)+:4] == 4'd0) ? "A" :
(ck_byte_map[(g*8)+:4] == 4'd1) ? "B" :
(ck_byte_map[(g*8)+:4] == 4'd2) ? "C" : "D" ;
generate_ddr_ck_map[(((g*2)+1)*8)+:8] = (ck_byte_map[((g*8)+4)+:4] == 4'd0) ? "0" :
(ck_byte_map[((g*8)+4)+:4] == 4'd1) ? "1" : "2" ; //each STRING charater takes 0 location
end
end
endfunction
// Enable low power mode for input buffer
localparam IBUF_LOW_PWR
= (IBUF_LPWR_MODE == "OFF") ? "FALSE" :
((IBUF_LPWR_MODE == "ON") ? "TRUE" : "ILLEGAL");
// Ratio of data to strobe
localparam DQ_PER_DQS = DQ_WIDTH / DQS_WIDTH;
// number of data phases per internal clock
localparam PHASE_PER_CLK = 2*nCK_PER_CLK;
// used to determine routing to OUT_FIFO for control/address for 2:1
// vs. 4:1 memory:internal clock ratio modes
localparam PHASE_DIV = 4 / nCK_PER_CLK;
localparam CLK_PERIOD = tCK * nCK_PER_CLK;
// Create an aggregate parameters for data mapping to reduce # of generate
// statements required in remapping code. Need to account for the case
// when the DQ:DQS ratio is not 8:1 - in this case, each DATAx_MAP
// parameter will have fewer than 8 elements used
localparam FULL_DATA_MAP = {DATA17_MAP[12*DQ_PER_DQS-1:0],
DATA16_MAP[12*DQ_PER_DQS-1:0],
DATA15_MAP[12*DQ_PER_DQS-1:0],
DATA14_MAP[12*DQ_PER_DQS-1:0],
DATA13_MAP[12*DQ_PER_DQS-1:0],
DATA12_MAP[12*DQ_PER_DQS-1:0],
DATA11_MAP[12*DQ_PER_DQS-1:0],
DATA10_MAP[12*DQ_PER_DQS-1:0],
DATA9_MAP[12*DQ_PER_DQS-1:0],
DATA8_MAP[12*DQ_PER_DQS-1:0],
DATA7_MAP[12*DQ_PER_DQS-1:0],
DATA6_MAP[12*DQ_PER_DQS-1:0],
DATA5_MAP[12*DQ_PER_DQS-1:0],
DATA4_MAP[12*DQ_PER_DQS-1:0],
DATA3_MAP[12*DQ_PER_DQS-1:0],
DATA2_MAP[12*DQ_PER_DQS-1:0],
DATA1_MAP[12*DQ_PER_DQS-1:0],
DATA0_MAP[12*DQ_PER_DQS-1:0]};
// Same deal, but for data mask mapping
localparam FULL_MASK_MAP = {MASK1_MAP, MASK0_MAP};
localparam TMP_BYTELANES_DDR_CK = generate_bytelanes_ddr_ck(CK_BYTE_MAP) ;
localparam TMP_GENERATE_DDR_CK_MAP = generate_ddr_ck_map(CK_BYTE_MAP) ;
// Temporary parameters to determine which bank is outputting the CK/CK#
// Eventually there will be support for multiple CK/CK# output
//localparam TMP_DDR_CLK_SELECT_BANK = (CK_BYTE_MAP[7:4]);
//// Temporary method to force MC_PHY to generate ODDR associated with
//// CK/CK# output only for a single byte lane in the design. All banks
//// that won't be generating the CK/CK# will have "UNUSED" as their
//// PHY_GENERATE_DDR_CK parameter
//localparam TMP_PHY_0_GENERATE_DDR_CK
// = (TMP_DDR_CLK_SELECT_BANK != 0) ? "UNUSED" :
// ((CK_BYTE_MAP[1:0] == 2'b00) ? "A" :
// ((CK_BYTE_MAP[1:0] == 2'b01) ? "B" :
// ((CK_BYTE_MAP[1:0] == 2'b10) ? "C" : "D")));
//localparam TMP_PHY_1_GENERATE_DDR_CK
// = (TMP_DDR_CLK_SELECT_BANK != 1) ? "UNUSED" :
// ((CK_BYTE_MAP[1:0] == 2'b00) ? "A" :
// ((CK_BYTE_MAP[1:0] == 2'b01) ? "B" :
// ((CK_BYTE_MAP[1:0] == 2'b10) ? "C" : "D")));
//localparam TMP_PHY_2_GENERATE_DDR_CK
// = (TMP_DDR_CLK_SELECT_BANK != 2) ? "UNUSED" :
// ((CK_BYTE_MAP[1:0] == 2'b00) ? "A" :
// ((CK_BYTE_MAP[1:0] == 2'b01) ? "B" :
// ((CK_BYTE_MAP[1:0] == 2'b10) ? "C" : "D")));
// Function to generate MC_PHY parameters PHY_BITLANES_OUTONLYx
// which indicates which bit lanes in data byte lanes are
// output-only bitlanes (e.g. used specifically for data mask outputs)
function [143:0] calc_phy_bitlanes_outonly;
input [215:0] data_mask_in;
integer z;
begin
calc_phy_bitlanes_outonly = 'b0;
// Only enable BITLANES parameters for data masks if, well, if
// the data masks are actually enabled
if (USE_DM_PORT == 1)
for (z = 0; z < DM_WIDTH; z = z + 1)
calc_phy_bitlanes_outonly[48*data_mask_in[(12*z+8)+:3] +
12*data_mask_in[(12*z+4)+:2] +
data_mask_in[12*z+:4]] = 1'b1;
end
endfunction
localparam PHY_BITLANES_OUTONLY = calc_phy_bitlanes_outonly(FULL_MASK_MAP);
localparam PHY_0_BITLANES_OUTONLY = PHY_BITLANES_OUTONLY[47:0];
localparam PHY_1_BITLANES_OUTONLY = PHY_BITLANES_OUTONLY[95:48];
localparam PHY_2_BITLANES_OUTONLY = PHY_BITLANES_OUTONLY[143:96];
// Determine which bank and byte lane generates the RCLK used to clock
// out the auxilliary (ODT, CKE) outputs
localparam CKE_ODT_RCLK_SELECT_BANK_AUX_ON
= (CKE_ODT_BYTE_MAP[7:4] == 4'h0) ? 0 :
((CKE_ODT_BYTE_MAP[7:4] == 4'h1) ? 1 :
((CKE_ODT_BYTE_MAP[7:4] == 4'h2) ? 2 :
((CKE_ODT_BYTE_MAP[7:4] == 4'h3) ? 3 :
((CKE_ODT_BYTE_MAP[7:4] == 4'h4) ? 4 : -1))));
localparam CKE_ODT_RCLK_SELECT_LANE_AUX_ON
= (CKE_ODT_BYTE_MAP[3:0] == 4'h0) ? "A" :
((CKE_ODT_BYTE_MAP[3:0] == 4'h1) ? "B" :
((CKE_ODT_BYTE_MAP[3:0] == 4'h2) ? "C" :
((CKE_ODT_BYTE_MAP[3:0] == 4'h3) ? "D" : "ILLEGAL")));
localparam CKE_ODT_RCLK_SELECT_BANK_AUX_OFF
= (CKE_MAP[11:8] == 4'h0) ? 0 :
((CKE_MAP[11:8] == 4'h1) ? 1 :
((CKE_MAP[11:8] == 4'h2) ? 2 :
((CKE_MAP[11:8] == 4'h3) ? 3 :
((CKE_MAP[11:8] == 4'h4) ? 4 : -1))));
localparam CKE_ODT_RCLK_SELECT_LANE_AUX_OFF
= (CKE_MAP[7:4] == 4'h0) ? "A" :
((CKE_MAP[7:4] == 4'h1) ? "B" :
((CKE_MAP[7:4] == 4'h2) ? "C" :
((CKE_MAP[7:4] == 4'h3) ? "D" : "ILLEGAL")));
localparam CKE_ODT_RCLK_SELECT_BANK = (CKE_ODT_AUX == "TRUE") ? CKE_ODT_RCLK_SELECT_BANK_AUX_ON : CKE_ODT_RCLK_SELECT_BANK_AUX_OFF ;
localparam CKE_ODT_RCLK_SELECT_LANE = (CKE_ODT_AUX == "TRUE") ? CKE_ODT_RCLK_SELECT_LANE_AUX_ON : CKE_ODT_RCLK_SELECT_LANE_AUX_OFF ;
//***************************************************************************
// OCLKDELAYED tap setting calculation:
// Parameters for calculating amount of phase shifting output clock to
// achieve 90 degree offset between DQS and DQ on writes
//***************************************************************************
//90 deg equivalent to 0.25 for MEM_RefClk <= 300 MHz
// and 1.25 for Mem_RefClk > 300 MHz
localparam PO_OCLKDELAY_INV = (((SIM_CAL_OPTION == "NONE") && (tCK > 2500)) || (tCK >= 3333)) ? "FALSE" : "TRUE";
//DIV1: MemRefClk >= 400 MHz, DIV2: 200 <= MemRefClk < 400,
//DIV4: MemRefClk < 200 MHz
localparam PHY_0_A_PI_FREQ_REF_DIV = tCK > 5000 ? "DIV4" :
tCK > 2500 ? "DIV2": "NONE";
localparam FREQ_REF_DIV = (PHY_0_A_PI_FREQ_REF_DIV == "DIV4" ? 4 :
PHY_0_A_PI_FREQ_REF_DIV == "DIV2" ? 2 : 1);
// Intrinsic delay between OCLK and OCLK_DELAYED Phaser Output
localparam real INT_DELAY = 0.4392/FREQ_REF_DIV + 100.0/tCK;
// Whether OCLK_DELAY output comes inverted or not
localparam real HALF_CYCLE_DELAY = 0.5*(PO_OCLKDELAY_INV == "TRUE" ? 1 : 0);
// Phaser-Out Stage3 Tap delay for 90 deg shift.
// Maximum tap delay is FreqRefClk period distributed over 64 taps
// localparam real TAP_DELAY = MC_OCLK_DELAY/64/FREQ_REF_DIV;
localparam real MC_OCLK_DELAY = ((PO_OCLKDELAY_INV == "TRUE" ? 1.25 : 0.25) -
(INT_DELAY + HALF_CYCLE_DELAY))
* 63 * FREQ_REF_DIV;
//localparam integer PHY_0_A_PO_OCLK_DELAY = MC_OCLK_DELAY;
localparam integer PHY_0_A_PO_OCLK_DELAY_HW
= (tCK > 2273) ? 34 :
(tCK > 2000) ? 33 :
(tCK > 1724) ? 32 :
(tCK > 1515) ? 31 :
(tCK > 1315) ? 30 :
(tCK > 1136) ? 29 :
(tCK > 1021) ? 28 : 27;
// Note that simulation requires a different value than in H/W because of the
// difference in the way delays are modeled
localparam integer PHY_0_A_PO_OCLK_DELAY = (SIM_CAL_OPTION == "NONE") ?
((tCK > 2500) ? 8 :
(DRAM_TYPE == "DDR3") ? PHY_0_A_PO_OCLK_DELAY_HW : 30) :
MC_OCLK_DELAY;
// Initial DQ IDELAY value
localparam PHY_0_A_IDELAYE2_IDELAY_VALUE = (SIM_CAL_OPTION != "FAST_CAL") ? 0 :
(tCK < 1000) ? 0 :
(tCK < 1330) ? 0 :
(tCK < 2300) ? 0 :
(tCK < 2500) ? 2 : 0;
//localparam PHY_0_A_IDELAYE2_IDELAY_VALUE = 0;
// Aux_out parameters RD_CMD_OFFSET = CL+2? and WR_CMD_OFFSET = CWL+3?
localparam PHY_0_RD_CMD_OFFSET_0 = 10;
localparam PHY_0_RD_CMD_OFFSET_1 = 10;
localparam PHY_0_RD_CMD_OFFSET_2 = 10;
localparam PHY_0_RD_CMD_OFFSET_3 = 10;
// 4:1 and 2:1 have WR_CMD_OFFSET values for ODT timing
localparam PHY_0_WR_CMD_OFFSET_0 = (nCK_PER_CLK == 4) ? 8 : 4;
localparam PHY_0_WR_CMD_OFFSET_1 = (nCK_PER_CLK == 4) ? 8 : 4;
localparam PHY_0_WR_CMD_OFFSET_2 = (nCK_PER_CLK == 4) ? 8 : 4;
localparam PHY_0_WR_CMD_OFFSET_3 = (nCK_PER_CLK == 4) ? 8 : 4;
// 4:1 and 2:1 have different values
localparam PHY_0_WR_DURATION_0 = 7;
localparam PHY_0_WR_DURATION_1 = 7;
localparam PHY_0_WR_DURATION_2 = 7;
localparam PHY_0_WR_DURATION_3 = 7;
// Aux_out parameters for toggle mode (CKE)
localparam CWL_M = (REG_CTRL == "ON") ? CWL + 1 : CWL;
localparam PHY_0_CMD_OFFSET = (nCK_PER_CLK == 4) ? (CWL_M % 2) ? 8 : 9 :
(CWL < 7) ?
4 + ((CWL_M % 2) ? 0 : 1) :
5 + ((CWL_M % 2) ? 0 : 1);
// temporary parameter to enable/disable PHY PC counters. In both 4:1 and
// 2:1 cases, this should be disabled. For now, enable for 4:1 mode to
// avoid making too many changes at once.
localparam PHY_COUNT_EN = (nCK_PER_CLK == 4) ? "TRUE" : "FALSE";
wire [((HIGHEST_LANE+3)/4)*4-1:0] aux_out;
wire [HIGHEST_LANE-1:0] mem_dqs_in;
wire [HIGHEST_LANE-1:0] mem_dqs_out;
wire [HIGHEST_LANE-1:0] mem_dqs_ts;
wire [HIGHEST_LANE*10-1:0] mem_dq_in;
wire [HIGHEST_LANE*12-1:0] mem_dq_out;
wire [HIGHEST_LANE*12-1:0] mem_dq_ts;
wire [DQ_WIDTH-1:0] in_dq;
wire [DQS_WIDTH-1:0] in_dqs;
wire [ROW_WIDTH-1:0] out_addr;
wire [BANK_WIDTH-1:0] out_ba;
wire out_cas_n;
wire [CS_WIDTH*nCS_PER_RANK-1:0] out_cs_n;
wire [DM_WIDTH-1:0] out_dm;
wire [ODT_WIDTH -1:0] out_odt;
wire [CKE_WIDTH -1 :0] out_cke ;
wire [DQ_WIDTH-1:0] out_dq;
wire [DQS_WIDTH-1:0] out_dqs;
wire out_parity;
wire out_ras_n;
wire out_we_n;
wire [HIGHEST_LANE*80-1:0] phy_din;
wire [HIGHEST_LANE*80-1:0] phy_dout;
wire phy_rd_en;
wire [DM_WIDTH-1:0] ts_dm;
wire [DQ_WIDTH-1:0] ts_dq;
wire [DQS_WIDTH-1:0] ts_dqs;
reg [31:0] phy_ctl_wd_i1;
reg [31:0] phy_ctl_wd_i2;
reg phy_ctl_wr_i1;
reg phy_ctl_wr_i2;
reg [5:0] data_offset_1_i1;
reg [5:0] data_offset_1_i2;
reg [5:0] data_offset_2_i1;
reg [5:0] data_offset_2_i2;
wire [31:0] phy_ctl_wd_temp;
wire phy_ctl_wr_temp;
wire [5:0] data_offset_1_temp;
wire [5:0] data_offset_2_temp;
wire [5:0] data_offset_1_of;
wire [5:0] data_offset_2_of;
wire [31:0] phy_ctl_wd_of;
(* keep = "true", max_fanout = 3 *) wire phy_ctl_wr_of /* synthesis syn_maxfan = 1 */;
wire [3:0] phy_ctl_full_temp;
wire data_io_idle_pwrdwn;
// Always read from input data FIFOs when not empty
assign phy_rd_en = !if_empty;
// IDELAYE2 initial value
assign idelaye2_init_val = PHY_0_A_IDELAYE2_IDELAY_VALUE;
assign oclkdelay_init_val = PHY_0_A_PO_OCLK_DELAY;
// Idle powerdown when there are no pending reads in the MC
assign data_io_idle_pwrdwn = DATA_IO_IDLE_PWRDWN == "ON" ? idle : 1'b0;
//***************************************************************************
// Auxiliary output steering
//***************************************************************************
// For a 4 rank I/F the aux_out[3:0] from the addr/ctl bank will be
// mapped to ddr_odt and the aux_out[7:4] from one of the data banks
// will map to ddr_cke. For I/Fs less than 4 the aux_out[3:0] from the
// addr/ctl bank would bank would map to both ddr_odt and ddr_cke.
generate
if(CKE_ODT_AUX == "TRUE")begin:cke_thru_auxpins
if (CKE_WIDTH == 1) begin : gen_cke
// Explicitly instantiate OBUF to ensure that these are present
// in the netlist. Typically this is not required since NGDBUILD
// at the top-level knows to infer an I/O/IOBUF and therefore a
// top-level LOC constraint can be attached to that pin. This does
// not work when a hierarchical flow is used and the LOC is applied
// at the individual core-level UCF
OBUF u_cke_obuf
(
.I (aux_out[4*CKE_ODT_RCLK_SELECT_BANK]),
.O (ddr_cke)
);
end else begin: gen_2rank_cke
OBUF u_cke0_obuf
(
.I (aux_out[4*CKE_ODT_RCLK_SELECT_BANK]),
.O (ddr_cke[0])
);
OBUF u_cke1_obuf
(
.I (aux_out[4*CKE_ODT_RCLK_SELECT_BANK+2]),
.O (ddr_cke[1])
);
end
end
endgenerate
generate
if(CKE_ODT_AUX == "TRUE")begin:odt_thru_auxpins
if (USE_ODT_PORT == 1) begin : gen_use_odt
// Explicitly instantiate OBUF to ensure that these are present
// in the netlist. Typically this is not required since NGDBUILD
// at the top-level knows to infer an I/O/IOBUF and therefore a
// top-level LOC constraint can be attached to that pin. This does
// not work when a hierarchical flow is used and the LOC is applied
// at the individual core-level UCF
OBUF u_odt_obuf
(
.I (aux_out[4*CKE_ODT_RCLK_SELECT_BANK+1]),
.O (ddr_odt[0])
);
if (ODT_WIDTH == 2 && RANKS == 1) begin: gen_2port_odt
OBUF u_odt1_obuf
(
.I (aux_out[4*CKE_ODT_RCLK_SELECT_BANK+2]),
.O (ddr_odt[1])
);
end else if (ODT_WIDTH == 2 && RANKS == 2) begin: gen_2rank_odt
OBUF u_odt1_obuf
(
.I (aux_out[4*CKE_ODT_RCLK_SELECT_BANK+3]),
.O (ddr_odt[1])
);
end else if (ODT_WIDTH == 3 && RANKS == 1) begin: gen_3port_odt
OBUF u_odt1_obuf
(
.I (aux_out[4*CKE_ODT_RCLK_SELECT_BANK+2]),
.O (ddr_odt[1])
);
OBUF u_odt2_obuf
(
.I (aux_out[4*CKE_ODT_RCLK_SELECT_BANK+3]),
.O (ddr_odt[2])
);
end
end else begin
assign ddr_odt = 'b0;
end
end
endgenerate
//***************************************************************************
// Read data bit steering
//***************************************************************************
// Transpose elements of rd_data_map to form final read data output:
// phy_din elements are grouped according to "physical bit" - e.g.
// for nCK_PER_CLK = 4, there are 8 data phases transfered per physical
// bit per clock cycle:
// = {dq0_fall3, dq0_rise3, dq0_fall2, dq0_rise2,
// dq0_fall1, dq0_rise1, dq0_fall0, dq0_rise0}
// whereas rd_data is are grouped according to "phase" - e.g.
// = {dq7_rise0, dq6_rise0, dq5_rise0, dq4_rise0,
// dq3_rise0, dq2_rise0, dq1_rise0, dq0_rise0}
// therefore rd_data is formed by transposing phy_din - e.g.
// for nCK_PER_CLK = 4, and DQ_WIDTH = 16, and assuming MC_PHY
// bit_lane[0] maps to DQ[0], and bit_lane[1] maps to DQ[1], then
// the assignments for bits of rd_data corresponding to DQ[1:0]
// would be:
// {rd_data[112], rd_data[96], rd_data[80], rd_data[64],
// rd_data[48], rd_data[32], rd_data[16], rd_data[0]} = phy_din[7:0]
// {rd_data[113], rd_data[97], rd_data[81], rd_data[65],
// rd_data[49], rd_data[33], rd_data[17], rd_data[1]} = phy_din[15:8]
generate
genvar i, j;
for (i = 0; i < DQ_WIDTH; i = i + 1) begin: gen_loop_rd_data_1
for (j = 0; j < PHASE_PER_CLK; j = j + 1) begin: gen_loop_rd_data_2
assign rd_data[DQ_WIDTH*j + i]
= phy_din[(320*FULL_DATA_MAP[(12*i+8)+:3]+
80*FULL_DATA_MAP[(12*i+4)+:2] +
8*FULL_DATA_MAP[12*i+:4]) + j];
end
end
endgenerate
//***************************************************************************
// Control/address
//***************************************************************************
assign out_cas_n
= mem_dq_out[48*CAS_MAP[10:8] + 12*CAS_MAP[5:4] + CAS_MAP[3:0]];
generate
// if signal placed on bit lanes [0-9]
if (CAS_MAP[3:0] < 4'hA) begin: gen_cas_lt10
// Determine routing based on clock ratio mode. If running in 4:1
// mode, then all four bits from logic are used. If 2:1 mode, only
// 2-bits are provided by logic, and each bit is repeated 2x to form
// 4-bit input to IN_FIFO, e.g.
// 4:1 mode: phy_dout[] = {in[3], in[2], in[1], in[0]}
// 2:1 mode: phy_dout[] = {in[1], in[1], in[0], in[0]}
assign phy_dout[(320*CAS_MAP[10:8] + 80*CAS_MAP[5:4] +
8*CAS_MAP[3:0])+:4]
= {mux_cas_n[3/PHASE_DIV], mux_cas_n[2/PHASE_DIV],
mux_cas_n[1/PHASE_DIV], mux_cas_n[0]};
end else begin: gen_cas_ge10
// If signal is placed in bit lane [10] or [11], route to upper
// nibble of phy_dout lane [5] or [6] respectively (in this case
// phy_dout lane [5, 6] are multiplexed to take input for two
// different SDR signals - this is how bits[10,11] need to be
// provided to the OUT_FIFO
assign phy_dout[(320*CAS_MAP[10:8] + 80*CAS_MAP[5:4] +
8*(CAS_MAP[3:0]-5) + 4)+:4]
= {mux_cas_n[3/PHASE_DIV], mux_cas_n[2/PHASE_DIV],
mux_cas_n[1/PHASE_DIV], mux_cas_n[0]};
end
endgenerate
assign out_ras_n
= mem_dq_out[48*RAS_MAP[10:8] + 12*RAS_MAP[5:4] + RAS_MAP[3:0]];
generate
if (RAS_MAP[3:0] < 4'hA) begin: gen_ras_lt10
assign phy_dout[(320*RAS_MAP[10:8] + 80*RAS_MAP[5:4] +
8*RAS_MAP[3:0])+:4]
= {mux_ras_n[3/PHASE_DIV], mux_ras_n[2/PHASE_DIV],
mux_ras_n[1/PHASE_DIV], mux_ras_n[0]};
end else begin: gen_ras_ge10
assign phy_dout[(320*RAS_MAP[10:8] + 80*RAS_MAP[5:4] +
8*(RAS_MAP[3:0]-5) + 4)+:4]
= {mux_ras_n[3/PHASE_DIV], mux_ras_n[2/PHASE_DIV],
mux_ras_n[1/PHASE_DIV], mux_ras_n[0]};
end
endgenerate
assign out_we_n
= mem_dq_out[48*WE_MAP[10:8] + 12*WE_MAP[5:4] + WE_MAP[3:0]];
generate
if (WE_MAP[3:0] < 4'hA) begin: gen_we_lt10
assign phy_dout[(320*WE_MAP[10:8] + 80*WE_MAP[5:4] +
8*WE_MAP[3:0])+:4]
= {mux_we_n[3/PHASE_DIV], mux_we_n[2/PHASE_DIV],
mux_we_n[1/PHASE_DIV], mux_we_n[0]};
end else begin: gen_we_ge10
assign phy_dout[(320*WE_MAP[10:8] + 80*WE_MAP[5:4] +
8*(WE_MAP[3:0]-5) + 4)+:4]
= {mux_we_n[3/PHASE_DIV], mux_we_n[2/PHASE_DIV],
mux_we_n[1/PHASE_DIV], mux_we_n[0]};
end
endgenerate
generate
if (REG_CTRL == "ON") begin: gen_parity_out
// Generate addr/ctrl parity output only for DDR3 and DDR2 registered DIMMs
assign out_parity
= mem_dq_out[48*PARITY_MAP[10:8] + 12*PARITY_MAP[5:4] +
PARITY_MAP[3:0]];
if (PARITY_MAP[3:0] < 4'hA) begin: gen_lt10
assign phy_dout[(320*PARITY_MAP[10:8] + 80*PARITY_MAP[5:4] +
8*PARITY_MAP[3:0])+:4]
= {parity_in[3/PHASE_DIV], parity_in[2/PHASE_DIV],
parity_in[1/PHASE_DIV], parity_in[0]};
end else begin: gen_ge10
assign phy_dout[(320*PARITY_MAP[10:8] + 80*PARITY_MAP[5:4] +
8*(PARITY_MAP[3:0]-5) + 4)+:4]
= {parity_in[3/PHASE_DIV], parity_in[2/PHASE_DIV],
parity_in[1/PHASE_DIV], parity_in[0]};
end
end
endgenerate
//*****************************************************************
generate
genvar m, n,x;
//*****************************************************************
// Control/address (multi-bit) buses
//*****************************************************************
// Row/Column address
for (m = 0; m < ROW_WIDTH; m = m + 1) begin: gen_addr_out
assign out_addr[m]
= mem_dq_out[48*ADDR_MAP[(12*m+8)+:3] +
12*ADDR_MAP[(12*m+4)+:2] +
ADDR_MAP[12*m+:4]];
if (ADDR_MAP[12*m+:4] < 4'hA) begin: gen_lt10
// For multi-bit buses, we also have to deal with transposition
// when going from the logic-side control bus to phy_dout
for (n = 0; n < 4; n = n + 1) begin: loop_xpose
assign phy_dout[320*ADDR_MAP[(12*m+8)+:3] +
80*ADDR_MAP[(12*m+4)+:2] +
8*ADDR_MAP[12*m+:4] + n]
= mux_address[ROW_WIDTH*(n/PHASE_DIV) + m];
end
end else begin: gen_ge10
for (n = 0; n < 4; n = n + 1) begin: loop_xpose
assign phy_dout[320*ADDR_MAP[(12*m+8)+:3] +
80*ADDR_MAP[(12*m+4)+:2] +
8*(ADDR_MAP[12*m+:4]-5) + 4 + n]
= mux_address[ROW_WIDTH*(n/PHASE_DIV) + m];
end
end
end
// Bank address
for (m = 0; m < BANK_WIDTH; m = m + 1) begin: gen_ba_out
assign out_ba[m]
= mem_dq_out[48*BANK_MAP[(12*m+8)+:3] +
12*BANK_MAP[(12*m+4)+:2] +
BANK_MAP[12*m+:4]];
if (BANK_MAP[12*m+:4] < 4'hA) begin: gen_lt10
for (n = 0; n < 4; n = n + 1) begin: loop_xpose
assign phy_dout[320*BANK_MAP[(12*m+8)+:3] +
80*BANK_MAP[(12*m+4)+:2] +
8*BANK_MAP[12*m+:4] + n]
= mux_bank[BANK_WIDTH*(n/PHASE_DIV) + m];
end
end else begin: gen_ge10
for (n = 0; n < 4; n = n + 1) begin: loop_xpose
assign phy_dout[320*BANK_MAP[(12*m+8)+:3] +
80*BANK_MAP[(12*m+4)+:2] +
8*(BANK_MAP[12*m+:4]-5) + 4 + n]
= mux_bank[BANK_WIDTH*(n/PHASE_DIV) + m];
end
end
end
// Chip select
if (USE_CS_PORT == 1) begin: gen_cs_n_out
for (m = 0; m < CS_WIDTH*nCS_PER_RANK; m = m + 1) begin: gen_cs_out
assign out_cs_n[m]
= mem_dq_out[48*CS_MAP[(12*m+8)+:3] +
12*CS_MAP[(12*m+4)+:2] +
CS_MAP[12*m+:4]];
if (CS_MAP[12*m+:4] < 4'hA) begin: gen_lt10
for (n = 0; n < 4; n = n + 1) begin: loop_xpose
assign phy_dout[320*CS_MAP[(12*m+8)+:3] +
80*CS_MAP[(12*m+4)+:2] +
8*CS_MAP[12*m+:4] + n]
= mux_cs_n[CS_WIDTH*nCS_PER_RANK*(n/PHASE_DIV) + m];
end
end else begin: gen_ge10
for (n = 0; n < 4; n = n + 1) begin: loop_xpose
assign phy_dout[320*CS_MAP[(12*m+8)+:3] +
80*CS_MAP[(12*m+4)+:2] +
8*(CS_MAP[12*m+:4]-5) + 4 + n]
= mux_cs_n[CS_WIDTH*nCS_PER_RANK*(n/PHASE_DIV) + m];
end
end
end
end
if(CKE_ODT_AUX == "FALSE") begin
// ODT_ports
wire [ODT_WIDTH*nCK_PER_CLK -1 :0] mux_odt_remap ;
if(RANKS == 1) begin
for(x =0 ; x < nCK_PER_CLK ; x = x+1) begin
assign mux_odt_remap[(x*ODT_WIDTH)+:ODT_WIDTH] = {ODT_WIDTH{mux_odt[0]}} ;
end
end else begin
for(x =0 ; x < 2*nCK_PER_CLK ; x = x+2) begin
assign mux_odt_remap[(x*ODT_WIDTH/RANKS)+:ODT_WIDTH/RANKS] = {ODT_WIDTH/RANKS{mux_odt[0]}} ;
assign mux_odt_remap[((x*ODT_WIDTH/RANKS)+(ODT_WIDTH/RANKS))+:ODT_WIDTH/RANKS] = {ODT_WIDTH/RANKS{mux_odt[1]}} ;
end
end
if (USE_ODT_PORT == 1) begin: gen_odt_out
for (m = 0; m < ODT_WIDTH; m = m + 1) begin: gen_odt_out_1
assign out_odt[m]
= mem_dq_out[48*ODT_MAP[(12*m+8)+:3] +
12*ODT_MAP[(12*m+4)+:2] +
ODT_MAP[12*m+:4]];
if (ODT_MAP[12*m+:4] < 4'hA) begin: gen_lt10
for (n = 0; n < 4; n = n + 1) begin: loop_xpose
assign phy_dout[320*ODT_MAP[(12*m+8)+:3] +
80*ODT_MAP[(12*m+4)+:2] +
8*ODT_MAP[12*m+:4] + n]
= mux_odt_remap[ODT_WIDTH*(n/PHASE_DIV) + m];
end
end else begin: gen_ge10
for (n = 0; n < 4; n = n + 1) begin: loop_xpose
assign phy_dout[320*ODT_MAP[(12*m+8)+:3] +
80*ODT_MAP[(12*m+4)+:2] +
8*(ODT_MAP[12*m+:4]-5) + 4 + n]
= mux_odt_remap[ODT_WIDTH*(n/PHASE_DIV) + m];
end
end
end
end
wire [CKE_WIDTH*nCK_PER_CLK -1:0] mux_cke_remap ;
for(x = 0 ; x < nCK_PER_CLK ; x = x +1) begin
assign mux_cke_remap[(x*CKE_WIDTH)+:CKE_WIDTH] = {CKE_WIDTH{mux_cke[x]}} ;
end
for (m = 0; m < CKE_WIDTH; m = m + 1) begin: gen_cke_out
assign out_cke[m]
= mem_dq_out[48*CKE_MAP[(12*m+8)+:3] +
12*CKE_MAP[(12*m+4)+:2] +
CKE_MAP[12*m+:4]];
if (CKE_MAP[12*m+:4] < 4'hA) begin: gen_lt10
for (n = 0; n < 4; n = n + 1) begin: loop_xpose
assign phy_dout[320*CKE_MAP[(12*m+8)+:3] +
80*CKE_MAP[(12*m+4)+:2] +
8*CKE_MAP[12*m+:4] + n]
= mux_cke_remap[CKE_WIDTH*(n/PHASE_DIV) + m];
end
end else begin: gen_ge10
for (n = 0; n < 4; n = n + 1) begin: loop_xpose
assign phy_dout[320*CKE_MAP[(12*m+8)+:3] +
80*CKE_MAP[(12*m+4)+:2] +
8*(CKE_MAP[12*m+:4]-5) + 4 + n]
= mux_cke_remap[CKE_WIDTH*(n/PHASE_DIV) + m];
end
end
end
end
//*****************************************************************
// Data mask
//*****************************************************************
if (USE_DM_PORT == 1) begin: gen_dm_out
for (m = 0; m < DM_WIDTH; m = m + 1) begin: gen_dm_out
assign out_dm[m]
= mem_dq_out[48*FULL_MASK_MAP[(12*m+8)+:3] +
12*FULL_MASK_MAP[(12*m+4)+:2] +
FULL_MASK_MAP[12*m+:4]];
assign ts_dm[m]
= mem_dq_ts[48*FULL_MASK_MAP[(12*m+8)+:3] +
12*FULL_MASK_MAP[(12*m+4)+:2] +
FULL_MASK_MAP[12*m+:4]];
for (n = 0; n < PHASE_PER_CLK; n = n + 1) begin: loop_xpose
assign phy_dout[320*FULL_MASK_MAP[(12*m+8)+:3] +
80*FULL_MASK_MAP[(12*m+4)+:2] +
8*FULL_MASK_MAP[12*m+:4] + n]
= mux_wrdata_mask[DM_WIDTH*n + m];
end
end
end
//*****************************************************************
// Input and output DQ
//*****************************************************************
for (m = 0; m < DQ_WIDTH; m = m + 1) begin: gen_dq_inout
// to MC_PHY
assign mem_dq_in[40*FULL_DATA_MAP[(12*m+8)+:3] +
10*FULL_DATA_MAP[(12*m+4)+:2] +
FULL_DATA_MAP[12*m+:4]]
= in_dq[m];
// to I/O buffers
assign out_dq[m]
= mem_dq_out[48*FULL_DATA_MAP[(12*m+8)+:3] +
12*FULL_DATA_MAP[(12*m+4)+:2] +
FULL_DATA_MAP[12*m+:4]];
assign ts_dq[m]
= mem_dq_ts[48*FULL_DATA_MAP[(12*m+8)+:3] +
12*FULL_DATA_MAP[(12*m+4)+:2] +
FULL_DATA_MAP[12*m+:4]];
for (n = 0; n < PHASE_PER_CLK; n = n + 1) begin: loop_xpose
assign phy_dout[320*FULL_DATA_MAP[(12*m+8)+:3] +
80*FULL_DATA_MAP[(12*m+4)+:2] +
8*FULL_DATA_MAP[12*m+:4] + n]
= mux_wrdata[DQ_WIDTH*n + m];
end
end
//*****************************************************************
// Input and output DQS
//*****************************************************************
for (m = 0; m < DQS_WIDTH; m = m + 1) begin: gen_dqs_inout
// to MC_PHY
assign mem_dqs_in[4*DQS_BYTE_MAP[(8*m+4)+:3] + DQS_BYTE_MAP[(8*m)+:2]]
= in_dqs[m];
// to I/O buffers
assign out_dqs[m]
= mem_dqs_out[4*DQS_BYTE_MAP[(8*m+4)+:3] + DQS_BYTE_MAP[(8*m)+:2]];
assign ts_dqs[m]
= mem_dqs_ts[4*DQS_BYTE_MAP[(8*m+4)+:3] + DQS_BYTE_MAP[(8*m)+:2]];
end
endgenerate
//***************************************************************************
// Memory I/F output and I/O buffer instantiation
//***************************************************************************
// Note on instantiation - generally at the minimum, it's not required to
// instantiate the output buffers - they can be inferred by the synthesis
// tool, and there aren't any attributes that need to be associated with
// them. Consider as a future option to take out the OBUF instantiations
OBUF u_cas_n_obuf
(
.I (out_cas_n),
.O (ddr_cas_n)
);
OBUF u_ras_n_obuf
(
.I (out_ras_n),
.O (ddr_ras_n)
);
OBUF u_we_n_obuf
(
.I (out_we_n),
.O (ddr_we_n)
);
generate
genvar p;
for (p = 0; p < ROW_WIDTH; p = p + 1) begin: gen_addr_obuf
OBUF u_addr_obuf
(
.I (out_addr[p]),
.O (ddr_addr[p])
);
end
for (p = 0; p < BANK_WIDTH; p = p + 1) begin: gen_bank_obuf
OBUF u_bank_obuf
(
.I (out_ba[p]),
.O (ddr_ba[p])
);
end
if (USE_CS_PORT == 1) begin: gen_cs_n_obuf
for (p = 0; p < CS_WIDTH*nCS_PER_RANK; p = p + 1) begin: gen_cs_obuf
OBUF u_cs_n_obuf
(
.I (out_cs_n[p]),
.O (ddr_cs_n[p])
);
end
end
if(CKE_ODT_AUX == "FALSE")begin:cke_odt_thru_outfifo
if (USE_ODT_PORT== 1) begin: gen_odt_obuf
for (p = 0; p < ODT_WIDTH; p = p + 1) begin: gen_odt_obuf
OBUF u_cs_n_obuf
(
.I (out_odt[p]),
.O (ddr_odt[p])
);
end
end
for (p = 0; p < CKE_WIDTH; p = p + 1) begin: gen_cke_obuf
OBUF u_cs_n_obuf
(
.I (out_cke[p]),
.O (ddr_cke[p])
);
end
end
if (REG_CTRL == "ON") begin: gen_parity_obuf
// Generate addr/ctrl parity output only for DDR3 registered DIMMs
OBUF u_parity_obuf
(
.I (out_parity),
.O (ddr_parity)
);
end else begin: gen_parity_tieoff
assign ddr_parity = 1'b0;
end
if ((DRAM_TYPE == "DDR3") || (REG_CTRL == "ON")) begin: gen_reset_obuf
// Generate reset output only for DDR3 and DDR2 RDIMMs
OBUF u_reset_obuf
(
.I (mux_reset_n),
.O (ddr_reset_n)
);
end else begin: gen_reset_tieoff
assign ddr_reset_n = 1'b1;
end
if (USE_DM_PORT == 1) begin: gen_dm_obuf
for (p = 0; p < DM_WIDTH; p = p + 1) begin: loop_dm
OBUFT u_dm_obuf
(
.I (out_dm[p]),
.T (ts_dm[p]),
.O (ddr_dm[p])
);
end
end else begin: gen_dm_tieoff
assign ddr_dm = 'b0;
end
if (DATA_IO_PRIM_TYPE == "HP_LP") begin: gen_dq_iobuf_HP
for (p = 0; p < DQ_WIDTH; p = p + 1) begin: gen_dq_iobuf
IOBUF_DCIEN #
(
.IBUF_LOW_PWR (IBUF_LOW_PWR)
)
u_iobuf_dq
(
.DCITERMDISABLE (data_io_idle_pwrdwn),
.IBUFDISABLE (data_io_idle_pwrdwn),
.I (out_dq[p]),
.T (ts_dq[p]),
.O (in_dq[p]),
.IO (ddr_dq[p])
);
end
end else if (DATA_IO_PRIM_TYPE == "HR_LP") begin: gen_dq_iobuf_HR
for (p = 0; p < DQ_WIDTH; p = p + 1) begin: gen_dq_iobuf
IOBUF_INTERMDISABLE #
(
.IBUF_LOW_PWR (IBUF_LOW_PWR)
)
u_iobuf_dq
(
.INTERMDISABLE (data_io_idle_pwrdwn),
.IBUFDISABLE (data_io_idle_pwrdwn),
.I (out_dq[p]),
.T (ts_dq[p]),
.O (in_dq[p]),
.IO (ddr_dq[p])
);
end
end else begin: gen_dq_iobuf_default
for (p = 0; p < DQ_WIDTH; p = p + 1) begin: gen_dq_iobuf
IOBUF #
(
.IBUF_LOW_PWR (IBUF_LOW_PWR)
)
u_iobuf_dq
(
.I (out_dq[p]),
.T (ts_dq[p]),
.O (in_dq[p]),
.IO (ddr_dq[p])
);
end
end
if (DATA_IO_PRIM_TYPE == "HP_LP") begin: gen_dqs_iobuf_HP
for (p = 0; p < DQS_WIDTH; p = p + 1) begin: gen_dqs_iobuf
if ((DRAM_TYPE == "DDR2") &&
(DDR2_DQSN_ENABLE != "YES")) begin: gen_ddr2_dqs_se
IOBUF_DCIEN #
(
.IBUF_LOW_PWR (IBUF_LOW_PWR)
)
u_iobuf_dqs
(
.DCITERMDISABLE (data_io_idle_pwrdwn),
.IBUFDISABLE (data_io_idle_pwrdwn),
.I (out_dqs[p]),
.T (ts_dqs[p]),
.O (in_dqs[p]),
.IO (ddr_dqs[p])
);
assign ddr_dqs_n[p] = 1'b0;
end else begin: gen_dqs_diff
IOBUFDS_DCIEN #
(
.IBUF_LOW_PWR (IBUF_LOW_PWR),
.DQS_BIAS ("TRUE")
)
u_iobuf_dqs
(
.DCITERMDISABLE (data_io_idle_pwrdwn),
.IBUFDISABLE (data_io_idle_pwrdwn),
.I (out_dqs[p]),
.T (ts_dqs[p]),
.O (in_dqs[p]),
.IO (ddr_dqs[p]),
.IOB (ddr_dqs_n[p])
);
end
end
end else if (DATA_IO_PRIM_TYPE == "HR_LP") begin: gen_dqs_iobuf_HR
for (p = 0; p < DQS_WIDTH; p = p + 1) begin: gen_dqs_iobuf
if ((DRAM_TYPE == "DDR2") &&
(DDR2_DQSN_ENABLE != "YES")) begin: gen_ddr2_dqs_se
IOBUF_INTERMDISABLE #
(
.IBUF_LOW_PWR (IBUF_LOW_PWR)
)
u_iobuf_dqs
(
.INTERMDISABLE (data_io_idle_pwrdwn),
.IBUFDISABLE (data_io_idle_pwrdwn),
.I (out_dqs[p]),
.T (ts_dqs[p]),
.O (in_dqs[p]),
.IO (ddr_dqs[p])
);
assign ddr_dqs_n[p] = 1'b0;
end else begin: gen_dqs_diff
IOBUFDS_INTERMDISABLE #
(
.IBUF_LOW_PWR (IBUF_LOW_PWR),
.DQS_BIAS ("TRUE")
)
u_iobuf_dqs
(
.INTERMDISABLE (data_io_idle_pwrdwn),
.IBUFDISABLE (data_io_idle_pwrdwn),
.I (out_dqs[p]),
.T (ts_dqs[p]),
.O (in_dqs[p]),
.IO (ddr_dqs[p]),
.IOB (ddr_dqs_n[p])
);
end
end
end else begin: gen_dqs_iobuf_default
for (p = 0; p < DQS_WIDTH; p = p + 1) begin: gen_dqs_iobuf
if ((DRAM_TYPE == "DDR2") &&
(DDR2_DQSN_ENABLE != "YES")) begin: gen_ddr2_dqs_se
IOBUF #
(
.IBUF_LOW_PWR (IBUF_LOW_PWR)
)
u_iobuf_dqs
(
.I (out_dqs[p]),
.T (ts_dqs[p]),
.O (in_dqs[p]),
.IO (ddr_dqs[p])
);
assign ddr_dqs_n[p] = 1'b0;
end else begin: gen_dqs_diff
IOBUFDS #
(
.IBUF_LOW_PWR (IBUF_LOW_PWR),
.DQS_BIAS ("TRUE")
)
u_iobuf_dqs
(
.I (out_dqs[p]),
.T (ts_dqs[p]),
.O (in_dqs[p]),
.IO (ddr_dqs[p]),
.IOB (ddr_dqs_n[p])
);
end
end
end
endgenerate
always @(posedge clk) begin
phy_ctl_wd_i1 <= #TCQ phy_ctl_wd;
phy_ctl_wr_i1 <= #TCQ phy_ctl_wr;
phy_ctl_wd_i2 <= #TCQ phy_ctl_wd_i1;
phy_ctl_wr_i2 <= #TCQ phy_ctl_wr_i1;
data_offset_1_i1 <= #TCQ data_offset_1;
data_offset_1_i2 <= #TCQ data_offset_1_i1;
data_offset_2_i1 <= #TCQ data_offset_2;
data_offset_2_i2 <= #TCQ data_offset_2_i1;
end
// 2 cycles of command delay needed for 4;1 mode. 2:1 mode does not need it.
// 2:1 mode the command goes through pre fifo
assign phy_ctl_wd_temp = (nCK_PER_CLK == 4) ? phy_ctl_wd_i2 : phy_ctl_wd_of;
assign phy_ctl_wr_temp = (nCK_PER_CLK == 4) ? phy_ctl_wr_i2 : phy_ctl_wr_of;
assign data_offset_1_temp = (nCK_PER_CLK == 4) ? data_offset_1_i2 : data_offset_1_of;
assign data_offset_2_temp = (nCK_PER_CLK == 4) ? data_offset_2_i2 : data_offset_2_of;
generate
begin
mig_7series_v1_9_ddr_of_pre_fifo #
(
.TCQ (25),
.DEPTH (8),
.WIDTH (32)
)
phy_ctl_pre_fifo_0
(
.clk (clk),
.rst (rst),
.full_in (phy_ctl_full_temp[1]),
.wr_en_in (phy_ctl_wr),
.d_in (phy_ctl_wd),
.wr_en_out (phy_ctl_wr_of),
.d_out (phy_ctl_wd_of)
);
mig_7series_v1_9_ddr_of_pre_fifo #
(
.TCQ (25),
.DEPTH (8),
.WIDTH (6)
)
phy_ctl_pre_fifo_1
(
.clk (clk),
.rst (rst),
.full_in (phy_ctl_full_temp[2]),
.wr_en_in (phy_ctl_wr),
.d_in (data_offset_1),
.wr_en_out (),
.d_out (data_offset_1_of)
);
mig_7series_v1_9_ddr_of_pre_fifo #
(
.TCQ (25),
.DEPTH (8),
.WIDTH (6)
)
phy_ctl_pre_fifo_2
(
.clk (clk),
.rst (rst),
.full_in (phy_ctl_full_temp[3]),
.wr_en_in (phy_ctl_wr),
.d_in (data_offset_2),
.wr_en_out (),
.d_out (data_offset_2_of)
);
end
endgenerate
//***************************************************************************
// Hard PHY instantiation
//***************************************************************************
assign phy_ctl_full = phy_ctl_full_temp[0];
mig_7series_v1_9_ddr_mc_phy #
(
.BYTE_LANES_B0 (BYTE_LANES_B0),
.BYTE_LANES_B1 (BYTE_LANES_B1),
.BYTE_LANES_B2 (BYTE_LANES_B2),
.BYTE_LANES_B3 (BYTE_LANES_B3),
.BYTE_LANES_B4 (BYTE_LANES_B4),
.DATA_CTL_B0 (DATA_CTL_B0),
.DATA_CTL_B1 (DATA_CTL_B1),
.DATA_CTL_B2 (DATA_CTL_B2),
.DATA_CTL_B3 (DATA_CTL_B3),
.DATA_CTL_B4 (DATA_CTL_B4),
.PHY_0_BITLANES (PHY_0_BITLANES),
.PHY_1_BITLANES (PHY_1_BITLANES),
.PHY_2_BITLANES (PHY_2_BITLANES),
.PHY_0_BITLANES_OUTONLY (PHY_0_BITLANES_OUTONLY),
.PHY_1_BITLANES_OUTONLY (PHY_1_BITLANES_OUTONLY),
.PHY_2_BITLANES_OUTONLY (PHY_2_BITLANES_OUTONLY),
.RCLK_SELECT_BANK (CKE_ODT_RCLK_SELECT_BANK),
.RCLK_SELECT_LANE (CKE_ODT_RCLK_SELECT_LANE),
//.CKE_ODT_AUX (CKE_ODT_AUX),
.GENERATE_DDR_CK_MAP (TMP_GENERATE_DDR_CK_MAP),
.BYTELANES_DDR_CK (TMP_BYTELANES_DDR_CK),
.NUM_DDR_CK (CK_WIDTH),
.LP_DDR_CK_WIDTH (LP_DDR_CK_WIDTH),
.PO_CTL_COARSE_BYPASS ("FALSE"),
.PHYCTL_CMD_FIFO ("FALSE"),
.PHY_CLK_RATIO (nCK_PER_CLK),
.MASTER_PHY_CTL (MASTER_PHY_CTL),
.PHY_FOUR_WINDOW_CLOCKS (63),
.PHY_EVENTS_DELAY (18),
.PHY_COUNT_EN ("FALSE"), //PHY_COUNT_EN
.PHY_SYNC_MODE ("FALSE"),
.SYNTHESIS ((SIM_CAL_OPTION == "NONE") ? "TRUE" : "FALSE"),
.PHY_DISABLE_SEQ_MATCH ("TRUE"), //"TRUE"
.PHY_0_GENERATE_IDELAYCTRL ("FALSE"),
.PHY_0_A_PI_FREQ_REF_DIV (PHY_0_A_PI_FREQ_REF_DIV),
.PHY_0_CMD_OFFSET (PHY_0_CMD_OFFSET), //for CKE
.PHY_0_RD_CMD_OFFSET_0 (PHY_0_RD_CMD_OFFSET_0),
.PHY_0_RD_CMD_OFFSET_1 (PHY_0_RD_CMD_OFFSET_1),
.PHY_0_RD_CMD_OFFSET_2 (PHY_0_RD_CMD_OFFSET_2),
.PHY_0_RD_CMD_OFFSET_3 (PHY_0_RD_CMD_OFFSET_3),
.PHY_0_RD_DURATION_0 (6),
.PHY_0_RD_DURATION_1 (6),
.PHY_0_RD_DURATION_2 (6),
.PHY_0_RD_DURATION_3 (6),
.PHY_0_WR_CMD_OFFSET_0 (PHY_0_WR_CMD_OFFSET_0),
.PHY_0_WR_CMD_OFFSET_1 (PHY_0_WR_CMD_OFFSET_1),
.PHY_0_WR_CMD_OFFSET_2 (PHY_0_WR_CMD_OFFSET_2),
.PHY_0_WR_CMD_OFFSET_3 (PHY_0_WR_CMD_OFFSET_3),
.PHY_0_WR_DURATION_0 (PHY_0_WR_DURATION_0),
.PHY_0_WR_DURATION_1 (PHY_0_WR_DURATION_1),
.PHY_0_WR_DURATION_2 (PHY_0_WR_DURATION_2),
.PHY_0_WR_DURATION_3 (PHY_0_WR_DURATION_3),
.PHY_0_AO_TOGGLE ((RANKS == 1) ? 1 : 5),
.PHY_0_A_PO_OCLK_DELAY (PHY_0_A_PO_OCLK_DELAY),
.PHY_0_B_PO_OCLK_DELAY (PHY_0_A_PO_OCLK_DELAY),
.PHY_0_C_PO_OCLK_DELAY (PHY_0_A_PO_OCLK_DELAY),
.PHY_0_D_PO_OCLK_DELAY (PHY_0_A_PO_OCLK_DELAY),
.PHY_0_A_PO_OCLKDELAY_INV (PO_OCLKDELAY_INV),
.PHY_0_A_IDELAYE2_IDELAY_VALUE (PHY_0_A_IDELAYE2_IDELAY_VALUE),
.PHY_0_B_IDELAYE2_IDELAY_VALUE (PHY_0_A_IDELAYE2_IDELAY_VALUE),
.PHY_0_C_IDELAYE2_IDELAY_VALUE (PHY_0_A_IDELAYE2_IDELAY_VALUE),
.PHY_0_D_IDELAYE2_IDELAY_VALUE (PHY_0_A_IDELAYE2_IDELAY_VALUE),
.PHY_1_GENERATE_IDELAYCTRL ("FALSE"),
//.PHY_1_GENERATE_DDR_CK (TMP_PHY_1_GENERATE_DDR_CK),
//.PHY_1_NUM_DDR_CK (1),
.PHY_1_A_PO_OCLK_DELAY (PHY_0_A_PO_OCLK_DELAY),
.PHY_1_B_PO_OCLK_DELAY (PHY_0_A_PO_OCLK_DELAY),
.PHY_1_C_PO_OCLK_DELAY (PHY_0_A_PO_OCLK_DELAY),
.PHY_1_D_PO_OCLK_DELAY (PHY_0_A_PO_OCLK_DELAY),
.PHY_1_A_IDELAYE2_IDELAY_VALUE (PHY_0_A_IDELAYE2_IDELAY_VALUE),
.PHY_1_B_IDELAYE2_IDELAY_VALUE (PHY_0_A_IDELAYE2_IDELAY_VALUE),
.PHY_1_C_IDELAYE2_IDELAY_VALUE (PHY_0_A_IDELAYE2_IDELAY_VALUE),
.PHY_1_D_IDELAYE2_IDELAY_VALUE (PHY_0_A_IDELAYE2_IDELAY_VALUE),
.PHY_2_GENERATE_IDELAYCTRL ("FALSE"),
//.PHY_2_GENERATE_DDR_CK (TMP_PHY_2_GENERATE_DDR_CK),
//.PHY_2_NUM_DDR_CK (1),
.PHY_2_A_PO_OCLK_DELAY (PHY_0_A_PO_OCLK_DELAY),
.PHY_2_B_PO_OCLK_DELAY (PHY_0_A_PO_OCLK_DELAY),
.PHY_2_C_PO_OCLK_DELAY (PHY_0_A_PO_OCLK_DELAY),
.PHY_2_D_PO_OCLK_DELAY (PHY_0_A_PO_OCLK_DELAY),
.PHY_2_A_IDELAYE2_IDELAY_VALUE (PHY_0_A_IDELAYE2_IDELAY_VALUE),
.PHY_2_B_IDELAYE2_IDELAY_VALUE (PHY_0_A_IDELAYE2_IDELAY_VALUE),
.PHY_2_C_IDELAYE2_IDELAY_VALUE (PHY_0_A_IDELAYE2_IDELAY_VALUE),
.PHY_2_D_IDELAYE2_IDELAY_VALUE (PHY_0_A_IDELAYE2_IDELAY_VALUE),
.TCK (tCK),
.PHY_0_IODELAY_GRP (IODELAY_GRP)
,.PHY_1_IODELAY_GRP (IODELAY_GRP)
,.PHY_2_IODELAY_GRP (IODELAY_GRP)
,.BANK_TYPE (BANK_TYPE)
,.CKE_ODT_AUX (CKE_ODT_AUX)
)
u_ddr_mc_phy
(
.rst (rst),
// Don't use MC_PHY to generate DDR_RESET_N output. Instead
// generate this output outside of MC_PHY (and synchronous to CLK)
.ddr_rst_in_n (1'b1),
.phy_clk (clk),
.freq_refclk (freq_refclk),
.mem_refclk (mem_refclk),
// Remove later - always same connection as phy_clk port
.mem_refclk_div4 (clk),
.pll_lock (pll_lock),
.auxout_clk (),
.sync_pulse (sync_pulse),
// IDELAYCTRL instantiated outside of mc_phy module
.idelayctrl_refclk (),
.phy_dout (phy_dout),
.phy_cmd_wr_en (phy_cmd_wr_en),
.phy_data_wr_en (phy_data_wr_en),
.phy_rd_en (phy_rd_en),
.phy_ctl_wd (phy_ctl_wd_temp),
.phy_ctl_wr (phy_ctl_wr_temp),
.if_empty_def (phy_if_empty_def),
.if_rst (phy_if_reset),
.phyGo ('b1),
.aux_in_1 (aux_in_1),
.aux_in_2 (aux_in_2),
// No support yet for different data offsets for different I/O banks
// (possible use in supporting wider range of skew among bytes)
.data_offset_1 (data_offset_1_temp),
.data_offset_2 (data_offset_2_temp),
.cke_in (),
.if_a_empty (),
.if_empty (if_empty),
.if_empty_or (),
.if_empty_and (),
.of_ctl_a_full (),
// .of_data_a_full (phy_data_full),
.of_ctl_full (phy_cmd_full),
.of_data_full (),
.pre_data_a_full (phy_pre_data_a_full),
.idelay_ld (idelay_ld),
.idelay_ce (idelay_ce),
.idelay_inc (idelay_inc),
.input_sink (),
.phy_din (phy_din),
.phy_ctl_a_full (),
.phy_ctl_full (phy_ctl_full_temp),
.mem_dq_out (mem_dq_out),
.mem_dq_ts (mem_dq_ts),
.mem_dq_in (mem_dq_in),
.mem_dqs_out (mem_dqs_out),
.mem_dqs_ts (mem_dqs_ts),
.mem_dqs_in (mem_dqs_in),
.aux_out (aux_out),
.phy_ctl_ready (),
.rst_out (),
.ddr_clk (ddr_clk),
//.rclk (),
.mcGo (phy_mc_go),
.phy_write_calib (phy_write_calib),
.phy_read_calib (phy_read_calib),
.calib_sel (calib_sel),
.calib_in_common (calib_in_common),
.calib_zero_inputs (calib_zero_inputs),
.calib_zero_ctrl (calib_zero_ctrl),
.calib_zero_lanes ('b0),
.po_fine_enable (po_fine_enable),
.po_coarse_enable (po_coarse_enable),
.po_fine_inc (po_fine_inc),
.po_coarse_inc (po_coarse_inc),
.po_counter_load_en (po_counter_load_en),
.po_sel_fine_oclk_delay (po_sel_fine_oclk_delay),
.po_counter_load_val (po_counter_load_val),
.po_counter_read_en (po_counter_read_en),
.po_coarse_overflow (),
.po_fine_overflow (),
.po_counter_read_val (po_counter_read_val),
.pi_rst_dqs_find (pi_rst_dqs_find),
.pi_fine_enable (pi_fine_enable),
.pi_fine_inc (pi_fine_inc),
.pi_counter_load_en (pi_counter_load_en),
.pi_counter_read_en (dbg_pi_counter_read_en),
.pi_counter_load_val (pi_counter_load_val),
.pi_fine_overflow (),
.pi_counter_read_val (pi_counter_read_val),
.pi_phase_locked (pi_phase_locked),
.pi_phase_locked_all (pi_phase_locked_all),
.pi_dqs_found (),
.pi_dqs_found_any (pi_dqs_found),
.pi_dqs_found_all (pi_dqs_found_all),
.pi_dqs_found_lanes (dbg_pi_dqs_found_lanes_phy4lanes),
// Currently not being used. May be used in future if periodic
// reads become a requirement. This output could be used to signal
// a catastrophic failure in read capture and the need for
// re-calibration.
.pi_dqs_out_of_range (pi_dqs_out_of_range)
,.ref_dll_lock (ref_dll_lock)
,.pi_phase_locked_lanes (dbg_pi_phase_locked_phy4lanes)
// ,.rst_phaser_ref (rst_phaser_ref)
);
endmodule
|
// (C) 2001-2016 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
// THIS FILE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THIS FILE OR THE USE OR OTHER DEALINGS
// IN THIS FILE.
/******************************************************************************
* *
* This module reads and writes data to the RS232 connectpr on Altera's *
* DE1 and DE2 Development and Education Boards. *
* *
******************************************************************************/
module altera_up_rs232_counters (
// Inputs
clk,
reset,
reset_counters,
// Bidirectionals
// Outputs
baud_clock_rising_edge,
baud_clock_falling_edge,
all_bits_transmitted
);
/*****************************************************************************
* Parameter Declarations *
*****************************************************************************/
parameter CW = 9; // BAUD COUNTER WIDTH
parameter BAUD_TICK_COUNT = 433;
parameter HALF_BAUD_TICK_COUNT = 216;
parameter TDW = 11; // TOTAL DATA WIDTH
/*****************************************************************************
* Port Declarations *
*****************************************************************************/
// Inputs
input clk;
input reset;
input reset_counters;
// Bidirectionals
// Outputs
output reg baud_clock_rising_edge;
output reg baud_clock_falling_edge;
output reg all_bits_transmitted;
/*****************************************************************************
* Constant Declarations *
*****************************************************************************/
/*****************************************************************************
* Internal Wires and Registers Declarations *
*****************************************************************************/
// Internal Wires
// Internal Registers
reg [(CW-1):0] baud_counter;
reg [ 3: 0] bit_counter;
// State Machine Registers
/*****************************************************************************
* Finite State Machine(s) *
*****************************************************************************/
/*****************************************************************************
* Sequential Logic *
*****************************************************************************/
always @(posedge clk)
begin
if (reset)
baud_counter <= {CW{1'b0}};
else if (reset_counters)
baud_counter <= {CW{1'b0}};
else if (baud_counter == BAUD_TICK_COUNT)
baud_counter <= {CW{1'b0}};
else
baud_counter <= baud_counter + 1;
end
always @(posedge clk)
begin
if (reset)
baud_clock_rising_edge <= 1'b0;
else if (baud_counter == BAUD_TICK_COUNT)
baud_clock_rising_edge <= 1'b1;
else
baud_clock_rising_edge <= 1'b0;
end
always @(posedge clk)
begin
if (reset)
baud_clock_falling_edge <= 1'b0;
else if (baud_counter == HALF_BAUD_TICK_COUNT)
baud_clock_falling_edge <= 1'b1;
else
baud_clock_falling_edge <= 1'b0;
end
always @(posedge clk)
begin
if (reset)
bit_counter <= 4'h0;
else if (reset_counters)
bit_counter <= 4'h0;
else if (bit_counter == TDW)
bit_counter <= 4'h0;
else if (baud_counter == BAUD_TICK_COUNT)
bit_counter <= bit_counter + 4'h1;
end
always @(posedge clk)
begin
if (reset)
all_bits_transmitted <= 1'b0;
else if (bit_counter == TDW)
all_bits_transmitted <= 1'b1;
else
all_bits_transmitted <= 1'b0;
end
/*****************************************************************************
* Combinational Logic *
*****************************************************************************/
/*****************************************************************************
* Internal Modules *
*****************************************************************************/
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2010 by Wilson Snyder.
module t (/*AUTOARG*/
// Outputs
data_out,
// Inputs
wr, wa, rst_l, rd, ra, data_in, clk
);
input clk;
/*AUTOINPUT*/
// Beginning of automatic inputs (from unused autoinst inputs)
input [31:0] data_in; // To sub of reg_1r1w.v
input [7:0] ra; // To sub of reg_1r1w.v
input rd; // To sub of reg_1r1w.v
input rst_l; // To sub of reg_1r1w.v
input [7:0] wa; // To sub of reg_1r1w.v
input wr; // To sub of reg_1r1w.v
// End of automatics
/*AUTOOUTPUT*/
// Beginning of automatic outputs (from unused autoinst outputs)
output [31:0] data_out; // From sub of reg_1r1w.v
// End of automatics
reg_1r1w #(.WIDTH(32), .DEPTH(256), .ADRWID(8))
sub
(/*AUTOINST*/
// Outputs
.data_out (data_out[31:0]),
// Inputs
.data_in (data_in[31:0]),
.ra (ra[7:0]),
.wa (wa[7:0]),
.wr (wr),
.rd (rd),
.clk (clk),
.rst_l (rst_l));
endmodule
module reg_1r1w
#(
parameter WIDTH=32,
parameter ADRWID=10,
parameter DEPTH=1024,
parameter RST=0
)
(/*AUTOARG*/
// Outputs
data_out,
// Inputs
data_in, ra, wa, wr, rd, clk, rst_l
);
input [WIDTH-1:0] data_in;
input [ADRWID-1:0] ra;
input [ADRWID-1:0] wa;
input wr;
input rd;
input clk;
input rst_l;
output [WIDTH-1:0] data_out;
reg [WIDTH-1:0] array [DEPTH-1:0];
reg [ADRWID-1:0] ra_r, wa_r;
reg [WIDTH-1:0] data_in_r;
reg wr_r;
reg rd_r;
integer x;
// Message 679
always @(posedge clk) begin
int tmp = x + 1;
if (tmp !== x + 1) $stop;
end
always @(posedge clk or negedge rst_l) begin
if (!rst_l) begin
for (x=0; x<DEPTH; x=x+1) begin // <== VERILATOR FLAGS THIS LINE
if (RST == 1) begin
array[x] <= 0;
end
end
ra_r <= 0;
wa_r <= 0;
wr_r <= 0;
rd_r <= 0;
data_in_r <= 0;
end
else begin
ra_r <= ra;
wa_r <= wa;
wr_r <= wr;
rd_r <= rd;
data_in_r <= data_in;
if (wr_r) array[wa_r] <= data_in_r;
end
end
endmodule
// Local Variables:
// verilog-auto-inst-param-value: t
// End:
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2010 by Wilson Snyder.
module t (/*AUTOARG*/
// Outputs
data_out,
// Inputs
wr, wa, rst_l, rd, ra, data_in, clk
);
input clk;
/*AUTOINPUT*/
// Beginning of automatic inputs (from unused autoinst inputs)
input [31:0] data_in; // To sub of reg_1r1w.v
input [7:0] ra; // To sub of reg_1r1w.v
input rd; // To sub of reg_1r1w.v
input rst_l; // To sub of reg_1r1w.v
input [7:0] wa; // To sub of reg_1r1w.v
input wr; // To sub of reg_1r1w.v
// End of automatics
/*AUTOOUTPUT*/
// Beginning of automatic outputs (from unused autoinst outputs)
output [31:0] data_out; // From sub of reg_1r1w.v
// End of automatics
reg_1r1w #(.WIDTH(32), .DEPTH(256), .ADRWID(8))
sub
(/*AUTOINST*/
// Outputs
.data_out (data_out[31:0]),
// Inputs
.data_in (data_in[31:0]),
.ra (ra[7:0]),
.wa (wa[7:0]),
.wr (wr),
.rd (rd),
.clk (clk),
.rst_l (rst_l));
endmodule
module reg_1r1w
#(
parameter WIDTH=32,
parameter ADRWID=10,
parameter DEPTH=1024,
parameter RST=0
)
(/*AUTOARG*/
// Outputs
data_out,
// Inputs
data_in, ra, wa, wr, rd, clk, rst_l
);
input [WIDTH-1:0] data_in;
input [ADRWID-1:0] ra;
input [ADRWID-1:0] wa;
input wr;
input rd;
input clk;
input rst_l;
output [WIDTH-1:0] data_out;
reg [WIDTH-1:0] array [DEPTH-1:0];
reg [ADRWID-1:0] ra_r, wa_r;
reg [WIDTH-1:0] data_in_r;
reg wr_r;
reg rd_r;
integer x;
// Message 679
always @(posedge clk) begin
int tmp = x + 1;
if (tmp !== x + 1) $stop;
end
always @(posedge clk or negedge rst_l) begin
if (!rst_l) begin
for (x=0; x<DEPTH; x=x+1) begin // <== VERILATOR FLAGS THIS LINE
if (RST == 1) begin
array[x] <= 0;
end
end
ra_r <= 0;
wa_r <= 0;
wr_r <= 0;
rd_r <= 0;
data_in_r <= 0;
end
else begin
ra_r <= ra;
wa_r <= wa;
wr_r <= wr;
rd_r <= rd;
data_in_r <= data_in;
if (wr_r) array[wa_r] <= data_in_r;
end
end
endmodule
// Local Variables:
// verilog-auto-inst-param-value: t
// End:
|
// ----------------------------------------------------------------------
// Copyright (c) 2016, The Regents of the University of California All
// rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// * Neither the name of The Regents of the University of California
// nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL REGENTS OF THE
// UNIVERSITY OF CALIFORNIA BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
// OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
// TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
// ----------------------------------------------------------------------
//----------------------------------------------------------------------------
// Filename: pipeline.v
// Version: 1.00
// Verilog Standard: Verilog-2001
// Description: Standard 0-delay pipeline implementation. Takes WR_DATA on
// WR_READY and WR_VALID. RD_DATA is read on RD_READY and
// RD_VALID. C_DEPTH specifies the latency between RD and WR ports
// Author: Dustin Richmond (@darichmond)
//-----------------------------------------------------------------------------
`timescale 1ns/1ns
module pipeline
#(
parameter C_DEPTH = 10,
parameter C_WIDTH = 10,
parameter C_USE_MEMORY = 1
)
(
input CLK,
input RST_IN,
input [C_WIDTH-1:0] WR_DATA,
input WR_DATA_VALID,
output WR_DATA_READY,
output [C_WIDTH-1:0] RD_DATA,
output RD_DATA_VALID,
input RD_DATA_READY
);
generate
if (C_USE_MEMORY & C_DEPTH > 2) begin
mem_pipeline
#(
.C_PIPELINE_INPUT (1),
.C_PIPELINE_OUTPUT (1),
/*AUTOINSTPARAM*/
// Parameters
.C_DEPTH (C_DEPTH),
.C_WIDTH (C_WIDTH))
pipeline_inst
(/*AUTOINST*/
// Outputs
.WR_DATA_READY (WR_DATA_READY),
.RD_DATA (RD_DATA[C_WIDTH-1:0]),
.RD_DATA_VALID (RD_DATA_VALID),
// Inputs
.CLK (CLK),
.RST_IN (RST_IN),
.WR_DATA (WR_DATA[C_WIDTH-1:0]),
.WR_DATA_VALID (WR_DATA_VALID),
.RD_DATA_READY (RD_DATA_READY));
end else begin
reg_pipeline
#(/*AUTOINSTPARAM*/
// Parameters
.C_DEPTH (C_DEPTH),
.C_WIDTH (C_WIDTH))
pipeline_inst
(/*AUTOINST*/
// Outputs
.WR_DATA_READY (WR_DATA_READY),
.RD_DATA (RD_DATA[C_WIDTH-1:0]),
.RD_DATA_VALID (RD_DATA_VALID),
// Inputs
.CLK (CLK),
.RST_IN (RST_IN),
.WR_DATA (WR_DATA[C_WIDTH-1:0]),
.WR_DATA_VALID (WR_DATA_VALID),
.RD_DATA_READY (RD_DATA_READY));
end
endgenerate
endmodule // pipeline
module mem_pipeline
#(
parameter C_DEPTH = 10,
parameter C_WIDTH = 10,
parameter C_PIPELINE_INPUT = 0,
parameter C_PIPELINE_OUTPUT = 1
)
(
input CLK,
input RST_IN,
input [C_WIDTH-1:0] WR_DATA,
input WR_DATA_VALID,
output WR_DATA_READY,
output [C_WIDTH-1:0] RD_DATA,
output RD_DATA_VALID,
input RD_DATA_READY
);
localparam C_INPUT_REGISTERS = C_PIPELINE_INPUT?1:0;
localparam C_OUTPUT_REGISTERS = C_PIPELINE_OUTPUT?1:0;
wire RST;
wire [C_WIDTH-1:0] wRdData;
wire wRdDataValid;
wire wRdDataReady;
wire [C_WIDTH-1:0] wWrData;
wire wWrDataValid;
wire wWrDataReady;
assign RST = RST_IN;
reg_pipeline
#(
// Parameters
.C_DEPTH (C_INPUT_REGISTERS),
/*AUTOINSTPARAM*/
// Parameters
.C_WIDTH (C_WIDTH))
reg_in
(
// Outputs
.RD_DATA (wRdData),
.RD_DATA_VALID (wRdDataValid),
// Inputs
.RD_DATA_READY (wRdDataReady),
/*AUTOINST*/
// Outputs
.WR_DATA_READY (WR_DATA_READY),
// Inputs
.CLK (CLK),
.RST_IN (RST_IN),
.WR_DATA (WR_DATA[C_WIDTH-1:0]),
.WR_DATA_VALID (WR_DATA_VALID));
fifo
#(
// Parameters
.C_WIDTH (C_WIDTH),
.C_DEPTH (C_DEPTH - C_PIPELINE_INPUT - C_PIPELINE_OUTPUT),
.C_DELAY (C_DEPTH - C_PIPELINE_INPUT - C_PIPELINE_OUTPUT)
/*AUTOINSTPARAM*/)
fifo_inst
(
// Outputs
.RD_DATA (wWrData),
.WR_READY (wRdDataReady),
.RD_VALID (wWrDataValid),
// Inputs
.WR_DATA (wRdData),
.WR_VALID (wRdDataValid),
.RD_READY (wWrDataReady),
/*AUTOINST*/
// Inputs
.CLK (CLK),
.RST (RST));
reg_pipeline
#(
// Parameters
.C_DEPTH (C_OUTPUT_REGISTERS),
.C_WIDTH (C_WIDTH)
/*AUTOINSTPARAM*/)
reg_OUT
(
// Outputs
.WR_DATA_READY (wWrDataReady),
// Inputs
.WR_DATA (wWrData),
.WR_DATA_VALID (wWrDataValid),
/*AUTOINST*/
// Outputs
.RD_DATA (RD_DATA[C_WIDTH-1:0]),
.RD_DATA_VALID (RD_DATA_VALID),
// Inputs
.CLK (CLK),
.RST_IN (RST_IN),
.RD_DATA_READY (RD_DATA_READY));
endmodule // mem_pipeline
/* verilator lint_off UNOPTFLAT */
module reg_pipeline
#(
parameter C_DEPTH = 10,
parameter C_WIDTH = 10
)
(
input CLK,
input RST_IN,
input [C_WIDTH-1:0] WR_DATA,
input WR_DATA_VALID,
output WR_DATA_READY,
output [C_WIDTH-1:0] RD_DATA,
output RD_DATA_VALID,
input RD_DATA_READY
);
genvar i;
wire wReady [C_DEPTH:0];
reg [C_WIDTH-1:0] _rData [C_DEPTH:1], rData [C_DEPTH:0];
reg _rValid [C_DEPTH:1], rValid [C_DEPTH:0];
// Read interface
assign wReady[C_DEPTH] = RD_DATA_READY;
assign RD_DATA = rData[C_DEPTH];
assign RD_DATA_VALID = rValid[C_DEPTH];
// Write interface
assign WR_DATA_READY = wReady[0];
always @(*) begin
rData[0] = WR_DATA;
rValid[0] = WR_DATA_VALID;
end
generate
for( i = 1 ; i <= C_DEPTH; i = i + 1 ) begin : gen_stages
assign #1 wReady[i-1] = ~rValid[i] | wReady[i];
// Data Registers
always @(*) begin
_rData[i] = rData[i-1];
end
// Enable the data register when the corresponding stage is ready
always @(posedge CLK) begin
if(wReady[i-1]) begin
rData[i] <= #1 _rData[i];
end
end
// Valid Registers
always @(*) begin
if(RST_IN) begin
_rValid[i] = 1'b0;
end else begin
_rValid[i] = rValid[i-1] | (rValid[i] & ~wReady[i]);
end
end
// Always enable the valid registers
always @(posedge CLK) begin
rValid[i] <= #1 _rValid[i];
end
end
endgenerate
endmodule
/* verilator lint_on UNOPTFLAT */
|
(************************************************************************)
(* v * The Coq Proof Assistant / The Coq Development Team *)
(* <O___,, * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2015 *)
(* \VV/ **************************************************************)
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
(** * Int31 numbers defines indeed a cyclic structure : Z/(2^31)Z *)
(**
Author: Arnaud Spiwack (+ Pierre Letouzey)
*)
Require Import List.
Require Import Min.
Require Export Int31.
Require Import Znumtheory.
Require Import Zgcd_alt.
Require Import Zpow_facts.
Require Import BigNumPrelude.
Require Import CyclicAxioms.
Require Import ROmega.
Local Open Scope nat_scope.
Local Open Scope int31_scope.
Section Basics.
(** * Basic results about [iszero], [shiftl], [shiftr] *)
Lemma iszero_eq0 : forall x, iszero x = true -> x=0.
Proof.
destruct x; simpl; intros.
repeat
match goal with H:(if ?d then _ else _) = true |- _ =>
destruct d; try discriminate
end.
reflexivity.
Qed.
Lemma iszero_not_eq0 : forall x, iszero x = false -> x<>0.
Proof.
intros x H Eq; rewrite Eq in H; simpl in *; discriminate.
Qed.
Lemma sneakl_shiftr : forall x,
x = sneakl (firstr x) (shiftr x).
Proof.
destruct x; simpl; auto.
Qed.
Lemma sneakr_shiftl : forall x,
x = sneakr (firstl x) (shiftl x).
Proof.
destruct x; simpl; auto.
Qed.
Lemma twice_zero : forall x,
twice x = 0 <-> twice_plus_one x = 1.
Proof.
destruct x; simpl in *; split;
intro H; injection H; intros; subst; auto.
Qed.
Lemma twice_or_twice_plus_one : forall x,
x = twice (shiftr x) \/ x = twice_plus_one (shiftr x).
Proof.
intros; case_eq (firstr x); intros.
destruct x; simpl in *; rewrite H; auto.
destruct x; simpl in *; rewrite H; auto.
Qed.
(** * Iterated shift to the right *)
Definition nshiftr x := nat_rect _ x (fun _ => shiftr).
Lemma nshiftr_S :
forall n x, nshiftr x (S n) = shiftr (nshiftr x n).
Proof.
reflexivity.
Qed.
Lemma nshiftr_S_tail :
forall n x, nshiftr x (S n) = nshiftr (shiftr x) n.
Proof.
intros n; elim n; simpl; auto.
intros; now f_equal.
Qed.
Lemma nshiftr_n_0 : forall n, nshiftr 0 n = 0.
Proof.
induction n; simpl; auto.
rewrite IHn; auto.
Qed.
Lemma nshiftr_size : forall x, nshiftr x size = 0.
Proof.
destruct x; simpl; auto.
Qed.
Lemma nshiftr_above_size : forall k x, size<=k ->
nshiftr x k = 0.
Proof.
intros.
replace k with ((k-size)+size)%nat by omega.
induction (k-size)%nat; auto.
rewrite nshiftr_size; auto.
simpl; rewrite IHn; auto.
Qed.
(** * Iterated shift to the left *)
Definition nshiftl x := nat_rect _ x (fun _ => shiftl).
Lemma nshiftl_S :
forall n x, nshiftl x (S n) = shiftl (nshiftl x n).
Proof.
reflexivity.
Qed.
Lemma nshiftl_S_tail :
forall n x, nshiftl x (S n) = nshiftl (shiftl x) n.
Proof.
intros n; elim n; simpl; intros; now f_equal.
Qed.
Lemma nshiftl_n_0 : forall n, nshiftl 0 n = 0.
Proof.
induction n; simpl; auto.
rewrite IHn; auto.
Qed.
Lemma nshiftl_size : forall x, nshiftl x size = 0.
Proof.
destruct x; simpl; auto.
Qed.
Lemma nshiftl_above_size : forall k x, size<=k ->
nshiftl x k = 0.
Proof.
intros.
replace k with ((k-size)+size)%nat by omega.
induction (k-size)%nat; auto.
rewrite nshiftl_size; auto.
simpl; rewrite IHn; auto.
Qed.
Lemma firstr_firstl :
forall x, firstr x = firstl (nshiftl x (pred size)).
Proof.
destruct x; simpl; auto.
Qed.
Lemma firstl_firstr :
forall x, firstl x = firstr (nshiftr x (pred size)).
Proof.
destruct x; simpl; auto.
Qed.
(** More advanced results about [nshiftr] *)
Lemma nshiftr_predsize_0_firstl : forall x,
nshiftr x (pred size) = 0 -> firstl x = D0.
Proof.
destruct x; compute; intros H; injection H; intros; subst; auto.
Qed.
Lemma nshiftr_0_propagates : forall n p x, n <= p ->
nshiftr x n = 0 -> nshiftr x p = 0.
Proof.
intros.
replace p with ((p-n)+n)%nat by omega.
induction (p-n)%nat.
simpl; auto.
simpl; rewrite IHn0; auto.
Qed.
Lemma nshiftr_0_firstl : forall n x, n < size ->
nshiftr x n = 0 -> firstl x = D0.
Proof.
intros.
apply nshiftr_predsize_0_firstl.
apply nshiftr_0_propagates with n; auto; omega.
Qed.
(** * Some induction principles over [int31] *)
(** Not used for the moment. Are they really useful ? *)
Lemma int31_ind_sneakl : forall P : int31->Prop,
P 0 ->
(forall x d, P x -> P (sneakl d x)) ->
forall x, P x.
Proof.
intros.
assert (forall n, n<=size -> P (nshiftr x (size - n))).
induction n; intros.
rewrite nshiftr_size; auto.
rewrite sneakl_shiftr.
apply H0.
change (P (nshiftr x (S (size - S n)))).
replace (S (size - S n))%nat with (size - n)%nat by omega.
apply IHn; omega.
change x with (nshiftr x (size-size)); auto.
Qed.
Lemma int31_ind_twice : forall P : int31->Prop,
P 0 ->
(forall x, P x -> P (twice x)) ->
(forall x, P x -> P (twice_plus_one x)) ->
forall x, P x.
Proof.
induction x using int31_ind_sneakl; auto.
destruct d; auto.
Qed.
(** * Some generic results about [recr] *)
Section Recr.
(** [recr] satisfies the fixpoint equation used for its definition. *)
Variable (A:Type)(case0:A)(caserec:digits->int31->A->A).
Lemma recr_aux_eqn : forall n x, iszero x = false ->
recr_aux (S n) A case0 caserec x =
caserec (firstr x) (shiftr x) (recr_aux n A case0 caserec (shiftr x)).
Proof.
intros; simpl; rewrite H; auto.
Qed.
Lemma recr_aux_converges :
forall n p x, n <= size -> n <= p ->
recr_aux n A case0 caserec (nshiftr x (size - n)) =
recr_aux p A case0 caserec (nshiftr x (size - n)).
Proof.
induction n.
simpl minus; intros.
rewrite nshiftr_size; destruct p; simpl; auto.
intros.
destruct p.
inversion H0.
unfold recr_aux; fold recr_aux.
destruct (iszero (nshiftr x (size - S n))); auto.
f_equal.
change (shiftr (nshiftr x (size - S n))) with (nshiftr x (S (size - S n))).
replace (S (size - S n))%nat with (size - n)%nat by omega.
apply IHn; auto with arith.
Qed.
Lemma recr_eqn : forall x, iszero x = false ->
recr A case0 caserec x =
caserec (firstr x) (shiftr x) (recr A case0 caserec (shiftr x)).
Proof.
intros.
unfold recr.
change x with (nshiftr x (size - size)).
rewrite (recr_aux_converges size (S size)); auto with arith.
rewrite recr_aux_eqn; auto.
Qed.
(** [recr] is usually equivalent to a variant [recrbis]
written without [iszero] check. *)
Fixpoint recrbis_aux (n:nat)(A:Type)(case0:A)(caserec:digits->int31->A->A)
(i:int31) : A :=
match n with
| O => case0
| S next =>
let si := shiftr i in
caserec (firstr i) si (recrbis_aux next A case0 caserec si)
end.
Definition recrbis := recrbis_aux size.
Hypothesis case0_caserec : caserec D0 0 case0 = case0.
Lemma recrbis_aux_equiv : forall n x,
recrbis_aux n A case0 caserec x = recr_aux n A case0 caserec x.
Proof.
induction n; simpl; auto; intros.
case_eq (iszero x); intros; [ | f_equal; auto ].
rewrite (iszero_eq0 _ H); simpl; auto.
replace (recrbis_aux n A case0 caserec 0) with case0; auto.
clear H IHn; induction n; simpl; congruence.
Qed.
Lemma recrbis_equiv : forall x,
recrbis A case0 caserec x = recr A case0 caserec x.
Proof.
intros; apply recrbis_aux_equiv; auto.
Qed.
End Recr.
(** * Incrementation *)
Section Incr.
(** Variant of [incr] via [recrbis] *)
Let Incr (b : digits) (si rec : int31) :=
match b with
| D0 => sneakl D1 si
| D1 => sneakl D0 rec
end.
Definition incrbis_aux n x := recrbis_aux n _ In Incr x.
Lemma incrbis_aux_equiv : forall x, incrbis_aux size x = incr x.
Proof.
unfold incr, recr, incrbis_aux; fold Incr; intros.
apply recrbis_aux_equiv; auto.
Qed.
(** Recursive equations satisfied by [incr] *)
Lemma incr_eqn1 :
forall x, firstr x = D0 -> incr x = twice_plus_one (shiftr x).
Proof.
intros.
case_eq (iszero x); intros.
rewrite (iszero_eq0 _ H0); simpl; auto.
unfold incr; rewrite recr_eqn; fold incr; auto.
rewrite H; auto.
Qed.
Lemma incr_eqn2 :
forall x, firstr x = D1 -> incr x = twice (incr (shiftr x)).
Proof.
intros.
case_eq (iszero x); intros.
rewrite (iszero_eq0 _ H0) in H; simpl in H; discriminate.
unfold incr; rewrite recr_eqn; fold incr; auto.
rewrite H; auto.
Qed.
Lemma incr_twice : forall x, incr (twice x) = twice_plus_one x.
Proof.
intros.
rewrite incr_eqn1; destruct x; simpl; auto.
Qed.
Lemma incr_twice_plus_one_firstl :
forall x, firstl x = D0 -> incr (twice_plus_one x) = twice (incr x).
Proof.
intros.
rewrite incr_eqn2; [ | destruct x; simpl; auto ].
f_equal; f_equal.
destruct x; simpl in *; rewrite H; auto.
Qed.
(** The previous result is actually true even without the
constraint on [firstl], but this is harder to prove
(see later). *)
End Incr.
(** * Conversion to [Z] : the [phi] function *)
Section Phi.
(** Variant of [phi] via [recrbis] *)
Let Phi := fun b (_:int31) =>
match b with D0 => Z.double | D1 => Z.succ_double end.
Definition phibis_aux n x := recrbis_aux n _ Z0 Phi x.
Lemma phibis_aux_equiv : forall x, phibis_aux size x = phi x.
Proof.
unfold phi, recr, phibis_aux; fold Phi; intros.
apply recrbis_aux_equiv; auto.
Qed.
(** Recursive equations satisfied by [phi] *)
Lemma phi_eqn1 : forall x, firstr x = D0 ->
phi x = Z.double (phi (shiftr x)).
Proof.
intros.
case_eq (iszero x); intros.
rewrite (iszero_eq0 _ H0); simpl; auto.
intros; unfold phi; rewrite recr_eqn; fold phi; auto.
rewrite H; auto.
Qed.
Lemma phi_eqn2 : forall x, firstr x = D1 ->
phi x = Z.succ_double (phi (shiftr x)).
Proof.
intros.
case_eq (iszero x); intros.
rewrite (iszero_eq0 _ H0) in H; simpl in H; discriminate.
intros; unfold phi; rewrite recr_eqn; fold phi; auto.
rewrite H; auto.
Qed.
Lemma phi_twice_firstl : forall x, firstl x = D0 ->
phi (twice x) = Z.double (phi x).
Proof.
intros.
rewrite phi_eqn1; auto; [ | destruct x; auto ].
f_equal; f_equal.
destruct x; simpl in *; rewrite H; auto.
Qed.
Lemma phi_twice_plus_one_firstl : forall x, firstl x = D0 ->
phi (twice_plus_one x) = Z.succ_double (phi x).
Proof.
intros.
rewrite phi_eqn2; auto; [ | destruct x; auto ].
f_equal; f_equal.
destruct x; simpl in *; rewrite H; auto.
Qed.
End Phi.
(** [phi x] is positive and lower than [2^31] *)
Lemma phibis_aux_pos : forall n x, (0 <= phibis_aux n x)%Z.
Proof.
induction n.
simpl; unfold phibis_aux; simpl; auto with zarith.
intros.
unfold phibis_aux, recrbis_aux; fold recrbis_aux;
fold (phibis_aux n (shiftr x)).
destruct (firstr x).
specialize IHn with (shiftr x); rewrite Z.double_spec; omega.
specialize IHn with (shiftr x); rewrite Z.succ_double_spec; omega.
Qed.
Lemma phibis_aux_bounded :
forall n x, n <= size ->
(phibis_aux n (nshiftr x (size-n)) < 2 ^ (Z.of_nat n))%Z.
Proof.
induction n.
simpl minus; unfold phibis_aux; simpl; auto with zarith.
intros.
unfold phibis_aux, recrbis_aux; fold recrbis_aux;
fold (phibis_aux n (shiftr (nshiftr x (size - S n)))).
assert (shiftr (nshiftr x (size - S n)) = nshiftr x (size-n)).
replace (size - n)%nat with (S (size - (S n))) by omega.
simpl; auto.
rewrite H0.
assert (H1 : n <= size) by omega.
specialize (IHn x H1).
set (y:=phibis_aux n (nshiftr x (size - n))) in *.
rewrite Nat2Z.inj_succ, Z.pow_succ_r; auto with zarith.
case_eq (firstr (nshiftr x (size - S n))); intros.
rewrite Z.double_spec; auto with zarith.
rewrite Z.succ_double_spec; auto with zarith.
Qed.
Lemma phi_bounded : forall x, (0 <= phi x < 2 ^ (Z.of_nat size))%Z.
Proof.
intros.
rewrite <- phibis_aux_equiv.
split.
apply phibis_aux_pos.
change x with (nshiftr x (size-size)).
apply phibis_aux_bounded; auto.
Qed.
Lemma phibis_aux_lowerbound :
forall n x, firstr (nshiftr x n) = D1 ->
(2 ^ Z.of_nat n <= phibis_aux (S n) x)%Z.
Proof.
induction n.
intros.
unfold nshiftr in H; simpl in *.
unfold phibis_aux, recrbis_aux.
rewrite H, Z.succ_double_spec; omega.
intros.
remember (S n) as m.
unfold phibis_aux, recrbis_aux; fold recrbis_aux;
fold (phibis_aux m (shiftr x)).
subst m.
rewrite Nat2Z.inj_succ, Z.pow_succ_r; auto with zarith.
assert (2^(Z.of_nat n) <= phibis_aux (S n) (shiftr x))%Z.
apply IHn.
rewrite <- nshiftr_S_tail; auto.
destruct (firstr x).
change (Z.double (phibis_aux (S n) (shiftr x))) with
(2*(phibis_aux (S n) (shiftr x)))%Z.
omega.
rewrite Z.succ_double_spec; omega.
Qed.
Lemma phi_lowerbound :
forall x, firstl x = D1 -> (2^(Z.of_nat (pred size)) <= phi x)%Z.
Proof.
intros.
generalize (phibis_aux_lowerbound (pred size) x).
rewrite <- firstl_firstr.
change (S (pred size)) with size; auto.
rewrite phibis_aux_equiv; auto.
Qed.
(** * Equivalence modulo [2^n] *)
Section EqShiftL.
(** After killing [n] bits at the left, are the numbers equal ?*)
Definition EqShiftL n x y :=
nshiftl x n = nshiftl y n.
Lemma EqShiftL_zero : forall x y, EqShiftL O x y <-> x = y.
Proof.
unfold EqShiftL; intros; unfold nshiftl; simpl; split; auto.
Qed.
Lemma EqShiftL_size : forall k x y, size<=k -> EqShiftL k x y.
Proof.
red; intros; rewrite 2 nshiftl_above_size; auto.
Qed.
Lemma EqShiftL_le : forall k k' x y, k <= k' ->
EqShiftL k x y -> EqShiftL k' x y.
Proof.
unfold EqShiftL; intros.
replace k' with ((k'-k)+k)%nat by omega.
remember (k'-k)%nat as n.
clear Heqn H k'.
induction n; simpl; auto.
f_equal; auto.
Qed.
Lemma EqShiftL_firstr : forall k x y, k < size ->
EqShiftL k x y -> firstr x = firstr y.
Proof.
intros.
rewrite 2 firstr_firstl.
f_equal.
apply EqShiftL_le with k; auto.
unfold size.
auto with arith.
Qed.
Lemma EqShiftL_twice : forall k x y,
EqShiftL k (twice x) (twice y) <-> EqShiftL (S k) x y.
Proof.
intros; unfold EqShiftL.
rewrite 2 nshiftl_S_tail; split; auto.
Qed.
(** * From int31 to list of digits. *)
(** Lower (=rightmost) bits comes first. *)
Definition i2l := recrbis _ nil (fun d _ rec => d::rec).
Lemma i2l_length : forall x, length (i2l x) = size.
Proof.
intros; reflexivity.
Qed.
Fixpoint lshiftl l x :=
match l with
| nil => x
| d::l => sneakl d (lshiftl l x)
end.
Definition l2i l := lshiftl l On.
Lemma l2i_i2l : forall x, l2i (i2l x) = x.
Proof.
destruct x; compute; auto.
Qed.
Lemma i2l_sneakr : forall x d,
i2l (sneakr d x) = tail (i2l x) ++ d::nil.
Proof.
destruct x; compute; auto.
Qed.
Lemma i2l_sneakl : forall x d,
i2l (sneakl d x) = d :: removelast (i2l x).
Proof.
destruct x; compute; auto.
Qed.
Lemma i2l_l2i : forall l, length l = size ->
i2l (l2i l) = l.
Proof.
repeat (destruct l as [ |? l]; [intros; discriminate | ]).
destruct l; [ | intros; discriminate].
intros _; compute; auto.
Qed.
Fixpoint cstlist (A:Type)(a:A) n :=
match n with
| O => nil
| S n => a::cstlist _ a n
end.
Lemma i2l_nshiftl : forall n x, n<=size ->
i2l (nshiftl x n) = cstlist _ D0 n ++ firstn (size-n) (i2l x).
Proof.
induction n.
intros.
assert (firstn (size-0) (i2l x) = i2l x).
rewrite <- minus_n_O, <- (i2l_length x).
induction (i2l x); simpl; f_equal; auto.
rewrite H0; clear H0.
reflexivity.
intros.
rewrite nshiftl_S.
unfold shiftl; rewrite i2l_sneakl.
simpl cstlist.
rewrite <- app_comm_cons; f_equal.
rewrite IHn; [ | omega].
rewrite removelast_app.
apply f_equal.
replace (size-n)%nat with (S (size - S n))%nat by omega.
rewrite removelast_firstn; auto.
rewrite i2l_length; omega.
generalize (firstn_length (size-n) (i2l x)).
rewrite i2l_length.
intros H0 H1. rewrite H1 in H0.
rewrite min_l in H0 by omega.
simpl length in H0.
omega.
Qed.
(** [i2l] can be used to define a relation equivalent to [EqShiftL] *)
Lemma EqShiftL_i2l : forall k x y,
EqShiftL k x y <-> firstn (size-k) (i2l x) = firstn (size-k) (i2l y).
Proof.
intros.
destruct (le_lt_dec size k) as [Hle|Hlt].
split; intros.
replace (size-k)%nat with O by omega.
unfold firstn; auto.
apply EqShiftL_size; auto.
unfold EqShiftL.
assert (k <= size) by omega.
split; intros.
assert (i2l (nshiftl x k) = i2l (nshiftl y k)) by (f_equal; auto).
rewrite 2 i2l_nshiftl in H1; auto.
eapply app_inv_head; eauto.
assert (i2l (nshiftl x k) = i2l (nshiftl y k)).
rewrite 2 i2l_nshiftl; auto.
f_equal; auto.
rewrite <- (l2i_i2l (nshiftl x k)), <- (l2i_i2l (nshiftl y k)).
f_equal; auto.
Qed.
(** This equivalence allows proving easily the following delicate
result *)
Lemma EqShiftL_twice_plus_one : forall k x y,
EqShiftL k (twice_plus_one x) (twice_plus_one y) <-> EqShiftL (S k) x y.
Proof.
intros.
destruct (le_lt_dec size k) as [Hle|Hlt].
split; intros; apply EqShiftL_size; auto.
rewrite 2 EqShiftL_i2l.
unfold twice_plus_one.
rewrite 2 i2l_sneakl.
replace (size-k)%nat with (S (size - S k))%nat by omega.
remember (size - S k)%nat as n.
remember (i2l x) as lx.
remember (i2l y) as ly.
simpl.
rewrite 2 firstn_removelast.
split; intros.
injection H; auto.
f_equal; auto.
subst ly n; rewrite i2l_length; omega.
subst lx n; rewrite i2l_length; omega.
Qed.
Lemma EqShiftL_shiftr : forall k x y, EqShiftL k x y ->
EqShiftL (S k) (shiftr x) (shiftr y).
Proof.
intros.
destruct (le_lt_dec size (S k)) as [Hle|Hlt].
apply EqShiftL_size; auto.
case_eq (firstr x); intros.
rewrite <- EqShiftL_twice.
unfold twice; rewrite <- H0.
rewrite <- sneakl_shiftr.
rewrite (EqShiftL_firstr k x y); auto.
rewrite <- sneakl_shiftr; auto.
omega.
rewrite <- EqShiftL_twice_plus_one.
unfold twice_plus_one; rewrite <- H0.
rewrite <- sneakl_shiftr.
rewrite (EqShiftL_firstr k x y); auto.
rewrite <- sneakl_shiftr; auto.
omega.
Qed.
Lemma EqShiftL_incrbis : forall n k x y, n<=size ->
(n+k=S size)%nat ->
EqShiftL k x y ->
EqShiftL k (incrbis_aux n x) (incrbis_aux n y).
Proof.
induction n; simpl; intros.
red; auto.
destruct (eq_nat_dec k size).
subst k; apply EqShiftL_size; auto.
unfold incrbis_aux; simpl;
fold (incrbis_aux n (shiftr x)); fold (incrbis_aux n (shiftr y)).
rewrite (EqShiftL_firstr k x y); auto; try omega.
case_eq (firstr y); intros.
rewrite EqShiftL_twice_plus_one.
apply EqShiftL_shiftr; auto.
rewrite EqShiftL_twice.
apply IHn; try omega.
apply EqShiftL_shiftr; auto.
Qed.
Lemma EqShiftL_incr : forall x y,
EqShiftL 1 x y -> EqShiftL 1 (incr x) (incr y).
Proof.
intros.
rewrite <- 2 incrbis_aux_equiv.
apply EqShiftL_incrbis; auto.
Qed.
End EqShiftL.
(** * More equations about [incr] *)
Lemma incr_twice_plus_one :
forall x, incr (twice_plus_one x) = twice (incr x).
Proof.
intros.
rewrite incr_eqn2; [ | destruct x; simpl; auto].
apply EqShiftL_incr.
red; destruct x; simpl; auto.
Qed.
Lemma incr_firstr : forall x, firstr (incr x) <> firstr x.
Proof.
intros.
case_eq (firstr x); intros.
rewrite incr_eqn1; auto.
destruct (shiftr x); simpl; discriminate.
rewrite incr_eqn2; auto.
destruct (incr (shiftr x)); simpl; discriminate.
Qed.
Lemma incr_inv : forall x y,
incr x = twice_plus_one y -> x = twice y.
Proof.
intros.
case_eq (iszero x); intros.
rewrite (iszero_eq0 _ H0) in *; simpl in *.
change (incr 0) with 1 in H.
symmetry; rewrite twice_zero; auto.
case_eq (firstr x); intros.
rewrite incr_eqn1 in H; auto.
clear H0; destruct x; destruct y; simpl in *.
injection H; intros; subst; auto.
elim (incr_firstr x).
rewrite H1, H; destruct y; simpl; auto.
Qed.
(** * Conversion from [Z] : the [phi_inv] function *)
(** First, recursive equations *)
Lemma phi_inv_double_plus_one : forall z,
phi_inv (Z.succ_double z) = twice_plus_one (phi_inv z).
Proof.
destruct z; simpl; auto.
induction p; simpl.
rewrite 2 incr_twice; auto.
rewrite incr_twice, incr_twice_plus_one.
f_equal.
apply incr_inv; auto.
auto.
Qed.
Lemma phi_inv_double : forall z,
phi_inv (Z.double z) = twice (phi_inv z).
Proof.
destruct z; simpl; auto.
rewrite incr_twice_plus_one; auto.
Qed.
Lemma phi_inv_incr : forall z,
phi_inv (Z.succ z) = incr (phi_inv z).
Proof.
destruct z.
simpl; auto.
simpl; auto.
induction p; simpl; auto.
rewrite <- Pos.add_1_r, IHp, incr_twice_plus_one; auto.
rewrite incr_twice; auto.
simpl; auto.
destruct p; simpl; auto.
rewrite incr_twice; auto.
f_equal.
rewrite incr_twice_plus_one; auto.
induction p; simpl; auto.
rewrite incr_twice; auto.
f_equal.
rewrite incr_twice_plus_one; auto.
Qed.
(** [phi_inv o inv], the always-exact and easy-to-prove trip :
from int31 to Z and then back to int31. *)
Lemma phi_inv_phi_aux :
forall n x, n <= size ->
phi_inv (phibis_aux n (nshiftr x (size-n))) =
nshiftr x (size-n).
Proof.
induction n.
intros; simpl minus.
rewrite nshiftr_size; auto.
intros.
unfold phibis_aux, recrbis_aux; fold recrbis_aux;
fold (phibis_aux n (shiftr (nshiftr x (size-S n)))).
assert (shiftr (nshiftr x (size - S n)) = nshiftr x (size-n)).
replace (size - n)%nat with (S (size - (S n))); auto; omega.
rewrite H0.
case_eq (firstr (nshiftr x (size - S n))); intros.
rewrite phi_inv_double.
rewrite IHn by omega.
rewrite <- H0.
remember (nshiftr x (size - S n)) as y.
destruct y; simpl in H1; rewrite H1; auto.
rewrite phi_inv_double_plus_one.
rewrite IHn by omega.
rewrite <- H0.
remember (nshiftr x (size - S n)) as y.
destruct y; simpl in H1; rewrite H1; auto.
Qed.
Lemma phi_inv_phi : forall x, phi_inv (phi x) = x.
Proof.
intros.
rewrite <- phibis_aux_equiv.
replace x with (nshiftr x (size - size)) by auto.
apply phi_inv_phi_aux; auto.
Qed.
(** The other composition [phi o phi_inv] is harder to prove correct.
In particular, an overflow can happen, so a modulo is needed.
For the moment, we proceed via several steps, the first one
being a detour to [positive_to_in31]. *)
(** * [positive_to_int31] *)
(** A variant of [p2i] with [twice] and [twice_plus_one] instead of
[2*i] and [2*i+1] *)
Fixpoint p2ibis n p : (N*int31)%type :=
match n with
| O => (Npos p, On)
| S n => match p with
| xO p => let (r,i) := p2ibis n p in (r, twice i)
| xI p => let (r,i) := p2ibis n p in (r, twice_plus_one i)
| xH => (N0, In)
end
end.
Lemma p2ibis_bounded : forall n p,
nshiftr (snd (p2ibis n p)) n = 0.
Proof.
induction n.
simpl; intros; auto.
simpl p2ibis; intros.
destruct p; simpl snd.
specialize IHn with p.
destruct (p2ibis n p). simpl @snd in *.
rewrite nshiftr_S_tail.
destruct (le_lt_dec size n) as [Hle|Hlt].
rewrite nshiftr_above_size; auto.
assert (H:=nshiftr_0_firstl _ _ Hlt IHn).
replace (shiftr (twice_plus_one i)) with i; auto.
destruct i; simpl in *. rewrite H; auto.
specialize IHn with p.
destruct (p2ibis n p); simpl @snd in *.
rewrite nshiftr_S_tail.
destruct (le_lt_dec size n) as [Hle|Hlt].
rewrite nshiftr_above_size; auto.
assert (H:=nshiftr_0_firstl _ _ Hlt IHn).
replace (shiftr (twice i)) with i; auto.
destruct i; simpl in *; rewrite H; auto.
rewrite nshiftr_S_tail; auto.
replace (shiftr In) with 0; auto.
apply nshiftr_n_0.
Qed.
Local Open Scope Z_scope.
Lemma p2ibis_spec : forall n p, (n<=size)%nat ->
Zpos p = (Z.of_N (fst (p2ibis n p)))*2^(Z.of_nat n) +
phi (snd (p2ibis n p)).
Proof.
induction n; intros.
simpl; rewrite Pos.mul_1_r; auto.
replace (2^(Z.of_nat (S n)))%Z with (2*2^(Z.of_nat n))%Z by
(rewrite <- Z.pow_succ_r, <- Zpos_P_of_succ_nat;
auto with zarith).
rewrite (Z.mul_comm 2).
assert (n<=size)%nat by omega.
destruct p; simpl; [ | | auto];
specialize (IHn p H0);
generalize (p2ibis_bounded n p);
destruct (p2ibis n p) as (r,i); simpl in *; intros.
change (Zpos p~1) with (2*Zpos p + 1)%Z.
rewrite phi_twice_plus_one_firstl, Z.succ_double_spec.
rewrite IHn; ring.
apply (nshiftr_0_firstl n); auto; try omega.
change (Zpos p~0) with (2*Zpos p)%Z.
rewrite phi_twice_firstl.
change (Z.double (phi i)) with (2*(phi i))%Z.
rewrite IHn; ring.
apply (nshiftr_0_firstl n); auto; try omega.
Qed.
(** We now prove that this [p2ibis] is related to [phi_inv_positive] *)
Lemma phi_inv_positive_p2ibis : forall n p, (n<=size)%nat ->
EqShiftL (size-n) (phi_inv_positive p) (snd (p2ibis n p)).
Proof.
induction n.
intros.
apply EqShiftL_size; auto.
intros.
simpl p2ibis; destruct p; [ | | red; auto];
specialize IHn with p;
destruct (p2ibis n p); simpl @snd in *; simpl phi_inv_positive;
rewrite ?EqShiftL_twice_plus_one, ?EqShiftL_twice;
replace (S (size - S n))%nat with (size - n)%nat by omega;
apply IHn; omega.
Qed.
(** This gives the expected result about [phi o phi_inv], at least
for the positive case. *)
Lemma phi_phi_inv_positive : forall p,
phi (phi_inv_positive p) = (Zpos p) mod (2^(Z.of_nat size)).
Proof.
intros.
replace (phi_inv_positive p) with (snd (p2ibis size p)).
rewrite (p2ibis_spec size p) by auto.
rewrite Z.add_comm, Z_mod_plus.
symmetry; apply Zmod_small.
apply phi_bounded.
auto with zarith.
symmetry.
rewrite <- EqShiftL_zero.
apply (phi_inv_positive_p2ibis size p); auto.
Qed.
(** Moreover, [p2ibis] is also related with [p2i] and hence with
[positive_to_int31]. *)
Lemma double_twice_firstl : forall x, firstl x = D0 ->
(Twon*x = twice x)%int31.
Proof.
intros.
unfold mul31.
rewrite <- Z.double_spec, <- phi_twice_firstl, phi_inv_phi; auto.
Qed.
Lemma double_twice_plus_one_firstl : forall x, firstl x = D0 ->
(Twon*x+In = twice_plus_one x)%int31.
Proof.
intros.
rewrite double_twice_firstl; auto.
unfold add31.
rewrite phi_twice_firstl, <- Z.succ_double_spec,
<- phi_twice_plus_one_firstl, phi_inv_phi; auto.
Qed.
Lemma p2i_p2ibis : forall n p, (n<=size)%nat ->
p2i n p = p2ibis n p.
Proof.
induction n; simpl; auto; intros.
destruct p; auto; specialize IHn with p;
generalize (p2ibis_bounded n p);
rewrite IHn; try omega; destruct (p2ibis n p); simpl; intros;
f_equal; auto.
apply double_twice_plus_one_firstl.
apply (nshiftr_0_firstl n); auto; omega.
apply double_twice_firstl.
apply (nshiftr_0_firstl n); auto; omega.
Qed.
Lemma positive_to_int31_phi_inv_positive : forall p,
snd (positive_to_int31 p) = phi_inv_positive p.
Proof.
intros; unfold positive_to_int31.
rewrite p2i_p2ibis; auto.
symmetry.
rewrite <- EqShiftL_zero.
apply (phi_inv_positive_p2ibis size); auto.
Qed.
Lemma positive_to_int31_spec : forall p,
Zpos p = (Z.of_N (fst (positive_to_int31 p)))*2^(Z.of_nat size) +
phi (snd (positive_to_int31 p)).
Proof.
unfold positive_to_int31.
intros; rewrite p2i_p2ibis; auto.
apply p2ibis_spec; auto.
Qed.
(** Thanks to the result about [phi o phi_inv_positive], we can
now establish easily the most general results about
[phi o twice] and so one. *)
Lemma phi_twice : forall x,
phi (twice x) = (Z.double (phi x)) mod 2^(Z.of_nat size).
Proof.
intros.
pattern x at 1; rewrite <- (phi_inv_phi x).
rewrite <- phi_inv_double.
assert (0 <= Z.double (phi x)).
rewrite Z.double_spec; generalize (phi_bounded x); omega.
destruct (Z.double (phi x)).
simpl; auto.
apply phi_phi_inv_positive.
compute in H; elim H; auto.
Qed.
Lemma phi_twice_plus_one : forall x,
phi (twice_plus_one x) = (Z.succ_double (phi x)) mod 2^(Z.of_nat size).
Proof.
intros.
pattern x at 1; rewrite <- (phi_inv_phi x).
rewrite <- phi_inv_double_plus_one.
assert (0 <= Z.succ_double (phi x)).
rewrite Z.succ_double_spec; generalize (phi_bounded x); omega.
destruct (Z.succ_double (phi x)).
simpl; auto.
apply phi_phi_inv_positive.
compute in H; elim H; auto.
Qed.
Lemma phi_incr : forall x,
phi (incr x) = (Z.succ (phi x)) mod 2^(Z.of_nat size).
Proof.
intros.
pattern x at 1; rewrite <- (phi_inv_phi x).
rewrite <- phi_inv_incr.
assert (0 <= Z.succ (phi x)).
change (Z.succ (phi x)) with ((phi x)+1)%Z;
generalize (phi_bounded x); omega.
destruct (Z.succ (phi x)).
simpl; auto.
apply phi_phi_inv_positive.
compute in H; elim H; auto.
Qed.
(** With the previous results, we can deal with [phi o phi_inv] even
in the negative case *)
Lemma phi_phi_inv_negative :
forall p, phi (incr (complement_negative p)) = (Zneg p) mod 2^(Z.of_nat size).
Proof.
induction p.
simpl complement_negative.
rewrite phi_incr in IHp.
rewrite incr_twice, phi_twice_plus_one.
remember (phi (complement_negative p)) as q.
rewrite Z.succ_double_spec.
replace (2*q+1) with (2*(Z.succ q)-1) by omega.
rewrite <- Zminus_mod_idemp_l, <- Zmult_mod_idemp_r, IHp.
rewrite Zmult_mod_idemp_r, Zminus_mod_idemp_l; auto with zarith.
simpl complement_negative.
rewrite incr_twice_plus_one, phi_twice.
remember (phi (incr (complement_negative p))) as q.
rewrite Z.double_spec, IHp, Zmult_mod_idemp_r; auto with zarith.
simpl; auto.
Qed.
Lemma phi_phi_inv :
forall z, phi (phi_inv z) = z mod 2 ^ (Z.of_nat size).
Proof.
destruct z.
simpl; auto.
apply phi_phi_inv_positive.
apply phi_phi_inv_negative.
Qed.
End Basics.
Instance int31_ops : ZnZ.Ops int31 :=
{
digits := 31%positive; (* number of digits *)
zdigits := 31; (* number of digits *)
to_Z := phi; (* conversion to Z *)
of_pos := positive_to_int31; (* positive -> N*int31 : p => N,i
where p = N*2^31+phi i *)
head0 := head031; (* number of head 0 *)
tail0 := tail031; (* number of tail 0 *)
zero := 0;
one := 1;
minus_one := Tn; (* 2^31 - 1 *)
compare := compare31;
eq0 := fun i => match i ?= 0 with Eq => true | _ => false end;
opp_c := fun i => 0 -c i;
opp := opp31;
opp_carry := fun i => 0-i-1;
succ_c := fun i => i +c 1;
add_c := add31c;
add_carry_c := add31carryc;
succ := fun i => i + 1;
add := add31;
add_carry := fun i j => i + j + 1;
pred_c := fun i => i -c 1;
sub_c := sub31c;
sub_carry_c := sub31carryc;
pred := fun i => i - 1;
sub := sub31;
sub_carry := fun i j => i - j - 1;
mul_c := mul31c;
mul := mul31;
square_c := fun x => x *c x;
div21 := div3121;
div_gt := div31; (* this is supposed to be the special case of
division a/b where a > b *)
div := div31;
modulo_gt := fun i j => let (_,r) := i/j in r;
modulo := fun i j => let (_,r) := i/j in r;
gcd_gt := gcd31;
gcd := gcd31;
add_mul_div := addmuldiv31;
pos_mod := (* modulo 2^p *)
fun p i =>
match p ?= 31 with
| Lt => addmuldiv31 p 0 (addmuldiv31 (31-p) i 0)
| _ => i
end;
is_even :=
fun i => let (_,r) := i/2 in
match r ?= 0 with Eq => true | _ => false end;
sqrt2 := sqrt312;
sqrt := sqrt31;
lor := lor31;
land := land31;
lxor := lxor31
}.
Section Int31_Specs.
Local Open Scope Z_scope.
Notation "[| x |]" := (phi x) (at level 0, x at level 99).
Local Notation wB := (2 ^ (Z.of_nat size)).
Lemma wB_pos : wB > 0.
Proof.
auto with zarith.
Qed.
Notation "[+| c |]" :=
(interp_carry 1 wB phi c) (at level 0, c at level 99).
Notation "[-| c |]" :=
(interp_carry (-1) wB phi c) (at level 0, c at level 99).
Notation "[|| x ||]" :=
(zn2z_to_Z wB phi x) (at level 0, x at level 99).
Lemma spec_zdigits : [| 31 |] = 31.
Proof.
reflexivity.
Qed.
Lemma spec_more_than_1_digit: 1 < 31.
Proof.
auto with zarith.
Qed.
Lemma spec_0 : [| 0 |] = 0.
Proof.
reflexivity.
Qed.
Lemma spec_1 : [| 1 |] = 1.
Proof.
reflexivity.
Qed.
Lemma spec_m1 : [| Tn |] = wB - 1.
Proof.
reflexivity.
Qed.
Lemma spec_compare : forall x y,
(x ?= y)%int31 = ([|x|] ?= [|y|]).
Proof. reflexivity. Qed.
(** Addition *)
Lemma spec_add_c : forall x y, [+|add31c x y|] = [|x|] + [|y|].
Proof.
intros; unfold add31c, add31, interp_carry; rewrite phi_phi_inv.
generalize (phi_bounded x)(phi_bounded y); intros.
set (X:=[|x|]) in *; set (Y:=[|y|]) in *; clearbody X Y.
assert ((X+Y) mod wB ?= X+Y <> Eq -> [+|C1 (phi_inv (X+Y))|] = X+Y).
unfold interp_carry; rewrite phi_phi_inv, Z.compare_eq_iff; intros.
destruct (Z_lt_le_dec (X+Y) wB).
contradict H1; auto using Zmod_small with zarith.
rewrite <- (Z_mod_plus_full (X+Y) (-1) wB).
rewrite Zmod_small; romega.
generalize (Z.compare_eq ((X+Y) mod wB) (X+Y)); intros Heq.
destruct Z.compare; intros;
[ rewrite phi_phi_inv; auto | now apply H1 | now apply H1].
Qed.
Lemma spec_succ_c : forall x, [+|add31c x 1|] = [|x|] + 1.
Proof.
intros; apply spec_add_c.
Qed.
Lemma spec_add_carry_c : forall x y, [+|add31carryc x y|] = [|x|] + [|y|] + 1.
Proof.
intros.
unfold add31carryc, interp_carry; rewrite phi_phi_inv.
generalize (phi_bounded x)(phi_bounded y); intros.
set (X:=[|x|]) in *; set (Y:=[|y|]) in *; clearbody X Y.
assert ((X+Y+1) mod wB ?= X+Y+1 <> Eq -> [+|C1 (phi_inv (X+Y+1))|] = X+Y+1).
unfold interp_carry; rewrite phi_phi_inv, Z.compare_eq_iff; intros.
destruct (Z_lt_le_dec (X+Y+1) wB).
contradict H1; auto using Zmod_small with zarith.
rewrite <- (Z_mod_plus_full (X+Y+1) (-1) wB).
rewrite Zmod_small; romega.
generalize (Z.compare_eq ((X+Y+1) mod wB) (X+Y+1)); intros Heq.
destruct Z.compare; intros;
[ rewrite phi_phi_inv; auto | now apply H1 | now apply H1].
Qed.
Lemma spec_add : forall x y, [|x+y|] = ([|x|] + [|y|]) mod wB.
Proof.
intros; apply phi_phi_inv.
Qed.
Lemma spec_add_carry :
forall x y, [|x+y+1|] = ([|x|] + [|y|] + 1) mod wB.
Proof.
unfold add31; intros.
repeat rewrite phi_phi_inv.
apply Zplus_mod_idemp_l.
Qed.
Lemma spec_succ : forall x, [|x+1|] = ([|x|] + 1) mod wB.
Proof.
intros; rewrite <- spec_1; apply spec_add.
Qed.
(** Substraction *)
Lemma spec_sub_c : forall x y, [-|sub31c x y|] = [|x|] - [|y|].
Proof.
unfold sub31c, sub31, interp_carry; intros.
rewrite phi_phi_inv.
generalize (phi_bounded x)(phi_bounded y); intros.
set (X:=[|x|]) in *; set (Y:=[|y|]) in *; clearbody X Y.
assert ((X-Y) mod wB ?= X-Y <> Eq -> [-|C1 (phi_inv (X-Y))|] = X-Y).
unfold interp_carry; rewrite phi_phi_inv, Z.compare_eq_iff; intros.
destruct (Z_lt_le_dec (X-Y) 0).
rewrite <- (Z_mod_plus_full (X-Y) 1 wB).
rewrite Zmod_small; romega.
contradict H1; apply Zmod_small; romega.
generalize (Z.compare_eq ((X-Y) mod wB) (X-Y)); intros Heq.
destruct Z.compare; intros;
[ rewrite phi_phi_inv; auto | now apply H1 | now apply H1].
Qed.
Lemma spec_sub_carry_c : forall x y, [-|sub31carryc x y|] = [|x|] - [|y|] - 1.
Proof.
unfold sub31carryc, sub31, interp_carry; intros.
rewrite phi_phi_inv.
generalize (phi_bounded x)(phi_bounded y); intros.
set (X:=[|x|]) in *; set (Y:=[|y|]) in *; clearbody X Y.
assert ((X-Y-1) mod wB ?= X-Y-1 <> Eq -> [-|C1 (phi_inv (X-Y-1))|] = X-Y-1).
unfold interp_carry; rewrite phi_phi_inv, Z.compare_eq_iff; intros.
destruct (Z_lt_le_dec (X-Y-1) 0).
rewrite <- (Z_mod_plus_full (X-Y-1) 1 wB).
rewrite Zmod_small; romega.
contradict H1; apply Zmod_small; romega.
generalize (Z.compare_eq ((X-Y-1) mod wB) (X-Y-1)); intros Heq.
destruct Z.compare; intros;
[ rewrite phi_phi_inv; auto | now apply H1 | now apply H1].
Qed.
Lemma spec_sub : forall x y, [|x-y|] = ([|x|] - [|y|]) mod wB.
Proof.
intros; apply phi_phi_inv.
Qed.
Lemma spec_sub_carry :
forall x y, [|x-y-1|] = ([|x|] - [|y|] - 1) mod wB.
Proof.
unfold sub31; intros.
repeat rewrite phi_phi_inv.
apply Zminus_mod_idemp_l.
Qed.
Lemma spec_opp_c : forall x, [-|sub31c 0 x|] = -[|x|].
Proof.
intros; apply spec_sub_c.
Qed.
Lemma spec_opp : forall x, [|0 - x|] = (-[|x|]) mod wB.
Proof.
intros; apply phi_phi_inv.
Qed.
Lemma spec_opp_carry : forall x, [|0 - x - 1|] = wB - [|x|] - 1.
Proof.
unfold sub31; intros.
repeat rewrite phi_phi_inv.
change [|1|] with 1; change [|0|] with 0.
rewrite <- (Z_mod_plus_full (0-[|x|]) 1 wB).
rewrite Zminus_mod_idemp_l.
rewrite Zmod_small; generalize (phi_bounded x); romega.
Qed.
Lemma spec_pred_c : forall x, [-|sub31c x 1|] = [|x|] - 1.
Proof.
intros; apply spec_sub_c.
Qed.
Lemma spec_pred : forall x, [|x-1|] = ([|x|] - 1) mod wB.
Proof.
intros; apply spec_sub.
Qed.
(** Multiplication *)
Lemma phi2_phi_inv2 : forall x, [||phi_inv2 x||] = x mod (wB^2).
Proof.
assert (forall z, (z / wB) mod wB * wB + z mod wB = z mod wB ^ 2).
intros.
assert ((z/wB) mod wB = z/wB - (z/wB/wB)*wB).
rewrite (Z_div_mod_eq (z/wB) wB wB_pos) at 2; ring.
assert (z mod wB = z - (z/wB)*wB).
rewrite (Z_div_mod_eq z wB wB_pos) at 2; ring.
rewrite H.
rewrite H0 at 1.
ring_simplify.
rewrite Zdiv_Zdiv; auto with zarith.
rewrite (Z_div_mod_eq z (wB*wB)) at 2; auto with zarith.
change (wB*wB) with (wB^2); ring.
unfold phi_inv2.
destruct x; unfold zn2z_to_Z; rewrite ?phi_phi_inv;
change base with wB; auto.
Qed.
Lemma spec_mul_c : forall x y, [|| mul31c x y ||] = [|x|] * [|y|].
Proof.
unfold mul31c; intros.
rewrite phi2_phi_inv2.
apply Zmod_small.
generalize (phi_bounded x)(phi_bounded y); intros.
change (wB^2) with (wB * wB).
auto using Z.mul_lt_mono_nonneg with zarith.
Qed.
Lemma spec_mul : forall x y, [|x*y|] = ([|x|] * [|y|]) mod wB.
Proof.
intros; apply phi_phi_inv.
Qed.
Lemma spec_square_c : forall x, [|| mul31c x x ||] = [|x|] * [|x|].
Proof.
intros; apply spec_mul_c.
Qed.
(** Division *)
Lemma spec_div21 : forall a1 a2 b,
wB/2 <= [|b|] ->
[|a1|] < [|b|] ->
let (q,r) := div3121 a1 a2 b in
[|a1|] *wB+ [|a2|] = [|q|] * [|b|] + [|r|] /\
0 <= [|r|] < [|b|].
Proof.
unfold div3121; intros.
generalize (phi_bounded a1)(phi_bounded a2)(phi_bounded b); intros.
assert ([|b|]>0) by (auto with zarith).
generalize (Z_div_mod (phi2 a1 a2) [|b|] H4) (Z_div_pos (phi2 a1 a2) [|b|] H4).
unfold Z.div; destruct (Z.div_eucl (phi2 a1 a2) [|b|]).
rewrite ?phi_phi_inv.
destruct 1; intros.
unfold phi2 in *.
change base with wB; change base with wB in H5.
change (Z.pow_pos 2 31) with wB; change (Z.pow_pos 2 31) with wB in H.
rewrite H5, Z.mul_comm.
replace (z0 mod wB) with z0 by (symmetry; apply Zmod_small; omega).
replace (z mod wB) with z; auto with zarith.
symmetry; apply Zmod_small.
split.
apply H7; change base with wB; auto with zarith.
apply Z.mul_lt_mono_pos_r with [|b|]; [omega| ].
rewrite Z.mul_comm.
apply Z.le_lt_trans with ([|b|]*z+z0); [omega| ].
rewrite <- H5.
apply Z.le_lt_trans with ([|a1|]*wB+(wB-1)); [omega | ].
replace ([|a1|]*wB+(wB-1)) with (wB*([|a1|]+1)-1) by ring.
assert (wB*([|a1|]+1) <= wB*[|b|]); try omega.
apply Z.mul_le_mono_nonneg; omega.
Qed.
Lemma spec_div : forall a b, 0 < [|b|] ->
let (q,r) := div31 a b in
[|a|] = [|q|] * [|b|] + [|r|] /\
0 <= [|r|] < [|b|].
Proof.
unfold div31; intros.
assert ([|b|]>0) by (auto with zarith).
generalize (Z_div_mod [|a|] [|b|] H0) (Z_div_pos [|a|] [|b|] H0).
unfold Z.div; destruct (Z.div_eucl [|a|] [|b|]).
rewrite ?phi_phi_inv.
destruct 1; intros.
rewrite H1, Z.mul_comm.
generalize (phi_bounded a)(phi_bounded b); intros.
replace (z0 mod wB) with z0 by (symmetry; apply Zmod_small; omega).
replace (z mod wB) with z; auto with zarith.
symmetry; apply Zmod_small.
split; auto with zarith.
apply Z.le_lt_trans with [|a|]; auto with zarith.
rewrite H1.
apply Z.le_trans with ([|b|]*z); try omega.
rewrite <- (Z.mul_1_l z) at 1.
apply Z.mul_le_mono_nonneg; auto with zarith.
Qed.
Lemma spec_mod : forall a b, 0 < [|b|] ->
[|let (_,r) := (a/b)%int31 in r|] = [|a|] mod [|b|].
Proof.
unfold div31; intros.
assert ([|b|]>0) by (auto with zarith).
unfold Z.modulo.
generalize (Z_div_mod [|a|] [|b|] H0).
destruct (Z.div_eucl [|a|] [|b|]).
rewrite ?phi_phi_inv.
destruct 1; intros.
generalize (phi_bounded b); intros.
apply Zmod_small; omega.
Qed.
Lemma phi_gcd : forall i j,
[|gcd31 i j|] = Zgcdn (2*size) [|j|] [|i|].
Proof.
unfold gcd31.
induction (2*size)%nat; intros.
reflexivity.
simpl euler.
unfold compare31.
change [|On|] with 0.
generalize (phi_bounded j)(phi_bounded i); intros.
case_eq [|j|]; intros.
simpl; intros.
generalize (Zabs_spec [|i|]); omega.
simpl. rewrite IHn, H1; f_equal.
rewrite spec_mod, H1; auto.
rewrite H1; compute; auto.
rewrite H1 in H; destruct H as [H _]; compute in H; elim H; auto.
Qed.
Lemma spec_gcd : forall a b, Zis_gcd [|a|] [|b|] [|gcd31 a b|].
Proof.
intros.
rewrite phi_gcd.
apply Zis_gcd_sym.
apply Zgcdn_is_gcd.
unfold Zgcd_bound.
generalize (phi_bounded b).
destruct [|b|].
unfold size; auto with zarith.
intros (_,H).
cut (Pos.size_nat p <= size)%nat; [ omega | rewrite <- Zpower2_Psize; auto].
intros (H,_); compute in H; elim H; auto.
Qed.
Lemma iter_int31_iter_nat : forall A f i a,
iter_int31 i A f a = iter_nat (Z.abs_nat [|i|]) A f a.
Proof.
intros.
unfold iter_int31.
rewrite <- recrbis_equiv; auto; unfold recrbis.
rewrite <- phibis_aux_equiv.
revert i a; induction size.
simpl; auto.
simpl; intros.
case_eq (firstr i); intros H; rewrite 2 IHn;
unfold phibis_aux; simpl; rewrite ?H; fold (phibis_aux n (shiftr i));
generalize (phibis_aux_pos n (shiftr i)); intros;
set (z := phibis_aux n (shiftr i)) in *; clearbody z;
rewrite <- nat_rect_plus.
f_equal.
rewrite Z.double_spec, <- Z.add_diag.
symmetry; apply Zabs2Nat.inj_add; auto with zarith.
change (iter_nat (S (Z.abs_nat z) + (Z.abs_nat z))%nat A f a =
iter_nat (Z.abs_nat (Z.succ_double z)) A f a); f_equal.
rewrite Z.succ_double_spec, <- Z.add_diag.
rewrite Zabs2Nat.inj_add; auto with zarith.
rewrite Zabs2Nat.inj_add; auto with zarith.
change (Z.abs_nat 1) with 1%nat; omega.
Qed.
Fixpoint addmuldiv31_alt n i j :=
match n with
| O => i
| S n => addmuldiv31_alt n (sneakl (firstl j) i) (shiftl j)
end.
Lemma addmuldiv31_equiv : forall p x y,
addmuldiv31 p x y = addmuldiv31_alt (Z.abs_nat [|p|]) x y.
Proof.
intros.
unfold addmuldiv31.
rewrite iter_int31_iter_nat.
set (n:=Z.abs_nat [|p|]); clearbody n; clear p.
revert x y; induction n.
simpl; auto.
intros.
simpl addmuldiv31_alt.
replace (S n) with (n+1)%nat by (rewrite plus_comm; auto).
rewrite nat_rect_plus; simpl; auto.
Qed.
Lemma spec_add_mul_div : forall x y p, [|p|] <= Zpos 31 ->
[| addmuldiv31 p x y |] =
([|x|] * (2 ^ [|p|]) + [|y|] / (2 ^ ((Zpos 31) - [|p|]))) mod wB.
Proof.
intros.
rewrite addmuldiv31_equiv.
assert ([|p|] = Z.of_nat (Z.abs_nat [|p|])).
rewrite Zabs2Nat.id_abs; symmetry; apply Z.abs_eq.
destruct (phi_bounded p); auto.
rewrite H0; rewrite H0 in H; clear H0; rewrite Zabs2Nat.id.
set (n := Z.abs_nat [|p|]) in *; clearbody n.
assert (n <= 31)%nat.
rewrite Nat2Z.inj_le; auto with zarith.
clear p H; revert x y.
induction n.
simpl Z.of_nat; intros.
rewrite Z.mul_1_r.
replace ([|y|] / 2^(31-0)) with 0.
rewrite Z.add_0_r.
symmetry; apply Zmod_small; apply phi_bounded.
symmetry; apply Zdiv_small; apply phi_bounded.
simpl addmuldiv31_alt; intros.
rewrite IHn; [ | omega ].
case_eq (firstl y); intros.
rewrite phi_twice, Z.double_spec.
rewrite phi_twice_firstl; auto.
change (Z.double [|y|]) with (2*[|y|]).
rewrite Nat2Z.inj_succ, Z.pow_succ_r; auto with zarith.
rewrite Zplus_mod; rewrite Zmult_mod_idemp_l; rewrite <- Zplus_mod.
f_equal.
f_equal.
ring.
replace (31-Z.of_nat n) with (Z.succ(31-Z.succ(Z.of_nat n))) by ring.
rewrite Z.pow_succ_r, <- Zdiv_Zdiv; auto with zarith.
rewrite Z.mul_comm, Z_div_mult; auto with zarith.
rewrite phi_twice_plus_one, Z.succ_double_spec.
rewrite phi_twice; auto.
change (Z.double [|y|]) with (2*[|y|]).
rewrite Nat2Z.inj_succ, Z.pow_succ_r; auto with zarith.
rewrite Zplus_mod; rewrite Zmult_mod_idemp_l; rewrite <- Zplus_mod.
rewrite Z.mul_add_distr_r, Z.mul_1_l, <- Z.add_assoc.
f_equal.
f_equal.
ring.
assert ((2*[|y|]) mod wB = 2*[|y|] - wB).
clear - H. symmetry. apply Zmod_unique with 1; [ | ring ].
generalize (phi_lowerbound _ H) (phi_bounded y).
set (wB' := 2^Z.of_nat (pred size)).
replace wB with (2*wB'); [ omega | ].
unfold wB'. rewrite <- Z.pow_succ_r, <- Nat2Z.inj_succ by (auto with zarith).
f_equal.
rewrite H1.
replace wB with (2^(Z.of_nat n)*2^(31-Z.of_nat n)) by
(rewrite <- Zpower_exp; auto with zarith; f_equal; unfold size; ring).
unfold Z.sub; rewrite <- Z.mul_opp_l.
rewrite Z_div_plus; auto with zarith.
ring_simplify.
replace (31+-Z.of_nat n) with (Z.succ(31-Z.succ(Z.of_nat n))) by ring.
rewrite Z.pow_succ_r, <- Zdiv_Zdiv; auto with zarith.
rewrite Z.mul_comm, Z_div_mult; auto with zarith.
Qed.
Lemma spec_pos_mod : forall w p,
[|ZnZ.pos_mod p w|] = [|w|] mod (2 ^ [|p|]).
Proof.
unfold int31_ops, ZnZ.pos_mod, compare31.
change [|31|] with 31%Z.
assert (forall w p, 31<=p -> [|w|] = [|w|] mod 2^p).
intros.
generalize (phi_bounded w).
symmetry; apply Zmod_small.
split; auto with zarith.
apply Z.lt_le_trans with wB; auto with zarith.
apply Zpower_le_monotone; auto with zarith.
intros.
case_eq ([|p|] ?= 31); intros;
[ apply H; rewrite (Z.compare_eq _ _ H0); auto with zarith | |
apply H; change ([|p|]>31)%Z in H0; auto with zarith ].
change ([|p|]<31) in H0.
rewrite spec_add_mul_div by auto with zarith.
change [|0|] with 0%Z; rewrite Z.mul_0_l, Z.add_0_l.
generalize (phi_bounded p)(phi_bounded w); intros.
assert (31-[|p|]<wB).
apply Z.le_lt_trans with 31%Z; auto with zarith.
compute; auto.
assert ([|31-p|]=31-[|p|]).
unfold sub31; rewrite phi_phi_inv.
change [|31|] with 31%Z.
apply Zmod_small; auto with zarith.
rewrite spec_add_mul_div by (rewrite H4; auto with zarith).
change [|0|] with 0%Z; rewrite Zdiv_0_l, Z.add_0_r.
rewrite H4.
apply shift_unshift_mod_2; auto with zarith.
Qed.
(** Shift operations *)
Lemma spec_head00: forall x, [|x|] = 0 -> [|head031 x|] = Zpos 31.
Proof.
intros.
generalize (phi_inv_phi x).
rewrite H; simpl phi_inv.
intros H'; rewrite <- H'.
simpl; auto.
Qed.
Fixpoint head031_alt n x :=
match n with
| O => 0%nat
| S n => match firstl x with
| D0 => S (head031_alt n (shiftl x))
| D1 => 0%nat
end
end.
Lemma head031_equiv :
forall x, [|head031 x|] = Z.of_nat (head031_alt size x).
Proof.
intros.
case_eq (iszero x); intros.
rewrite (iszero_eq0 _ H).
simpl; auto.
unfold head031, recl.
change On with (phi_inv (Z.of_nat (31-size))).
replace (head031_alt size x) with
(head031_alt size x + (31 - size))%nat by auto.
assert (size <= 31)%nat by auto with arith.
revert x H; induction size; intros.
simpl; auto.
unfold recl_aux; fold recl_aux.
unfold head031_alt; fold head031_alt.
rewrite H.
assert ([|phi_inv (Z.of_nat (31-S n))|] = Z.of_nat (31 - S n)).
rewrite phi_phi_inv.
apply Zmod_small.
split.
change 0 with (Z.of_nat O); apply inj_le; omega.
apply Z.le_lt_trans with (Z.of_nat 31).
apply inj_le; omega.
compute; auto.
case_eq (firstl x); intros; auto.
rewrite plus_Sn_m, plus_n_Sm.
replace (S (31 - S n)) with (31 - n)%nat by omega.
rewrite <- IHn; [ | omega | ].
f_equal; f_equal.
unfold add31.
rewrite H1.
f_equal.
change [|In|] with 1.
replace (31-n)%nat with (S (31 - S n))%nat by omega.
rewrite Nat2Z.inj_succ; ring.
clear - H H2.
rewrite (sneakr_shiftl x) in H.
rewrite H2 in H.
case_eq (iszero (shiftl x)); intros; auto.
rewrite (iszero_eq0 _ H0) in H; discriminate.
Qed.
Lemma phi_nz : forall x, 0 < [|x|] <-> x <> 0%int31.
Proof.
split; intros.
red; intro; subst x; discriminate.
assert ([|x|]<>0%Z).
contradict H.
rewrite <- (phi_inv_phi x); rewrite H; auto.
generalize (phi_bounded x); auto with zarith.
Qed.
Lemma spec_head0 : forall x, 0 < [|x|] ->
wB/ 2 <= 2 ^ ([|head031 x|]) * [|x|] < wB.
Proof.
intros.
rewrite head031_equiv.
assert (nshiftl x size = 0%int31).
apply nshiftl_size.
revert x H H0.
unfold size at 2 5.
induction size.
simpl Z.of_nat.
intros.
compute in H0; rewrite H0 in H; discriminate.
intros.
simpl head031_alt.
case_eq (firstl x); intros.
rewrite (Nat2Z.inj_succ (head031_alt n (shiftl x))), Z.pow_succ_r; auto with zarith.
rewrite <- Z.mul_assoc, Z.mul_comm, <- Z.mul_assoc, <-(Z.mul_comm 2).
rewrite <- Z.double_spec, <- (phi_twice_firstl _ H1).
apply IHn.
rewrite phi_nz; rewrite phi_nz in H; contradict H.
change twice with shiftl in H.
rewrite (sneakr_shiftl x), H1, H; auto.
rewrite <- nshiftl_S_tail; auto.
change (2^(Z.of_nat 0)) with 1; rewrite Z.mul_1_l.
generalize (phi_bounded x); unfold size; split; auto with zarith.
change (2^(Z.of_nat 31)/2) with (2^(Z.of_nat (pred size))).
apply phi_lowerbound; auto.
Qed.
Lemma spec_tail00: forall x, [|x|] = 0 -> [|tail031 x|] = Zpos 31.
Proof.
intros.
generalize (phi_inv_phi x).
rewrite H; simpl phi_inv.
intros H'; rewrite <- H'.
simpl; auto.
Qed.
Fixpoint tail031_alt n x :=
match n with
| O => 0%nat
| S n => match firstr x with
| D0 => S (tail031_alt n (shiftr x))
| D1 => 0%nat
end
end.
Lemma tail031_equiv :
forall x, [|tail031 x|] = Z.of_nat (tail031_alt size x).
Proof.
intros.
case_eq (iszero x); intros.
rewrite (iszero_eq0 _ H).
simpl; auto.
unfold tail031, recr.
change On with (phi_inv (Z.of_nat (31-size))).
replace (tail031_alt size x) with
(tail031_alt size x + (31 - size))%nat by auto.
assert (size <= 31)%nat by auto with arith.
revert x H; induction size; intros.
simpl; auto.
unfold recr_aux; fold recr_aux.
unfold tail031_alt; fold tail031_alt.
rewrite H.
assert ([|phi_inv (Z.of_nat (31-S n))|] = Z.of_nat (31 - S n)).
rewrite phi_phi_inv.
apply Zmod_small.
split.
change 0 with (Z.of_nat O); apply inj_le; omega.
apply Z.le_lt_trans with (Z.of_nat 31).
apply inj_le; omega.
compute; auto.
case_eq (firstr x); intros; auto.
rewrite plus_Sn_m, plus_n_Sm.
replace (S (31 - S n)) with (31 - n)%nat by omega.
rewrite <- IHn; [ | omega | ].
f_equal; f_equal.
unfold add31.
rewrite H1.
f_equal.
change [|In|] with 1.
replace (31-n)%nat with (S (31 - S n))%nat by omega.
rewrite Nat2Z.inj_succ; ring.
clear - H H2.
rewrite (sneakl_shiftr x) in H.
rewrite H2 in H.
case_eq (iszero (shiftr x)); intros; auto.
rewrite (iszero_eq0 _ H0) in H; discriminate.
Qed.
Lemma spec_tail0 : forall x, 0 < [|x|] ->
exists y, 0 <= y /\ [|x|] = (2 * y + 1) * (2 ^ [|tail031 x|]).
Proof.
intros.
rewrite tail031_equiv.
assert (nshiftr x size = 0%int31).
apply nshiftr_size.
revert x H H0.
induction size.
simpl Z.of_nat.
intros.
compute in H0; rewrite H0 in H; discriminate.
intros.
simpl tail031_alt.
case_eq (firstr x); intros.
rewrite (Nat2Z.inj_succ (tail031_alt n (shiftr x))), Z.pow_succ_r; auto with zarith.
destruct (IHn (shiftr x)) as (y & Hy1 & Hy2).
rewrite phi_nz; rewrite phi_nz in H; contradict H.
rewrite (sneakl_shiftr x), H1, H; auto.
rewrite <- nshiftr_S_tail; auto.
exists y; split; auto.
rewrite phi_eqn1; auto.
rewrite Z.double_spec, Hy2; ring.
exists [|shiftr x|].
split.
generalize (phi_bounded (shiftr x)); auto with zarith.
rewrite phi_eqn2; auto.
rewrite Z.succ_double_spec; simpl; ring.
Qed.
(* Sqrt *)
(* Direct transcription of an old proof
of a fortran program in boyer-moore *)
Lemma quotient_by_2 a: a - 1 <= (a/2) + (a/2).
Proof.
case (Z_mod_lt a 2); auto with zarith.
intros H1; rewrite Zmod_eq_full; auto with zarith.
Qed.
Lemma sqrt_main_trick j k: 0 <= j -> 0 <= k ->
(j * k) + j <= ((j + k)/2 + 1) ^ 2.
Proof.
intros Hj; generalize Hj k; pattern j; apply natlike_ind;
auto; clear k j Hj.
intros _ k Hk; repeat rewrite Z.add_0_l.
apply Z.mul_nonneg_nonneg; generalize (Z_div_pos k 2); auto with zarith.
intros j Hj Hrec _ k Hk; pattern k; apply natlike_ind; auto; clear k Hk.
rewrite Z.mul_0_r, Z.add_0_r, Z.add_0_l.
generalize (sqr_pos (Z.succ j / 2)) (quotient_by_2 (Z.succ j));
unfold Z.succ.
rewrite Z.pow_2_r, Z.mul_add_distr_r; repeat rewrite Z.mul_add_distr_l.
auto with zarith.
intros k Hk _.
replace ((Z.succ j + Z.succ k) / 2) with ((j + k)/2 + 1).
generalize (Hrec Hj k Hk) (quotient_by_2 (j + k)).
unfold Z.succ; repeat rewrite Z.pow_2_r;
repeat rewrite Z.mul_add_distr_r; repeat rewrite Z.mul_add_distr_l.
repeat rewrite Z.mul_1_l; repeat rewrite Z.mul_1_r.
auto with zarith.
rewrite Z.add_comm, <- Z_div_plus_full_l; auto with zarith.
apply f_equal2 with (f := Z.div); auto with zarith.
Qed.
Lemma sqrt_main i j: 0 <= i -> 0 < j -> i < ((j + (i/j))/2 + 1) ^ 2.
Proof.
intros Hi Hj.
assert (Hij: 0 <= i/j) by (apply Z_div_pos; auto with zarith).
apply Z.lt_le_trans with (2 := sqrt_main_trick _ _ (Z.lt_le_incl _ _ Hj) Hij).
pattern i at 1; rewrite (Z_div_mod_eq i j); case (Z_mod_lt i j); auto with zarith.
Qed.
Lemma sqrt_init i: 1 < i -> i < (i/2 + 1) ^ 2.
Proof.
intros Hi.
assert (H1: 0 <= i - 2) by auto with zarith.
assert (H2: 1 <= (i / 2) ^ 2); auto with zarith.
replace i with (1* 2 + (i - 2)); auto with zarith.
rewrite Z.pow_2_r, Z_div_plus_full_l; auto with zarith.
generalize (sqr_pos ((i - 2)/ 2)) (Z_div_pos (i - 2) 2).
rewrite Z.mul_add_distr_r; repeat rewrite Z.mul_add_distr_l.
auto with zarith.
generalize (quotient_by_2 i).
rewrite Z.pow_2_r in H2 |- *;
repeat (rewrite Z.mul_add_distr_r ||
rewrite Z.mul_add_distr_l ||
rewrite Z.mul_1_l || rewrite Z.mul_1_r).
auto with zarith.
Qed.
Lemma sqrt_test_true i j: 0 <= i -> 0 < j -> i/j >= j -> j ^ 2 <= i.
Proof.
intros Hi Hj Hd; rewrite Z.pow_2_r.
apply Z.le_trans with (j * (i/j)); auto with zarith.
apply Z_mult_div_ge; auto with zarith.
Qed.
Lemma sqrt_test_false i j: 0 <= i -> 0 < j -> i/j < j -> (j + (i/j))/2 < j.
Proof.
intros Hi Hj H; case (Z.le_gt_cases j ((j + (i/j))/2)); auto.
intros H1; contradict H; apply Z.le_ngt.
assert (2 * j <= j + (i/j)); auto with zarith.
apply Z.le_trans with (2 * ((j + (i/j))/2)); auto with zarith.
apply Z_mult_div_ge; auto with zarith.
Qed.
Lemma sqrt31_step_def rec i j:
sqrt31_step rec i j =
match (fst (i/j) ?= j)%int31 with
Lt => rec i (fst ((j + fst(i/j))/2))%int31
| _ => j
end.
Proof.
unfold sqrt31_step; case div31; intros.
simpl; case compare31; auto.
Qed.
Lemma div31_phi i j: 0 < [|j|] -> [|fst (i/j)%int31|] = [|i|]/[|j|].
intros Hj; generalize (spec_div i j Hj).
case div31; intros q r; simpl @fst.
intros (H1,H2); apply Zdiv_unique with [|r|]; auto with zarith.
rewrite H1; ring.
Qed.
Lemma sqrt31_step_correct rec i j:
0 < [|i|] -> 0 < [|j|] -> [|i|] < ([|j|] + 1) ^ 2 ->
2 * [|j|] < wB ->
(forall j1 : int31,
0 < [|j1|] < [|j|] -> [|i|] < ([|j1|] + 1) ^ 2 ->
[|rec i j1|] ^ 2 <= [|i|] < ([|rec i j1|] + 1) ^ 2) ->
[|sqrt31_step rec i j|] ^ 2 <= [|i|] < ([|sqrt31_step rec i j|] + 1) ^ 2.
Proof.
assert (Hp2: 0 < [|2|]) by exact (eq_refl Lt).
intros Hi Hj Hij H31 Hrec; rewrite sqrt31_step_def.
rewrite spec_compare, div31_phi; auto.
case Z.compare_spec; auto; intros Hc;
try (split; auto; apply sqrt_test_true; auto with zarith; fail).
apply Hrec; repeat rewrite div31_phi; auto with zarith.
replace [|(j + fst (i / j)%int31)|] with ([|j|] + [|i|] / [|j|]).
split.
apply Z.le_succ_l in Hj. change (1 <= [|j|]) in Hj.
Z.le_elim Hj.
replace ([|j|] + [|i|]/[|j|]) with
(1 * 2 + (([|j|] - 2) + [|i|] / [|j|])); try ring.
rewrite Z_div_plus_full_l; auto with zarith.
assert (0 <= [|i|]/ [|j|]) by (apply Z_div_pos; auto with zarith).
assert (0 <= ([|j|] - 2 + [|i|] / [|j|]) / [|2|]) ; auto with zarith.
rewrite <- Hj, Zdiv_1_r.
replace (1 + [|i|])%Z with (1 * 2 + ([|i|] - 1))%Z; try ring.
rewrite Z_div_plus_full_l; auto with zarith.
assert (0 <= ([|i|] - 1) /2)%Z by (apply Z_div_pos; auto with zarith).
change ([|2|]) with 2%Z; auto with zarith.
apply sqrt_test_false; auto with zarith.
rewrite spec_add, div31_phi; auto.
symmetry; apply Zmod_small.
split; auto with zarith.
replace [|j + fst (i / j)%int31|] with ([|j|] + [|i|] / [|j|]).
apply sqrt_main; auto with zarith.
rewrite spec_add, div31_phi; auto.
symmetry; apply Zmod_small.
split; auto with zarith.
Qed.
Lemma iter31_sqrt_correct n rec i j: 0 < [|i|] -> 0 < [|j|] ->
[|i|] < ([|j|] + 1) ^ 2 -> 2 * [|j|] < 2 ^ (Z.of_nat size) ->
(forall j1, 0 < [|j1|] -> 2^(Z.of_nat n) + [|j1|] <= [|j|] ->
[|i|] < ([|j1|] + 1) ^ 2 -> 2 * [|j1|] < 2 ^ (Z.of_nat size) ->
[|rec i j1|] ^ 2 <= [|i|] < ([|rec i j1|] + 1) ^ 2) ->
[|iter31_sqrt n rec i j|] ^ 2 <= [|i|] < ([|iter31_sqrt n rec i j|] + 1) ^ 2.
Proof.
revert rec i j; elim n; unfold iter31_sqrt; fold iter31_sqrt; clear n.
intros rec i j Hi Hj Hij H31 Hrec; apply sqrt31_step_correct; auto with zarith.
intros; apply Hrec; auto with zarith.
rewrite Z.pow_0_r; auto with zarith.
intros n Hrec rec i j Hi Hj Hij H31 HHrec.
apply sqrt31_step_correct; auto.
intros j1 Hj1 Hjp1; apply Hrec; auto with zarith.
intros j2 Hj2 H2j2 Hjp2 Hj31; apply Hrec; auto with zarith.
intros j3 Hj3 Hpj3.
apply HHrec; auto.
rewrite Nat2Z.inj_succ, Z.pow_succ_r.
apply Z.le_trans with (2 ^Z.of_nat n + [|j2|]); auto with zarith.
apply Nat2Z.is_nonneg.
Qed.
Lemma spec_sqrt : forall x,
[|sqrt31 x|] ^ 2 <= [|x|] < ([|sqrt31 x|] + 1) ^ 2.
Proof.
intros i; unfold sqrt31.
rewrite spec_compare. case Z.compare_spec; change [|1|] with 1;
intros Hi; auto with zarith.
repeat rewrite Z.pow_2_r; auto with zarith.
apply iter31_sqrt_correct; auto with zarith.
rewrite div31_phi; change ([|2|]) with 2; auto with zarith.
replace ([|i|]) with (1 * 2 + ([|i|] - 2))%Z; try ring.
assert (0 <= ([|i|] - 2)/2)%Z by (apply Z_div_pos; auto with zarith).
rewrite Z_div_plus_full_l; auto with zarith.
rewrite div31_phi; change ([|2|]) with 2; auto with zarith.
apply sqrt_init; auto.
rewrite div31_phi; change ([|2|]) with 2; auto with zarith.
apply Z.le_lt_trans with ([|i|]).
apply Z_mult_div_ge; auto with zarith.
case (phi_bounded i); auto.
intros j2 H1 H2; contradict H2; apply Z.lt_nge.
rewrite div31_phi; change ([|2|]) with 2; auto with zarith.
apply Z.le_lt_trans with ([|i|]); auto with zarith.
assert (0 <= [|i|]/2)%Z by (apply Z_div_pos; auto with zarith).
apply Z.le_trans with (2 * ([|i|]/2)); auto with zarith.
apply Z_mult_div_ge; auto with zarith.
case (phi_bounded i); unfold size; auto with zarith.
change [|0|] with 0; auto with zarith.
case (phi_bounded i); repeat rewrite Z.pow_2_r; auto with zarith.
Qed.
Lemma sqrt312_step_def rec ih il j:
sqrt312_step rec ih il j =
match (ih ?= j)%int31 with
Eq => j
| Gt => j
| _ =>
match (fst (div3121 ih il j) ?= j)%int31 with
Lt => let m := match j +c fst (div3121 ih il j) with
C0 m1 => fst (m1/2)%int31
| C1 m1 => (fst (m1/2) + v30)%int31
end in rec ih il m
| _ => j
end
end.
Proof.
unfold sqrt312_step; case div3121; intros.
simpl; case compare31; auto.
Qed.
Lemma sqrt312_lower_bound ih il j:
phi2 ih il < ([|j|] + 1) ^ 2 -> [|ih|] <= [|j|].
Proof.
intros H1.
case (phi_bounded j); intros Hbj _.
case (phi_bounded il); intros Hbil _.
case (phi_bounded ih); intros Hbih Hbih1.
assert (([|ih|] < [|j|] + 1)%Z); auto with zarith.
apply Z.square_lt_simpl_nonneg; auto with zarith.
repeat rewrite <-Z.pow_2_r; apply Z.le_lt_trans with (2 := H1).
apply Z.le_trans with ([|ih|] * base)%Z; unfold phi2, base;
try rewrite Z.pow_2_r; auto with zarith.
Qed.
Lemma div312_phi ih il j: (2^30 <= [|j|] -> [|ih|] < [|j|] ->
[|fst (div3121 ih il j)|] = phi2 ih il/[|j|])%Z.
Proof.
intros Hj Hj1.
generalize (spec_div21 ih il j Hj Hj1).
case div3121; intros q r (Hq, Hr).
apply Zdiv_unique with (phi r); auto with zarith.
simpl @fst; apply eq_trans with (1 := Hq); ring.
Qed.
Lemma sqrt312_step_correct rec ih il j:
2 ^ 29 <= [|ih|] -> 0 < [|j|] -> phi2 ih il < ([|j|] + 1) ^ 2 ->
(forall j1, 0 < [|j1|] < [|j|] -> phi2 ih il < ([|j1|] + 1) ^ 2 ->
[|rec ih il j1|] ^ 2 <= phi2 ih il < ([|rec ih il j1|] + 1) ^ 2) ->
[|sqrt312_step rec ih il j|] ^ 2 <= phi2 ih il
< ([|sqrt312_step rec ih il j|] + 1) ^ 2.
Proof.
assert (Hp2: (0 < [|2|])%Z) by exact (eq_refl Lt).
intros Hih Hj Hij Hrec; rewrite sqrt312_step_def.
assert (H1: ([|ih|] <= [|j|])%Z) by (apply sqrt312_lower_bound with il; auto).
case (phi_bounded ih); intros Hih1 _.
case (phi_bounded il); intros Hil1 _.
case (phi_bounded j); intros _ Hj1.
assert (Hp3: (0 < phi2 ih il)).
unfold phi2; apply Z.lt_le_trans with ([|ih|] * base)%Z; auto with zarith.
apply Z.mul_pos_pos; auto with zarith.
apply Z.lt_le_trans with (2:= Hih); auto with zarith.
rewrite spec_compare. case Z.compare_spec; intros Hc1.
split; auto.
apply sqrt_test_true; auto.
unfold phi2, base; auto with zarith.
unfold phi2; rewrite Hc1.
assert (0 <= [|il|]/[|j|]) by (apply Z_div_pos; auto with zarith).
rewrite Z.mul_comm, Z_div_plus_full_l; unfold base; auto with zarith.
simpl wB in Hj1. unfold Z.pow_pos in Hj1. simpl in Hj1. auto with zarith.
case (Z.le_gt_cases (2 ^ 30) [|j|]); intros Hjj.
rewrite spec_compare; case Z.compare_spec;
rewrite div312_phi; auto; intros Hc;
try (split; auto; apply sqrt_test_true; auto with zarith; fail).
apply Hrec.
assert (Hf1: 0 <= phi2 ih il/ [|j|]) by (apply Z_div_pos; auto with zarith).
apply Z.le_succ_l in Hj. change (1 <= [|j|]) in Hj.
Z.le_elim Hj.
2: contradict Hc; apply Z.le_ngt; rewrite <- Hj, Zdiv_1_r; auto with zarith.
assert (Hf3: 0 < ([|j|] + phi2 ih il / [|j|]) / 2).
replace ([|j|] + phi2 ih il/ [|j|])%Z with
(1 * 2 + (([|j|] - 2) + phi2 ih il / [|j|])); try ring.
rewrite Z_div_plus_full_l; auto with zarith.
assert (0 <= ([|j|] - 2 + phi2 ih il / [|j|]) / 2) ; auto with zarith.
assert (Hf4: ([|j|] + phi2 ih il / [|j|]) / 2 < [|j|]).
apply sqrt_test_false; auto with zarith.
generalize (spec_add_c j (fst (div3121 ih il j))).
unfold interp_carry; case add31c; intros r;
rewrite div312_phi; auto with zarith.
rewrite div31_phi; change [|2|] with 2%Z; auto with zarith.
intros HH; rewrite HH; clear HH; auto with zarith.
rewrite spec_add, div31_phi; change [|2|] with 2%Z; auto.
rewrite Z.mul_1_l; intros HH.
rewrite Z.add_comm, <- Z_div_plus_full_l; auto with zarith.
change (phi v30 * 2) with (2 ^ Z.of_nat size).
rewrite HH, Zmod_small; auto with zarith.
replace (phi
match j +c fst (div3121 ih il j) with
| C0 m1 => fst (m1 / 2)%int31
| C1 m1 => fst (m1 / 2)%int31 + v30
end) with ((([|j|] + (phi2 ih il)/([|j|]))/2)).
apply sqrt_main; auto with zarith.
generalize (spec_add_c j (fst (div3121 ih il j))).
unfold interp_carry; case add31c; intros r;
rewrite div312_phi; auto with zarith.
rewrite div31_phi; auto with zarith.
intros HH; rewrite HH; auto with zarith.
intros HH; rewrite <- HH.
change (1 * 2 ^ Z.of_nat size) with (phi (v30) * 2).
rewrite Z_div_plus_full_l; auto with zarith.
rewrite Z.add_comm.
rewrite spec_add, Zmod_small.
rewrite div31_phi; auto.
split; auto with zarith.
case (phi_bounded (fst (r/2)%int31));
case (phi_bounded v30); auto with zarith.
rewrite div31_phi; change (phi 2) with 2%Z; auto.
change (2 ^Z.of_nat size) with (base/2 + phi v30).
assert (phi r / 2 < base/2); auto with zarith.
apply Z.mul_lt_mono_pos_r with 2; auto with zarith.
change (base/2 * 2) with base.
apply Z.le_lt_trans with (phi r).
rewrite Z.mul_comm; apply Z_mult_div_ge; auto with zarith.
case (phi_bounded r); auto with zarith.
contradict Hij; apply Z.le_ngt.
assert ((1 + [|j|]) <= 2 ^ 30); auto with zarith.
apply Z.le_trans with ((2 ^ 30) * (2 ^ 30)); auto with zarith.
assert (0 <= 1 + [|j|]); auto with zarith.
apply Z.mul_le_mono_nonneg; auto with zarith.
change ((2 ^ 30) * (2 ^ 30)) with ((2 ^ 29) * base).
apply Z.le_trans with ([|ih|] * base); auto with zarith.
unfold phi2, base; auto with zarith.
split; auto.
apply sqrt_test_true; auto.
unfold phi2, base; auto with zarith.
apply Z.le_ge; apply Z.le_trans with (([|j|] * base)/[|j|]).
rewrite Z.mul_comm, Z_div_mult; auto with zarith.
apply Z.ge_le; apply Z_div_ge; auto with zarith.
Qed.
Lemma iter312_sqrt_correct n rec ih il j:
2^29 <= [|ih|] -> 0 < [|j|] -> phi2 ih il < ([|j|] + 1) ^ 2 ->
(forall j1, 0 < [|j1|] -> 2^(Z.of_nat n) + [|j1|] <= [|j|] ->
phi2 ih il < ([|j1|] + 1) ^ 2 ->
[|rec ih il j1|] ^ 2 <= phi2 ih il < ([|rec ih il j1|] + 1) ^ 2) ->
[|iter312_sqrt n rec ih il j|] ^ 2 <= phi2 ih il
< ([|iter312_sqrt n rec ih il j|] + 1) ^ 2.
Proof.
revert rec ih il j; elim n; unfold iter312_sqrt; fold iter312_sqrt; clear n.
intros rec ih il j Hi Hj Hij Hrec; apply sqrt312_step_correct; auto with zarith.
intros; apply Hrec; auto with zarith.
rewrite Z.pow_0_r; auto with zarith.
intros n Hrec rec ih il j Hi Hj Hij HHrec.
apply sqrt312_step_correct; auto.
intros j1 Hj1 Hjp1; apply Hrec; auto with zarith.
intros j2 Hj2 H2j2 Hjp2; apply Hrec; auto with zarith.
intros j3 Hj3 Hpj3.
apply HHrec; auto.
rewrite Nat2Z.inj_succ, Z.pow_succ_r.
apply Z.le_trans with (2 ^Z.of_nat n + [|j2|])%Z; auto with zarith.
apply Nat2Z.is_nonneg.
Qed.
(* Avoid expanding [iter312_sqrt] before variables in the context. *)
Strategy 1 [iter312_sqrt].
Lemma spec_sqrt2 : forall x y,
wB/ 4 <= [|x|] ->
let (s,r) := sqrt312 x y in
[||WW x y||] = [|s|] ^ 2 + [+|r|] /\
[+|r|] <= 2 * [|s|].
Proof.
intros ih il Hih; unfold sqrt312.
change [||WW ih il||] with (phi2 ih il).
assert (Hbin: forall s, s * s + 2* s + 1 = (s + 1) ^ 2) by
(intros s; ring).
assert (Hb: 0 <= base) by (red; intros HH; discriminate).
assert (Hi2: phi2 ih il < (phi Tn + 1) ^ 2).
{ change ((phi Tn + 1) ^ 2) with (2^62).
apply Z.le_lt_trans with ((2^31 -1) * base + (2^31 - 1)); auto with zarith.
2: simpl; unfold Z.pow_pos; simpl; auto with zarith.
case (phi_bounded ih); case (phi_bounded il); intros H1 H2 H3 H4.
unfold base, Z.pow, Z.pow_pos in H2,H4; simpl in H2,H4.
unfold phi2. cbn [Z.pow Z.pow_pos Pos.iter]. auto with zarith. }
case (iter312_sqrt_correct 31 (fun _ _ j => j) ih il Tn); auto with zarith.
change [|Tn|] with 2147483647; auto with zarith.
intros j1 _ HH; contradict HH.
apply Z.lt_nge.
change [|Tn|] with 2147483647; auto with zarith.
change (2 ^ Z.of_nat 31) with 2147483648; auto with zarith.
case (phi_bounded j1); auto with zarith.
set (s := iter312_sqrt 31 (fun _ _ j : int31 => j) ih il Tn).
intros Hs1 Hs2.
generalize (spec_mul_c s s); case mul31c.
simpl zn2z_to_Z; intros HH.
assert ([|s|] = 0).
{ symmetry in HH. rewrite Z.mul_eq_0 in HH. destruct HH; auto. }
contradict Hs2; apply Z.le_ngt; rewrite H.
change ((0 + 1) ^ 2) with 1.
apply Z.le_trans with (2 ^ Z.of_nat size / 4 * base).
simpl; auto with zarith.
apply Z.le_trans with ([|ih|] * base); auto with zarith.
unfold phi2; case (phi_bounded il); auto with zarith.
intros ih1 il1.
change [||WW ih1 il1||] with (phi2 ih1 il1).
intros Hihl1.
generalize (spec_sub_c il il1).
case sub31c; intros il2 Hil2.
rewrite spec_compare; case Z.compare_spec.
unfold interp_carry in *.
intros H1; split.
rewrite Z.pow_2_r, <- Hihl1.
unfold phi2; ring[Hil2 H1].
replace [|il2|] with (phi2 ih il - phi2 ih1 il1).
rewrite Hihl1.
rewrite <-Hbin in Hs2; auto with zarith.
unfold phi2; rewrite H1, Hil2; ring.
unfold interp_carry.
intros H1; contradict Hs1.
apply Z.lt_nge; rewrite Z.pow_2_r, <-Hihl1.
unfold phi2.
case (phi_bounded il); intros _ H2.
apply Z.lt_le_trans with (([|ih|] + 1) * base + 0).
rewrite Z.mul_add_distr_r, Z.add_0_r; auto with zarith.
case (phi_bounded il1); intros H3 _.
apply Z.add_le_mono; auto with zarith.
unfold interp_carry in *; change (1 * 2 ^ Z.of_nat size) with base.
rewrite Z.pow_2_r, <- Hihl1, Hil2.
intros H1.
rewrite <- Z.le_succ_l, <- Z.add_1_r in H1.
Z.le_elim H1.
contradict Hs2; apply Z.le_ngt.
replace (([|s|] + 1) ^ 2) with (phi2 ih1 il1 + 2 * [|s|] + 1).
unfold phi2.
case (phi_bounded il); intros Hpil _.
assert (Hl1l: [|il1|] <= [|il|]).
{ case (phi_bounded il2); rewrite Hil2; auto with zarith. }
assert ([|ih1|] * base + 2 * [|s|] + 1 <= [|ih|] * base); auto with zarith.
case (phi_bounded s); change (2 ^ Z.of_nat size) with base; intros _ Hps.
case (phi_bounded ih1); intros Hpih1 _; auto with zarith.
apply Z.le_trans with (([|ih1|] + 2) * base); auto with zarith.
rewrite Z.mul_add_distr_r.
assert (2 * [|s|] + 1 <= 2 * base); auto with zarith.
rewrite Hihl1, Hbin; auto.
split.
unfold phi2; rewrite <- H1; ring.
replace (base + ([|il|] - [|il1|])) with (phi2 ih il - ([|s|] * [|s|])).
rewrite <-Hbin in Hs2; auto with zarith.
rewrite <- Hihl1; unfold phi2; rewrite <- H1; ring.
unfold interp_carry in Hil2 |- *.
unfold interp_carry; change (1 * 2 ^ Z.of_nat size) with base.
assert (Hsih: [|ih - 1|] = [|ih|] - 1).
{ rewrite spec_sub, Zmod_small; auto; change [|1|] with 1.
case (phi_bounded ih); intros H1 H2.
generalize Hih; change (2 ^ Z.of_nat size / 4) with 536870912.
split; auto with zarith. }
rewrite spec_compare; case Z.compare_spec.
rewrite Hsih.
intros H1; split.
rewrite Z.pow_2_r, <- Hihl1.
unfold phi2; rewrite <-H1.
transitivity ([|ih|] * base + [|il1|] + ([|il|] - [|il1|])).
ring.
rewrite <-Hil2.
change (2 ^ Z.of_nat size) with base; ring.
replace [|il2|] with (phi2 ih il - phi2 ih1 il1).
rewrite Hihl1.
rewrite <-Hbin in Hs2; auto with zarith.
unfold phi2.
rewrite <-H1.
ring_simplify.
transitivity (base + ([|il|] - [|il1|])).
ring.
rewrite <-Hil2.
change (2 ^ Z.of_nat size) with base; ring.
rewrite Hsih; intros H1.
assert (He: [|ih|] = [|ih1|]).
{ apply Z.le_antisymm; auto with zarith.
case (Z.le_gt_cases [|ih1|] [|ih|]); auto; intros H2.
contradict Hs1; apply Z.lt_nge; rewrite Z.pow_2_r, <-Hihl1.
unfold phi2.
case (phi_bounded il); change (2 ^ Z.of_nat size) with base;
intros _ Hpil1.
apply Z.lt_le_trans with (([|ih|] + 1) * base).
rewrite Z.mul_add_distr_r, Z.mul_1_l; auto with zarith.
case (phi_bounded il1); intros Hpil2 _.
apply Z.le_trans with (([|ih1|]) * base); auto with zarith. }
rewrite Z.pow_2_r, <-Hihl1; unfold phi2; rewrite <-He.
contradict Hs1; apply Z.lt_nge; rewrite Z.pow_2_r, <-Hihl1.
unfold phi2; rewrite He.
assert (phi il - phi il1 < 0); auto with zarith.
rewrite <-Hil2.
case (phi_bounded il2); auto with zarith.
intros H1.
rewrite Z.pow_2_r, <-Hihl1.
assert (H2 : [|ih1|]+2 <= [|ih|]); auto with zarith.
Z.le_elim H2.
contradict Hs2; apply Z.le_ngt.
replace (([|s|] + 1) ^ 2) with (phi2 ih1 il1 + 2 * [|s|] + 1).
unfold phi2.
assert ([|ih1|] * base + 2 * phi s + 1 <= [|ih|] * base + ([|il|] - [|il1|]));
auto with zarith.
rewrite <-Hil2.
change (-1 * 2 ^ Z.of_nat size) with (-base).
case (phi_bounded il2); intros Hpil2 _.
apply Z.le_trans with ([|ih|] * base + - base); auto with zarith.
case (phi_bounded s); change (2 ^ Z.of_nat size) with base; intros _ Hps.
assert (2 * [|s|] + 1 <= 2 * base); auto with zarith.
apply Z.le_trans with ([|ih1|] * base + 2 * base); auto with zarith.
assert (Hi: ([|ih1|] + 3) * base <= [|ih|] * base); auto with zarith.
rewrite Z.mul_add_distr_r in Hi; auto with zarith.
rewrite Hihl1, Hbin; auto.
unfold phi2; rewrite <-H2.
split.
replace [|il|] with (([|il|] - [|il1|]) + [|il1|]); try ring.
rewrite <-Hil2.
change (-1 * 2 ^ Z.of_nat size) with (-base); ring.
replace (base + [|il2|]) with (phi2 ih il - phi2 ih1 il1).
rewrite Hihl1.
rewrite <-Hbin in Hs2; auto with zarith.
unfold phi2; rewrite <-H2.
replace [|il|] with (([|il|] - [|il1|]) + [|il1|]); try ring.
rewrite <-Hil2.
change (-1 * 2 ^ Z.of_nat size) with (-base); ring.
Qed.
(** [iszero] *)
Lemma spec_eq0 : forall x, ZnZ.eq0 x = true -> [|x|] = 0.
Proof.
clear; unfold ZnZ.eq0, int31_ops.
unfold compare31; intros.
change [|0|] with 0 in H.
apply Z.compare_eq.
now destruct ([|x|] ?= 0).
Qed.
(* Even *)
Lemma spec_is_even : forall x,
if ZnZ.is_even x then [|x|] mod 2 = 0 else [|x|] mod 2 = 1.
Proof.
unfold ZnZ.is_even, int31_ops; intros.
generalize (spec_div x 2).
destruct (x/2)%int31 as (q,r); intros.
unfold compare31.
change [|2|] with 2 in H.
change [|0|] with 0.
destruct H; auto with zarith.
replace ([|x|] mod 2) with [|r|].
destruct H; auto with zarith.
case Z.compare_spec; auto with zarith.
apply Zmod_unique with [|q|]; auto with zarith.
Qed.
(* Bitwise *)
Lemma log2_phi_bounded x : Z.log2 [|x|] < Z.of_nat size.
Proof.
destruct (phi_bounded x) as (H,H').
Z.le_elim H.
- now apply Z.log2_lt_pow2.
- now rewrite <- H.
Qed.
Lemma spec_lor x y : [| ZnZ.lor x y |] = Z.lor [|x|] [|y|].
Proof.
unfold ZnZ.lor,int31_ops. unfold lor31.
rewrite phi_phi_inv.
apply Z.mod_small; split; trivial.
- apply Z.lor_nonneg; split; apply phi_bounded.
- apply Z.log2_lt_cancel. rewrite Z.log2_pow2 by easy.
rewrite Z.log2_lor; try apply phi_bounded.
apply Z.max_lub_lt; apply log2_phi_bounded.
Qed.
Lemma spec_land x y : [| ZnZ.land x y |] = Z.land [|x|] [|y|].
Proof.
unfold ZnZ.land, int31_ops. unfold land31.
rewrite phi_phi_inv.
apply Z.mod_small; split; trivial.
- apply Z.land_nonneg; left; apply phi_bounded.
- apply Z.log2_lt_cancel. rewrite Z.log2_pow2 by easy.
eapply Z.le_lt_trans.
apply Z.log2_land; try apply phi_bounded.
apply Z.min_lt_iff; left; apply log2_phi_bounded.
Qed.
Lemma spec_lxor x y : [| ZnZ.lxor x y |] = Z.lxor [|x|] [|y|].
Proof.
unfold ZnZ.lxor, int31_ops. unfold lxor31.
rewrite phi_phi_inv.
apply Z.mod_small; split; trivial.
- apply Z.lxor_nonneg; split; intros; apply phi_bounded.
- apply Z.log2_lt_cancel. rewrite Z.log2_pow2 by easy.
eapply Z.le_lt_trans.
apply Z.log2_lxor; try apply phi_bounded.
apply Z.max_lub_lt; apply log2_phi_bounded.
Qed.
Global Instance int31_specs : ZnZ.Specs int31_ops := {
spec_to_Z := phi_bounded;
spec_of_pos := positive_to_int31_spec;
spec_zdigits := spec_zdigits;
spec_more_than_1_digit := spec_more_than_1_digit;
spec_0 := spec_0;
spec_1 := spec_1;
spec_m1 := spec_m1;
spec_compare := spec_compare;
spec_eq0 := spec_eq0;
spec_opp_c := spec_opp_c;
spec_opp := spec_opp;
spec_opp_carry := spec_opp_carry;
spec_succ_c := spec_succ_c;
spec_add_c := spec_add_c;
spec_add_carry_c := spec_add_carry_c;
spec_succ := spec_succ;
spec_add := spec_add;
spec_add_carry := spec_add_carry;
spec_pred_c := spec_pred_c;
spec_sub_c := spec_sub_c;
spec_sub_carry_c := spec_sub_carry_c;
spec_pred := spec_pred;
spec_sub := spec_sub;
spec_sub_carry := spec_sub_carry;
spec_mul_c := spec_mul_c;
spec_mul := spec_mul;
spec_square_c := spec_square_c;
spec_div21 := spec_div21;
spec_div_gt := fun a b _ => spec_div a b;
spec_div := spec_div;
spec_modulo_gt := fun a b _ => spec_mod a b;
spec_modulo := spec_mod;
spec_gcd_gt := fun a b _ => spec_gcd a b;
spec_gcd := spec_gcd;
spec_head00 := spec_head00;
spec_head0 := spec_head0;
spec_tail00 := spec_tail00;
spec_tail0 := spec_tail0;
spec_add_mul_div := spec_add_mul_div;
spec_pos_mod := spec_pos_mod;
spec_is_even := spec_is_even;
spec_sqrt2 := spec_sqrt2;
spec_sqrt := spec_sqrt;
spec_lor := spec_lor;
spec_land := spec_land;
spec_lxor := spec_lxor }.
End Int31_Specs.
Module Int31Cyclic <: CyclicType.
Definition t := int31.
Definition ops := int31_ops.
Definition specs := int31_specs.
End Int31Cyclic.
|
(************************************************************************)
(* v * The Coq Proof Assistant / The Coq Development Team *)
(* <O___,, * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2015 *)
(* \VV/ **************************************************************)
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
(** * Int31 numbers defines indeed a cyclic structure : Z/(2^31)Z *)
(**
Author: Arnaud Spiwack (+ Pierre Letouzey)
*)
Require Import List.
Require Import Min.
Require Export Int31.
Require Import Znumtheory.
Require Import Zgcd_alt.
Require Import Zpow_facts.
Require Import BigNumPrelude.
Require Import CyclicAxioms.
Require Import ROmega.
Local Open Scope nat_scope.
Local Open Scope int31_scope.
Section Basics.
(** * Basic results about [iszero], [shiftl], [shiftr] *)
Lemma iszero_eq0 : forall x, iszero x = true -> x=0.
Proof.
destruct x; simpl; intros.
repeat
match goal with H:(if ?d then _ else _) = true |- _ =>
destruct d; try discriminate
end.
reflexivity.
Qed.
Lemma iszero_not_eq0 : forall x, iszero x = false -> x<>0.
Proof.
intros x H Eq; rewrite Eq in H; simpl in *; discriminate.
Qed.
Lemma sneakl_shiftr : forall x,
x = sneakl (firstr x) (shiftr x).
Proof.
destruct x; simpl; auto.
Qed.
Lemma sneakr_shiftl : forall x,
x = sneakr (firstl x) (shiftl x).
Proof.
destruct x; simpl; auto.
Qed.
Lemma twice_zero : forall x,
twice x = 0 <-> twice_plus_one x = 1.
Proof.
destruct x; simpl in *; split;
intro H; injection H; intros; subst; auto.
Qed.
Lemma twice_or_twice_plus_one : forall x,
x = twice (shiftr x) \/ x = twice_plus_one (shiftr x).
Proof.
intros; case_eq (firstr x); intros.
destruct x; simpl in *; rewrite H; auto.
destruct x; simpl in *; rewrite H; auto.
Qed.
(** * Iterated shift to the right *)
Definition nshiftr x := nat_rect _ x (fun _ => shiftr).
Lemma nshiftr_S :
forall n x, nshiftr x (S n) = shiftr (nshiftr x n).
Proof.
reflexivity.
Qed.
Lemma nshiftr_S_tail :
forall n x, nshiftr x (S n) = nshiftr (shiftr x) n.
Proof.
intros n; elim n; simpl; auto.
intros; now f_equal.
Qed.
Lemma nshiftr_n_0 : forall n, nshiftr 0 n = 0.
Proof.
induction n; simpl; auto.
rewrite IHn; auto.
Qed.
Lemma nshiftr_size : forall x, nshiftr x size = 0.
Proof.
destruct x; simpl; auto.
Qed.
Lemma nshiftr_above_size : forall k x, size<=k ->
nshiftr x k = 0.
Proof.
intros.
replace k with ((k-size)+size)%nat by omega.
induction (k-size)%nat; auto.
rewrite nshiftr_size; auto.
simpl; rewrite IHn; auto.
Qed.
(** * Iterated shift to the left *)
Definition nshiftl x := nat_rect _ x (fun _ => shiftl).
Lemma nshiftl_S :
forall n x, nshiftl x (S n) = shiftl (nshiftl x n).
Proof.
reflexivity.
Qed.
Lemma nshiftl_S_tail :
forall n x, nshiftl x (S n) = nshiftl (shiftl x) n.
Proof.
intros n; elim n; simpl; intros; now f_equal.
Qed.
Lemma nshiftl_n_0 : forall n, nshiftl 0 n = 0.
Proof.
induction n; simpl; auto.
rewrite IHn; auto.
Qed.
Lemma nshiftl_size : forall x, nshiftl x size = 0.
Proof.
destruct x; simpl; auto.
Qed.
Lemma nshiftl_above_size : forall k x, size<=k ->
nshiftl x k = 0.
Proof.
intros.
replace k with ((k-size)+size)%nat by omega.
induction (k-size)%nat; auto.
rewrite nshiftl_size; auto.
simpl; rewrite IHn; auto.
Qed.
Lemma firstr_firstl :
forall x, firstr x = firstl (nshiftl x (pred size)).
Proof.
destruct x; simpl; auto.
Qed.
Lemma firstl_firstr :
forall x, firstl x = firstr (nshiftr x (pred size)).
Proof.
destruct x; simpl; auto.
Qed.
(** More advanced results about [nshiftr] *)
Lemma nshiftr_predsize_0_firstl : forall x,
nshiftr x (pred size) = 0 -> firstl x = D0.
Proof.
destruct x; compute; intros H; injection H; intros; subst; auto.
Qed.
Lemma nshiftr_0_propagates : forall n p x, n <= p ->
nshiftr x n = 0 -> nshiftr x p = 0.
Proof.
intros.
replace p with ((p-n)+n)%nat by omega.
induction (p-n)%nat.
simpl; auto.
simpl; rewrite IHn0; auto.
Qed.
Lemma nshiftr_0_firstl : forall n x, n < size ->
nshiftr x n = 0 -> firstl x = D0.
Proof.
intros.
apply nshiftr_predsize_0_firstl.
apply nshiftr_0_propagates with n; auto; omega.
Qed.
(** * Some induction principles over [int31] *)
(** Not used for the moment. Are they really useful ? *)
Lemma int31_ind_sneakl : forall P : int31->Prop,
P 0 ->
(forall x d, P x -> P (sneakl d x)) ->
forall x, P x.
Proof.
intros.
assert (forall n, n<=size -> P (nshiftr x (size - n))).
induction n; intros.
rewrite nshiftr_size; auto.
rewrite sneakl_shiftr.
apply H0.
change (P (nshiftr x (S (size - S n)))).
replace (S (size - S n))%nat with (size - n)%nat by omega.
apply IHn; omega.
change x with (nshiftr x (size-size)); auto.
Qed.
Lemma int31_ind_twice : forall P : int31->Prop,
P 0 ->
(forall x, P x -> P (twice x)) ->
(forall x, P x -> P (twice_plus_one x)) ->
forall x, P x.
Proof.
induction x using int31_ind_sneakl; auto.
destruct d; auto.
Qed.
(** * Some generic results about [recr] *)
Section Recr.
(** [recr] satisfies the fixpoint equation used for its definition. *)
Variable (A:Type)(case0:A)(caserec:digits->int31->A->A).
Lemma recr_aux_eqn : forall n x, iszero x = false ->
recr_aux (S n) A case0 caserec x =
caserec (firstr x) (shiftr x) (recr_aux n A case0 caserec (shiftr x)).
Proof.
intros; simpl; rewrite H; auto.
Qed.
Lemma recr_aux_converges :
forall n p x, n <= size -> n <= p ->
recr_aux n A case0 caserec (nshiftr x (size - n)) =
recr_aux p A case0 caserec (nshiftr x (size - n)).
Proof.
induction n.
simpl minus; intros.
rewrite nshiftr_size; destruct p; simpl; auto.
intros.
destruct p.
inversion H0.
unfold recr_aux; fold recr_aux.
destruct (iszero (nshiftr x (size - S n))); auto.
f_equal.
change (shiftr (nshiftr x (size - S n))) with (nshiftr x (S (size - S n))).
replace (S (size - S n))%nat with (size - n)%nat by omega.
apply IHn; auto with arith.
Qed.
Lemma recr_eqn : forall x, iszero x = false ->
recr A case0 caserec x =
caserec (firstr x) (shiftr x) (recr A case0 caserec (shiftr x)).
Proof.
intros.
unfold recr.
change x with (nshiftr x (size - size)).
rewrite (recr_aux_converges size (S size)); auto with arith.
rewrite recr_aux_eqn; auto.
Qed.
(** [recr] is usually equivalent to a variant [recrbis]
written without [iszero] check. *)
Fixpoint recrbis_aux (n:nat)(A:Type)(case0:A)(caserec:digits->int31->A->A)
(i:int31) : A :=
match n with
| O => case0
| S next =>
let si := shiftr i in
caserec (firstr i) si (recrbis_aux next A case0 caserec si)
end.
Definition recrbis := recrbis_aux size.
Hypothesis case0_caserec : caserec D0 0 case0 = case0.
Lemma recrbis_aux_equiv : forall n x,
recrbis_aux n A case0 caserec x = recr_aux n A case0 caserec x.
Proof.
induction n; simpl; auto; intros.
case_eq (iszero x); intros; [ | f_equal; auto ].
rewrite (iszero_eq0 _ H); simpl; auto.
replace (recrbis_aux n A case0 caserec 0) with case0; auto.
clear H IHn; induction n; simpl; congruence.
Qed.
Lemma recrbis_equiv : forall x,
recrbis A case0 caserec x = recr A case0 caserec x.
Proof.
intros; apply recrbis_aux_equiv; auto.
Qed.
End Recr.
(** * Incrementation *)
Section Incr.
(** Variant of [incr] via [recrbis] *)
Let Incr (b : digits) (si rec : int31) :=
match b with
| D0 => sneakl D1 si
| D1 => sneakl D0 rec
end.
Definition incrbis_aux n x := recrbis_aux n _ In Incr x.
Lemma incrbis_aux_equiv : forall x, incrbis_aux size x = incr x.
Proof.
unfold incr, recr, incrbis_aux; fold Incr; intros.
apply recrbis_aux_equiv; auto.
Qed.
(** Recursive equations satisfied by [incr] *)
Lemma incr_eqn1 :
forall x, firstr x = D0 -> incr x = twice_plus_one (shiftr x).
Proof.
intros.
case_eq (iszero x); intros.
rewrite (iszero_eq0 _ H0); simpl; auto.
unfold incr; rewrite recr_eqn; fold incr; auto.
rewrite H; auto.
Qed.
Lemma incr_eqn2 :
forall x, firstr x = D1 -> incr x = twice (incr (shiftr x)).
Proof.
intros.
case_eq (iszero x); intros.
rewrite (iszero_eq0 _ H0) in H; simpl in H; discriminate.
unfold incr; rewrite recr_eqn; fold incr; auto.
rewrite H; auto.
Qed.
Lemma incr_twice : forall x, incr (twice x) = twice_plus_one x.
Proof.
intros.
rewrite incr_eqn1; destruct x; simpl; auto.
Qed.
Lemma incr_twice_plus_one_firstl :
forall x, firstl x = D0 -> incr (twice_plus_one x) = twice (incr x).
Proof.
intros.
rewrite incr_eqn2; [ | destruct x; simpl; auto ].
f_equal; f_equal.
destruct x; simpl in *; rewrite H; auto.
Qed.
(** The previous result is actually true even without the
constraint on [firstl], but this is harder to prove
(see later). *)
End Incr.
(** * Conversion to [Z] : the [phi] function *)
Section Phi.
(** Variant of [phi] via [recrbis] *)
Let Phi := fun b (_:int31) =>
match b with D0 => Z.double | D1 => Z.succ_double end.
Definition phibis_aux n x := recrbis_aux n _ Z0 Phi x.
Lemma phibis_aux_equiv : forall x, phibis_aux size x = phi x.
Proof.
unfold phi, recr, phibis_aux; fold Phi; intros.
apply recrbis_aux_equiv; auto.
Qed.
(** Recursive equations satisfied by [phi] *)
Lemma phi_eqn1 : forall x, firstr x = D0 ->
phi x = Z.double (phi (shiftr x)).
Proof.
intros.
case_eq (iszero x); intros.
rewrite (iszero_eq0 _ H0); simpl; auto.
intros; unfold phi; rewrite recr_eqn; fold phi; auto.
rewrite H; auto.
Qed.
Lemma phi_eqn2 : forall x, firstr x = D1 ->
phi x = Z.succ_double (phi (shiftr x)).
Proof.
intros.
case_eq (iszero x); intros.
rewrite (iszero_eq0 _ H0) in H; simpl in H; discriminate.
intros; unfold phi; rewrite recr_eqn; fold phi; auto.
rewrite H; auto.
Qed.
Lemma phi_twice_firstl : forall x, firstl x = D0 ->
phi (twice x) = Z.double (phi x).
Proof.
intros.
rewrite phi_eqn1; auto; [ | destruct x; auto ].
f_equal; f_equal.
destruct x; simpl in *; rewrite H; auto.
Qed.
Lemma phi_twice_plus_one_firstl : forall x, firstl x = D0 ->
phi (twice_plus_one x) = Z.succ_double (phi x).
Proof.
intros.
rewrite phi_eqn2; auto; [ | destruct x; auto ].
f_equal; f_equal.
destruct x; simpl in *; rewrite H; auto.
Qed.
End Phi.
(** [phi x] is positive and lower than [2^31] *)
Lemma phibis_aux_pos : forall n x, (0 <= phibis_aux n x)%Z.
Proof.
induction n.
simpl; unfold phibis_aux; simpl; auto with zarith.
intros.
unfold phibis_aux, recrbis_aux; fold recrbis_aux;
fold (phibis_aux n (shiftr x)).
destruct (firstr x).
specialize IHn with (shiftr x); rewrite Z.double_spec; omega.
specialize IHn with (shiftr x); rewrite Z.succ_double_spec; omega.
Qed.
Lemma phibis_aux_bounded :
forall n x, n <= size ->
(phibis_aux n (nshiftr x (size-n)) < 2 ^ (Z.of_nat n))%Z.
Proof.
induction n.
simpl minus; unfold phibis_aux; simpl; auto with zarith.
intros.
unfold phibis_aux, recrbis_aux; fold recrbis_aux;
fold (phibis_aux n (shiftr (nshiftr x (size - S n)))).
assert (shiftr (nshiftr x (size - S n)) = nshiftr x (size-n)).
replace (size - n)%nat with (S (size - (S n))) by omega.
simpl; auto.
rewrite H0.
assert (H1 : n <= size) by omega.
specialize (IHn x H1).
set (y:=phibis_aux n (nshiftr x (size - n))) in *.
rewrite Nat2Z.inj_succ, Z.pow_succ_r; auto with zarith.
case_eq (firstr (nshiftr x (size - S n))); intros.
rewrite Z.double_spec; auto with zarith.
rewrite Z.succ_double_spec; auto with zarith.
Qed.
Lemma phi_bounded : forall x, (0 <= phi x < 2 ^ (Z.of_nat size))%Z.
Proof.
intros.
rewrite <- phibis_aux_equiv.
split.
apply phibis_aux_pos.
change x with (nshiftr x (size-size)).
apply phibis_aux_bounded; auto.
Qed.
Lemma phibis_aux_lowerbound :
forall n x, firstr (nshiftr x n) = D1 ->
(2 ^ Z.of_nat n <= phibis_aux (S n) x)%Z.
Proof.
induction n.
intros.
unfold nshiftr in H; simpl in *.
unfold phibis_aux, recrbis_aux.
rewrite H, Z.succ_double_spec; omega.
intros.
remember (S n) as m.
unfold phibis_aux, recrbis_aux; fold recrbis_aux;
fold (phibis_aux m (shiftr x)).
subst m.
rewrite Nat2Z.inj_succ, Z.pow_succ_r; auto with zarith.
assert (2^(Z.of_nat n) <= phibis_aux (S n) (shiftr x))%Z.
apply IHn.
rewrite <- nshiftr_S_tail; auto.
destruct (firstr x).
change (Z.double (phibis_aux (S n) (shiftr x))) with
(2*(phibis_aux (S n) (shiftr x)))%Z.
omega.
rewrite Z.succ_double_spec; omega.
Qed.
Lemma phi_lowerbound :
forall x, firstl x = D1 -> (2^(Z.of_nat (pred size)) <= phi x)%Z.
Proof.
intros.
generalize (phibis_aux_lowerbound (pred size) x).
rewrite <- firstl_firstr.
change (S (pred size)) with size; auto.
rewrite phibis_aux_equiv; auto.
Qed.
(** * Equivalence modulo [2^n] *)
Section EqShiftL.
(** After killing [n] bits at the left, are the numbers equal ?*)
Definition EqShiftL n x y :=
nshiftl x n = nshiftl y n.
Lemma EqShiftL_zero : forall x y, EqShiftL O x y <-> x = y.
Proof.
unfold EqShiftL; intros; unfold nshiftl; simpl; split; auto.
Qed.
Lemma EqShiftL_size : forall k x y, size<=k -> EqShiftL k x y.
Proof.
red; intros; rewrite 2 nshiftl_above_size; auto.
Qed.
Lemma EqShiftL_le : forall k k' x y, k <= k' ->
EqShiftL k x y -> EqShiftL k' x y.
Proof.
unfold EqShiftL; intros.
replace k' with ((k'-k)+k)%nat by omega.
remember (k'-k)%nat as n.
clear Heqn H k'.
induction n; simpl; auto.
f_equal; auto.
Qed.
Lemma EqShiftL_firstr : forall k x y, k < size ->
EqShiftL k x y -> firstr x = firstr y.
Proof.
intros.
rewrite 2 firstr_firstl.
f_equal.
apply EqShiftL_le with k; auto.
unfold size.
auto with arith.
Qed.
Lemma EqShiftL_twice : forall k x y,
EqShiftL k (twice x) (twice y) <-> EqShiftL (S k) x y.
Proof.
intros; unfold EqShiftL.
rewrite 2 nshiftl_S_tail; split; auto.
Qed.
(** * From int31 to list of digits. *)
(** Lower (=rightmost) bits comes first. *)
Definition i2l := recrbis _ nil (fun d _ rec => d::rec).
Lemma i2l_length : forall x, length (i2l x) = size.
Proof.
intros; reflexivity.
Qed.
Fixpoint lshiftl l x :=
match l with
| nil => x
| d::l => sneakl d (lshiftl l x)
end.
Definition l2i l := lshiftl l On.
Lemma l2i_i2l : forall x, l2i (i2l x) = x.
Proof.
destruct x; compute; auto.
Qed.
Lemma i2l_sneakr : forall x d,
i2l (sneakr d x) = tail (i2l x) ++ d::nil.
Proof.
destruct x; compute; auto.
Qed.
Lemma i2l_sneakl : forall x d,
i2l (sneakl d x) = d :: removelast (i2l x).
Proof.
destruct x; compute; auto.
Qed.
Lemma i2l_l2i : forall l, length l = size ->
i2l (l2i l) = l.
Proof.
repeat (destruct l as [ |? l]; [intros; discriminate | ]).
destruct l; [ | intros; discriminate].
intros _; compute; auto.
Qed.
Fixpoint cstlist (A:Type)(a:A) n :=
match n with
| O => nil
| S n => a::cstlist _ a n
end.
Lemma i2l_nshiftl : forall n x, n<=size ->
i2l (nshiftl x n) = cstlist _ D0 n ++ firstn (size-n) (i2l x).
Proof.
induction n.
intros.
assert (firstn (size-0) (i2l x) = i2l x).
rewrite <- minus_n_O, <- (i2l_length x).
induction (i2l x); simpl; f_equal; auto.
rewrite H0; clear H0.
reflexivity.
intros.
rewrite nshiftl_S.
unfold shiftl; rewrite i2l_sneakl.
simpl cstlist.
rewrite <- app_comm_cons; f_equal.
rewrite IHn; [ | omega].
rewrite removelast_app.
apply f_equal.
replace (size-n)%nat with (S (size - S n))%nat by omega.
rewrite removelast_firstn; auto.
rewrite i2l_length; omega.
generalize (firstn_length (size-n) (i2l x)).
rewrite i2l_length.
intros H0 H1. rewrite H1 in H0.
rewrite min_l in H0 by omega.
simpl length in H0.
omega.
Qed.
(** [i2l] can be used to define a relation equivalent to [EqShiftL] *)
Lemma EqShiftL_i2l : forall k x y,
EqShiftL k x y <-> firstn (size-k) (i2l x) = firstn (size-k) (i2l y).
Proof.
intros.
destruct (le_lt_dec size k) as [Hle|Hlt].
split; intros.
replace (size-k)%nat with O by omega.
unfold firstn; auto.
apply EqShiftL_size; auto.
unfold EqShiftL.
assert (k <= size) by omega.
split; intros.
assert (i2l (nshiftl x k) = i2l (nshiftl y k)) by (f_equal; auto).
rewrite 2 i2l_nshiftl in H1; auto.
eapply app_inv_head; eauto.
assert (i2l (nshiftl x k) = i2l (nshiftl y k)).
rewrite 2 i2l_nshiftl; auto.
f_equal; auto.
rewrite <- (l2i_i2l (nshiftl x k)), <- (l2i_i2l (nshiftl y k)).
f_equal; auto.
Qed.
(** This equivalence allows proving easily the following delicate
result *)
Lemma EqShiftL_twice_plus_one : forall k x y,
EqShiftL k (twice_plus_one x) (twice_plus_one y) <-> EqShiftL (S k) x y.
Proof.
intros.
destruct (le_lt_dec size k) as [Hle|Hlt].
split; intros; apply EqShiftL_size; auto.
rewrite 2 EqShiftL_i2l.
unfold twice_plus_one.
rewrite 2 i2l_sneakl.
replace (size-k)%nat with (S (size - S k))%nat by omega.
remember (size - S k)%nat as n.
remember (i2l x) as lx.
remember (i2l y) as ly.
simpl.
rewrite 2 firstn_removelast.
split; intros.
injection H; auto.
f_equal; auto.
subst ly n; rewrite i2l_length; omega.
subst lx n; rewrite i2l_length; omega.
Qed.
Lemma EqShiftL_shiftr : forall k x y, EqShiftL k x y ->
EqShiftL (S k) (shiftr x) (shiftr y).
Proof.
intros.
destruct (le_lt_dec size (S k)) as [Hle|Hlt].
apply EqShiftL_size; auto.
case_eq (firstr x); intros.
rewrite <- EqShiftL_twice.
unfold twice; rewrite <- H0.
rewrite <- sneakl_shiftr.
rewrite (EqShiftL_firstr k x y); auto.
rewrite <- sneakl_shiftr; auto.
omega.
rewrite <- EqShiftL_twice_plus_one.
unfold twice_plus_one; rewrite <- H0.
rewrite <- sneakl_shiftr.
rewrite (EqShiftL_firstr k x y); auto.
rewrite <- sneakl_shiftr; auto.
omega.
Qed.
Lemma EqShiftL_incrbis : forall n k x y, n<=size ->
(n+k=S size)%nat ->
EqShiftL k x y ->
EqShiftL k (incrbis_aux n x) (incrbis_aux n y).
Proof.
induction n; simpl; intros.
red; auto.
destruct (eq_nat_dec k size).
subst k; apply EqShiftL_size; auto.
unfold incrbis_aux; simpl;
fold (incrbis_aux n (shiftr x)); fold (incrbis_aux n (shiftr y)).
rewrite (EqShiftL_firstr k x y); auto; try omega.
case_eq (firstr y); intros.
rewrite EqShiftL_twice_plus_one.
apply EqShiftL_shiftr; auto.
rewrite EqShiftL_twice.
apply IHn; try omega.
apply EqShiftL_shiftr; auto.
Qed.
Lemma EqShiftL_incr : forall x y,
EqShiftL 1 x y -> EqShiftL 1 (incr x) (incr y).
Proof.
intros.
rewrite <- 2 incrbis_aux_equiv.
apply EqShiftL_incrbis; auto.
Qed.
End EqShiftL.
(** * More equations about [incr] *)
Lemma incr_twice_plus_one :
forall x, incr (twice_plus_one x) = twice (incr x).
Proof.
intros.
rewrite incr_eqn2; [ | destruct x; simpl; auto].
apply EqShiftL_incr.
red; destruct x; simpl; auto.
Qed.
Lemma incr_firstr : forall x, firstr (incr x) <> firstr x.
Proof.
intros.
case_eq (firstr x); intros.
rewrite incr_eqn1; auto.
destruct (shiftr x); simpl; discriminate.
rewrite incr_eqn2; auto.
destruct (incr (shiftr x)); simpl; discriminate.
Qed.
Lemma incr_inv : forall x y,
incr x = twice_plus_one y -> x = twice y.
Proof.
intros.
case_eq (iszero x); intros.
rewrite (iszero_eq0 _ H0) in *; simpl in *.
change (incr 0) with 1 in H.
symmetry; rewrite twice_zero; auto.
case_eq (firstr x); intros.
rewrite incr_eqn1 in H; auto.
clear H0; destruct x; destruct y; simpl in *.
injection H; intros; subst; auto.
elim (incr_firstr x).
rewrite H1, H; destruct y; simpl; auto.
Qed.
(** * Conversion from [Z] : the [phi_inv] function *)
(** First, recursive equations *)
Lemma phi_inv_double_plus_one : forall z,
phi_inv (Z.succ_double z) = twice_plus_one (phi_inv z).
Proof.
destruct z; simpl; auto.
induction p; simpl.
rewrite 2 incr_twice; auto.
rewrite incr_twice, incr_twice_plus_one.
f_equal.
apply incr_inv; auto.
auto.
Qed.
Lemma phi_inv_double : forall z,
phi_inv (Z.double z) = twice (phi_inv z).
Proof.
destruct z; simpl; auto.
rewrite incr_twice_plus_one; auto.
Qed.
Lemma phi_inv_incr : forall z,
phi_inv (Z.succ z) = incr (phi_inv z).
Proof.
destruct z.
simpl; auto.
simpl; auto.
induction p; simpl; auto.
rewrite <- Pos.add_1_r, IHp, incr_twice_plus_one; auto.
rewrite incr_twice; auto.
simpl; auto.
destruct p; simpl; auto.
rewrite incr_twice; auto.
f_equal.
rewrite incr_twice_plus_one; auto.
induction p; simpl; auto.
rewrite incr_twice; auto.
f_equal.
rewrite incr_twice_plus_one; auto.
Qed.
(** [phi_inv o inv], the always-exact and easy-to-prove trip :
from int31 to Z and then back to int31. *)
Lemma phi_inv_phi_aux :
forall n x, n <= size ->
phi_inv (phibis_aux n (nshiftr x (size-n))) =
nshiftr x (size-n).
Proof.
induction n.
intros; simpl minus.
rewrite nshiftr_size; auto.
intros.
unfold phibis_aux, recrbis_aux; fold recrbis_aux;
fold (phibis_aux n (shiftr (nshiftr x (size-S n)))).
assert (shiftr (nshiftr x (size - S n)) = nshiftr x (size-n)).
replace (size - n)%nat with (S (size - (S n))); auto; omega.
rewrite H0.
case_eq (firstr (nshiftr x (size - S n))); intros.
rewrite phi_inv_double.
rewrite IHn by omega.
rewrite <- H0.
remember (nshiftr x (size - S n)) as y.
destruct y; simpl in H1; rewrite H1; auto.
rewrite phi_inv_double_plus_one.
rewrite IHn by omega.
rewrite <- H0.
remember (nshiftr x (size - S n)) as y.
destruct y; simpl in H1; rewrite H1; auto.
Qed.
Lemma phi_inv_phi : forall x, phi_inv (phi x) = x.
Proof.
intros.
rewrite <- phibis_aux_equiv.
replace x with (nshiftr x (size - size)) by auto.
apply phi_inv_phi_aux; auto.
Qed.
(** The other composition [phi o phi_inv] is harder to prove correct.
In particular, an overflow can happen, so a modulo is needed.
For the moment, we proceed via several steps, the first one
being a detour to [positive_to_in31]. *)
(** * [positive_to_int31] *)
(** A variant of [p2i] with [twice] and [twice_plus_one] instead of
[2*i] and [2*i+1] *)
Fixpoint p2ibis n p : (N*int31)%type :=
match n with
| O => (Npos p, On)
| S n => match p with
| xO p => let (r,i) := p2ibis n p in (r, twice i)
| xI p => let (r,i) := p2ibis n p in (r, twice_plus_one i)
| xH => (N0, In)
end
end.
Lemma p2ibis_bounded : forall n p,
nshiftr (snd (p2ibis n p)) n = 0.
Proof.
induction n.
simpl; intros; auto.
simpl p2ibis; intros.
destruct p; simpl snd.
specialize IHn with p.
destruct (p2ibis n p). simpl @snd in *.
rewrite nshiftr_S_tail.
destruct (le_lt_dec size n) as [Hle|Hlt].
rewrite nshiftr_above_size; auto.
assert (H:=nshiftr_0_firstl _ _ Hlt IHn).
replace (shiftr (twice_plus_one i)) with i; auto.
destruct i; simpl in *. rewrite H; auto.
specialize IHn with p.
destruct (p2ibis n p); simpl @snd in *.
rewrite nshiftr_S_tail.
destruct (le_lt_dec size n) as [Hle|Hlt].
rewrite nshiftr_above_size; auto.
assert (H:=nshiftr_0_firstl _ _ Hlt IHn).
replace (shiftr (twice i)) with i; auto.
destruct i; simpl in *; rewrite H; auto.
rewrite nshiftr_S_tail; auto.
replace (shiftr In) with 0; auto.
apply nshiftr_n_0.
Qed.
Local Open Scope Z_scope.
Lemma p2ibis_spec : forall n p, (n<=size)%nat ->
Zpos p = (Z.of_N (fst (p2ibis n p)))*2^(Z.of_nat n) +
phi (snd (p2ibis n p)).
Proof.
induction n; intros.
simpl; rewrite Pos.mul_1_r; auto.
replace (2^(Z.of_nat (S n)))%Z with (2*2^(Z.of_nat n))%Z by
(rewrite <- Z.pow_succ_r, <- Zpos_P_of_succ_nat;
auto with zarith).
rewrite (Z.mul_comm 2).
assert (n<=size)%nat by omega.
destruct p; simpl; [ | | auto];
specialize (IHn p H0);
generalize (p2ibis_bounded n p);
destruct (p2ibis n p) as (r,i); simpl in *; intros.
change (Zpos p~1) with (2*Zpos p + 1)%Z.
rewrite phi_twice_plus_one_firstl, Z.succ_double_spec.
rewrite IHn; ring.
apply (nshiftr_0_firstl n); auto; try omega.
change (Zpos p~0) with (2*Zpos p)%Z.
rewrite phi_twice_firstl.
change (Z.double (phi i)) with (2*(phi i))%Z.
rewrite IHn; ring.
apply (nshiftr_0_firstl n); auto; try omega.
Qed.
(** We now prove that this [p2ibis] is related to [phi_inv_positive] *)
Lemma phi_inv_positive_p2ibis : forall n p, (n<=size)%nat ->
EqShiftL (size-n) (phi_inv_positive p) (snd (p2ibis n p)).
Proof.
induction n.
intros.
apply EqShiftL_size; auto.
intros.
simpl p2ibis; destruct p; [ | | red; auto];
specialize IHn with p;
destruct (p2ibis n p); simpl @snd in *; simpl phi_inv_positive;
rewrite ?EqShiftL_twice_plus_one, ?EqShiftL_twice;
replace (S (size - S n))%nat with (size - n)%nat by omega;
apply IHn; omega.
Qed.
(** This gives the expected result about [phi o phi_inv], at least
for the positive case. *)
Lemma phi_phi_inv_positive : forall p,
phi (phi_inv_positive p) = (Zpos p) mod (2^(Z.of_nat size)).
Proof.
intros.
replace (phi_inv_positive p) with (snd (p2ibis size p)).
rewrite (p2ibis_spec size p) by auto.
rewrite Z.add_comm, Z_mod_plus.
symmetry; apply Zmod_small.
apply phi_bounded.
auto with zarith.
symmetry.
rewrite <- EqShiftL_zero.
apply (phi_inv_positive_p2ibis size p); auto.
Qed.
(** Moreover, [p2ibis] is also related with [p2i] and hence with
[positive_to_int31]. *)
Lemma double_twice_firstl : forall x, firstl x = D0 ->
(Twon*x = twice x)%int31.
Proof.
intros.
unfold mul31.
rewrite <- Z.double_spec, <- phi_twice_firstl, phi_inv_phi; auto.
Qed.
Lemma double_twice_plus_one_firstl : forall x, firstl x = D0 ->
(Twon*x+In = twice_plus_one x)%int31.
Proof.
intros.
rewrite double_twice_firstl; auto.
unfold add31.
rewrite phi_twice_firstl, <- Z.succ_double_spec,
<- phi_twice_plus_one_firstl, phi_inv_phi; auto.
Qed.
Lemma p2i_p2ibis : forall n p, (n<=size)%nat ->
p2i n p = p2ibis n p.
Proof.
induction n; simpl; auto; intros.
destruct p; auto; specialize IHn with p;
generalize (p2ibis_bounded n p);
rewrite IHn; try omega; destruct (p2ibis n p); simpl; intros;
f_equal; auto.
apply double_twice_plus_one_firstl.
apply (nshiftr_0_firstl n); auto; omega.
apply double_twice_firstl.
apply (nshiftr_0_firstl n); auto; omega.
Qed.
Lemma positive_to_int31_phi_inv_positive : forall p,
snd (positive_to_int31 p) = phi_inv_positive p.
Proof.
intros; unfold positive_to_int31.
rewrite p2i_p2ibis; auto.
symmetry.
rewrite <- EqShiftL_zero.
apply (phi_inv_positive_p2ibis size); auto.
Qed.
Lemma positive_to_int31_spec : forall p,
Zpos p = (Z.of_N (fst (positive_to_int31 p)))*2^(Z.of_nat size) +
phi (snd (positive_to_int31 p)).
Proof.
unfold positive_to_int31.
intros; rewrite p2i_p2ibis; auto.
apply p2ibis_spec; auto.
Qed.
(** Thanks to the result about [phi o phi_inv_positive], we can
now establish easily the most general results about
[phi o twice] and so one. *)
Lemma phi_twice : forall x,
phi (twice x) = (Z.double (phi x)) mod 2^(Z.of_nat size).
Proof.
intros.
pattern x at 1; rewrite <- (phi_inv_phi x).
rewrite <- phi_inv_double.
assert (0 <= Z.double (phi x)).
rewrite Z.double_spec; generalize (phi_bounded x); omega.
destruct (Z.double (phi x)).
simpl; auto.
apply phi_phi_inv_positive.
compute in H; elim H; auto.
Qed.
Lemma phi_twice_plus_one : forall x,
phi (twice_plus_one x) = (Z.succ_double (phi x)) mod 2^(Z.of_nat size).
Proof.
intros.
pattern x at 1; rewrite <- (phi_inv_phi x).
rewrite <- phi_inv_double_plus_one.
assert (0 <= Z.succ_double (phi x)).
rewrite Z.succ_double_spec; generalize (phi_bounded x); omega.
destruct (Z.succ_double (phi x)).
simpl; auto.
apply phi_phi_inv_positive.
compute in H; elim H; auto.
Qed.
Lemma phi_incr : forall x,
phi (incr x) = (Z.succ (phi x)) mod 2^(Z.of_nat size).
Proof.
intros.
pattern x at 1; rewrite <- (phi_inv_phi x).
rewrite <- phi_inv_incr.
assert (0 <= Z.succ (phi x)).
change (Z.succ (phi x)) with ((phi x)+1)%Z;
generalize (phi_bounded x); omega.
destruct (Z.succ (phi x)).
simpl; auto.
apply phi_phi_inv_positive.
compute in H; elim H; auto.
Qed.
(** With the previous results, we can deal with [phi o phi_inv] even
in the negative case *)
Lemma phi_phi_inv_negative :
forall p, phi (incr (complement_negative p)) = (Zneg p) mod 2^(Z.of_nat size).
Proof.
induction p.
simpl complement_negative.
rewrite phi_incr in IHp.
rewrite incr_twice, phi_twice_plus_one.
remember (phi (complement_negative p)) as q.
rewrite Z.succ_double_spec.
replace (2*q+1) with (2*(Z.succ q)-1) by omega.
rewrite <- Zminus_mod_idemp_l, <- Zmult_mod_idemp_r, IHp.
rewrite Zmult_mod_idemp_r, Zminus_mod_idemp_l; auto with zarith.
simpl complement_negative.
rewrite incr_twice_plus_one, phi_twice.
remember (phi (incr (complement_negative p))) as q.
rewrite Z.double_spec, IHp, Zmult_mod_idemp_r; auto with zarith.
simpl; auto.
Qed.
Lemma phi_phi_inv :
forall z, phi (phi_inv z) = z mod 2 ^ (Z.of_nat size).
Proof.
destruct z.
simpl; auto.
apply phi_phi_inv_positive.
apply phi_phi_inv_negative.
Qed.
End Basics.
Instance int31_ops : ZnZ.Ops int31 :=
{
digits := 31%positive; (* number of digits *)
zdigits := 31; (* number of digits *)
to_Z := phi; (* conversion to Z *)
of_pos := positive_to_int31; (* positive -> N*int31 : p => N,i
where p = N*2^31+phi i *)
head0 := head031; (* number of head 0 *)
tail0 := tail031; (* number of tail 0 *)
zero := 0;
one := 1;
minus_one := Tn; (* 2^31 - 1 *)
compare := compare31;
eq0 := fun i => match i ?= 0 with Eq => true | _ => false end;
opp_c := fun i => 0 -c i;
opp := opp31;
opp_carry := fun i => 0-i-1;
succ_c := fun i => i +c 1;
add_c := add31c;
add_carry_c := add31carryc;
succ := fun i => i + 1;
add := add31;
add_carry := fun i j => i + j + 1;
pred_c := fun i => i -c 1;
sub_c := sub31c;
sub_carry_c := sub31carryc;
pred := fun i => i - 1;
sub := sub31;
sub_carry := fun i j => i - j - 1;
mul_c := mul31c;
mul := mul31;
square_c := fun x => x *c x;
div21 := div3121;
div_gt := div31; (* this is supposed to be the special case of
division a/b where a > b *)
div := div31;
modulo_gt := fun i j => let (_,r) := i/j in r;
modulo := fun i j => let (_,r) := i/j in r;
gcd_gt := gcd31;
gcd := gcd31;
add_mul_div := addmuldiv31;
pos_mod := (* modulo 2^p *)
fun p i =>
match p ?= 31 with
| Lt => addmuldiv31 p 0 (addmuldiv31 (31-p) i 0)
| _ => i
end;
is_even :=
fun i => let (_,r) := i/2 in
match r ?= 0 with Eq => true | _ => false end;
sqrt2 := sqrt312;
sqrt := sqrt31;
lor := lor31;
land := land31;
lxor := lxor31
}.
Section Int31_Specs.
Local Open Scope Z_scope.
Notation "[| x |]" := (phi x) (at level 0, x at level 99).
Local Notation wB := (2 ^ (Z.of_nat size)).
Lemma wB_pos : wB > 0.
Proof.
auto with zarith.
Qed.
Notation "[+| c |]" :=
(interp_carry 1 wB phi c) (at level 0, c at level 99).
Notation "[-| c |]" :=
(interp_carry (-1) wB phi c) (at level 0, c at level 99).
Notation "[|| x ||]" :=
(zn2z_to_Z wB phi x) (at level 0, x at level 99).
Lemma spec_zdigits : [| 31 |] = 31.
Proof.
reflexivity.
Qed.
Lemma spec_more_than_1_digit: 1 < 31.
Proof.
auto with zarith.
Qed.
Lemma spec_0 : [| 0 |] = 0.
Proof.
reflexivity.
Qed.
Lemma spec_1 : [| 1 |] = 1.
Proof.
reflexivity.
Qed.
Lemma spec_m1 : [| Tn |] = wB - 1.
Proof.
reflexivity.
Qed.
Lemma spec_compare : forall x y,
(x ?= y)%int31 = ([|x|] ?= [|y|]).
Proof. reflexivity. Qed.
(** Addition *)
Lemma spec_add_c : forall x y, [+|add31c x y|] = [|x|] + [|y|].
Proof.
intros; unfold add31c, add31, interp_carry; rewrite phi_phi_inv.
generalize (phi_bounded x)(phi_bounded y); intros.
set (X:=[|x|]) in *; set (Y:=[|y|]) in *; clearbody X Y.
assert ((X+Y) mod wB ?= X+Y <> Eq -> [+|C1 (phi_inv (X+Y))|] = X+Y).
unfold interp_carry; rewrite phi_phi_inv, Z.compare_eq_iff; intros.
destruct (Z_lt_le_dec (X+Y) wB).
contradict H1; auto using Zmod_small with zarith.
rewrite <- (Z_mod_plus_full (X+Y) (-1) wB).
rewrite Zmod_small; romega.
generalize (Z.compare_eq ((X+Y) mod wB) (X+Y)); intros Heq.
destruct Z.compare; intros;
[ rewrite phi_phi_inv; auto | now apply H1 | now apply H1].
Qed.
Lemma spec_succ_c : forall x, [+|add31c x 1|] = [|x|] + 1.
Proof.
intros; apply spec_add_c.
Qed.
Lemma spec_add_carry_c : forall x y, [+|add31carryc x y|] = [|x|] + [|y|] + 1.
Proof.
intros.
unfold add31carryc, interp_carry; rewrite phi_phi_inv.
generalize (phi_bounded x)(phi_bounded y); intros.
set (X:=[|x|]) in *; set (Y:=[|y|]) in *; clearbody X Y.
assert ((X+Y+1) mod wB ?= X+Y+1 <> Eq -> [+|C1 (phi_inv (X+Y+1))|] = X+Y+1).
unfold interp_carry; rewrite phi_phi_inv, Z.compare_eq_iff; intros.
destruct (Z_lt_le_dec (X+Y+1) wB).
contradict H1; auto using Zmod_small with zarith.
rewrite <- (Z_mod_plus_full (X+Y+1) (-1) wB).
rewrite Zmod_small; romega.
generalize (Z.compare_eq ((X+Y+1) mod wB) (X+Y+1)); intros Heq.
destruct Z.compare; intros;
[ rewrite phi_phi_inv; auto | now apply H1 | now apply H1].
Qed.
Lemma spec_add : forall x y, [|x+y|] = ([|x|] + [|y|]) mod wB.
Proof.
intros; apply phi_phi_inv.
Qed.
Lemma spec_add_carry :
forall x y, [|x+y+1|] = ([|x|] + [|y|] + 1) mod wB.
Proof.
unfold add31; intros.
repeat rewrite phi_phi_inv.
apply Zplus_mod_idemp_l.
Qed.
Lemma spec_succ : forall x, [|x+1|] = ([|x|] + 1) mod wB.
Proof.
intros; rewrite <- spec_1; apply spec_add.
Qed.
(** Substraction *)
Lemma spec_sub_c : forall x y, [-|sub31c x y|] = [|x|] - [|y|].
Proof.
unfold sub31c, sub31, interp_carry; intros.
rewrite phi_phi_inv.
generalize (phi_bounded x)(phi_bounded y); intros.
set (X:=[|x|]) in *; set (Y:=[|y|]) in *; clearbody X Y.
assert ((X-Y) mod wB ?= X-Y <> Eq -> [-|C1 (phi_inv (X-Y))|] = X-Y).
unfold interp_carry; rewrite phi_phi_inv, Z.compare_eq_iff; intros.
destruct (Z_lt_le_dec (X-Y) 0).
rewrite <- (Z_mod_plus_full (X-Y) 1 wB).
rewrite Zmod_small; romega.
contradict H1; apply Zmod_small; romega.
generalize (Z.compare_eq ((X-Y) mod wB) (X-Y)); intros Heq.
destruct Z.compare; intros;
[ rewrite phi_phi_inv; auto | now apply H1 | now apply H1].
Qed.
Lemma spec_sub_carry_c : forall x y, [-|sub31carryc x y|] = [|x|] - [|y|] - 1.
Proof.
unfold sub31carryc, sub31, interp_carry; intros.
rewrite phi_phi_inv.
generalize (phi_bounded x)(phi_bounded y); intros.
set (X:=[|x|]) in *; set (Y:=[|y|]) in *; clearbody X Y.
assert ((X-Y-1) mod wB ?= X-Y-1 <> Eq -> [-|C1 (phi_inv (X-Y-1))|] = X-Y-1).
unfold interp_carry; rewrite phi_phi_inv, Z.compare_eq_iff; intros.
destruct (Z_lt_le_dec (X-Y-1) 0).
rewrite <- (Z_mod_plus_full (X-Y-1) 1 wB).
rewrite Zmod_small; romega.
contradict H1; apply Zmod_small; romega.
generalize (Z.compare_eq ((X-Y-1) mod wB) (X-Y-1)); intros Heq.
destruct Z.compare; intros;
[ rewrite phi_phi_inv; auto | now apply H1 | now apply H1].
Qed.
Lemma spec_sub : forall x y, [|x-y|] = ([|x|] - [|y|]) mod wB.
Proof.
intros; apply phi_phi_inv.
Qed.
Lemma spec_sub_carry :
forall x y, [|x-y-1|] = ([|x|] - [|y|] - 1) mod wB.
Proof.
unfold sub31; intros.
repeat rewrite phi_phi_inv.
apply Zminus_mod_idemp_l.
Qed.
Lemma spec_opp_c : forall x, [-|sub31c 0 x|] = -[|x|].
Proof.
intros; apply spec_sub_c.
Qed.
Lemma spec_opp : forall x, [|0 - x|] = (-[|x|]) mod wB.
Proof.
intros; apply phi_phi_inv.
Qed.
Lemma spec_opp_carry : forall x, [|0 - x - 1|] = wB - [|x|] - 1.
Proof.
unfold sub31; intros.
repeat rewrite phi_phi_inv.
change [|1|] with 1; change [|0|] with 0.
rewrite <- (Z_mod_plus_full (0-[|x|]) 1 wB).
rewrite Zminus_mod_idemp_l.
rewrite Zmod_small; generalize (phi_bounded x); romega.
Qed.
Lemma spec_pred_c : forall x, [-|sub31c x 1|] = [|x|] - 1.
Proof.
intros; apply spec_sub_c.
Qed.
Lemma spec_pred : forall x, [|x-1|] = ([|x|] - 1) mod wB.
Proof.
intros; apply spec_sub.
Qed.
(** Multiplication *)
Lemma phi2_phi_inv2 : forall x, [||phi_inv2 x||] = x mod (wB^2).
Proof.
assert (forall z, (z / wB) mod wB * wB + z mod wB = z mod wB ^ 2).
intros.
assert ((z/wB) mod wB = z/wB - (z/wB/wB)*wB).
rewrite (Z_div_mod_eq (z/wB) wB wB_pos) at 2; ring.
assert (z mod wB = z - (z/wB)*wB).
rewrite (Z_div_mod_eq z wB wB_pos) at 2; ring.
rewrite H.
rewrite H0 at 1.
ring_simplify.
rewrite Zdiv_Zdiv; auto with zarith.
rewrite (Z_div_mod_eq z (wB*wB)) at 2; auto with zarith.
change (wB*wB) with (wB^2); ring.
unfold phi_inv2.
destruct x; unfold zn2z_to_Z; rewrite ?phi_phi_inv;
change base with wB; auto.
Qed.
Lemma spec_mul_c : forall x y, [|| mul31c x y ||] = [|x|] * [|y|].
Proof.
unfold mul31c; intros.
rewrite phi2_phi_inv2.
apply Zmod_small.
generalize (phi_bounded x)(phi_bounded y); intros.
change (wB^2) with (wB * wB).
auto using Z.mul_lt_mono_nonneg with zarith.
Qed.
Lemma spec_mul : forall x y, [|x*y|] = ([|x|] * [|y|]) mod wB.
Proof.
intros; apply phi_phi_inv.
Qed.
Lemma spec_square_c : forall x, [|| mul31c x x ||] = [|x|] * [|x|].
Proof.
intros; apply spec_mul_c.
Qed.
(** Division *)
Lemma spec_div21 : forall a1 a2 b,
wB/2 <= [|b|] ->
[|a1|] < [|b|] ->
let (q,r) := div3121 a1 a2 b in
[|a1|] *wB+ [|a2|] = [|q|] * [|b|] + [|r|] /\
0 <= [|r|] < [|b|].
Proof.
unfold div3121; intros.
generalize (phi_bounded a1)(phi_bounded a2)(phi_bounded b); intros.
assert ([|b|]>0) by (auto with zarith).
generalize (Z_div_mod (phi2 a1 a2) [|b|] H4) (Z_div_pos (phi2 a1 a2) [|b|] H4).
unfold Z.div; destruct (Z.div_eucl (phi2 a1 a2) [|b|]).
rewrite ?phi_phi_inv.
destruct 1; intros.
unfold phi2 in *.
change base with wB; change base with wB in H5.
change (Z.pow_pos 2 31) with wB; change (Z.pow_pos 2 31) with wB in H.
rewrite H5, Z.mul_comm.
replace (z0 mod wB) with z0 by (symmetry; apply Zmod_small; omega).
replace (z mod wB) with z; auto with zarith.
symmetry; apply Zmod_small.
split.
apply H7; change base with wB; auto with zarith.
apply Z.mul_lt_mono_pos_r with [|b|]; [omega| ].
rewrite Z.mul_comm.
apply Z.le_lt_trans with ([|b|]*z+z0); [omega| ].
rewrite <- H5.
apply Z.le_lt_trans with ([|a1|]*wB+(wB-1)); [omega | ].
replace ([|a1|]*wB+(wB-1)) with (wB*([|a1|]+1)-1) by ring.
assert (wB*([|a1|]+1) <= wB*[|b|]); try omega.
apply Z.mul_le_mono_nonneg; omega.
Qed.
Lemma spec_div : forall a b, 0 < [|b|] ->
let (q,r) := div31 a b in
[|a|] = [|q|] * [|b|] + [|r|] /\
0 <= [|r|] < [|b|].
Proof.
unfold div31; intros.
assert ([|b|]>0) by (auto with zarith).
generalize (Z_div_mod [|a|] [|b|] H0) (Z_div_pos [|a|] [|b|] H0).
unfold Z.div; destruct (Z.div_eucl [|a|] [|b|]).
rewrite ?phi_phi_inv.
destruct 1; intros.
rewrite H1, Z.mul_comm.
generalize (phi_bounded a)(phi_bounded b); intros.
replace (z0 mod wB) with z0 by (symmetry; apply Zmod_small; omega).
replace (z mod wB) with z; auto with zarith.
symmetry; apply Zmod_small.
split; auto with zarith.
apply Z.le_lt_trans with [|a|]; auto with zarith.
rewrite H1.
apply Z.le_trans with ([|b|]*z); try omega.
rewrite <- (Z.mul_1_l z) at 1.
apply Z.mul_le_mono_nonneg; auto with zarith.
Qed.
Lemma spec_mod : forall a b, 0 < [|b|] ->
[|let (_,r) := (a/b)%int31 in r|] = [|a|] mod [|b|].
Proof.
unfold div31; intros.
assert ([|b|]>0) by (auto with zarith).
unfold Z.modulo.
generalize (Z_div_mod [|a|] [|b|] H0).
destruct (Z.div_eucl [|a|] [|b|]).
rewrite ?phi_phi_inv.
destruct 1; intros.
generalize (phi_bounded b); intros.
apply Zmod_small; omega.
Qed.
Lemma phi_gcd : forall i j,
[|gcd31 i j|] = Zgcdn (2*size) [|j|] [|i|].
Proof.
unfold gcd31.
induction (2*size)%nat; intros.
reflexivity.
simpl euler.
unfold compare31.
change [|On|] with 0.
generalize (phi_bounded j)(phi_bounded i); intros.
case_eq [|j|]; intros.
simpl; intros.
generalize (Zabs_spec [|i|]); omega.
simpl. rewrite IHn, H1; f_equal.
rewrite spec_mod, H1; auto.
rewrite H1; compute; auto.
rewrite H1 in H; destruct H as [H _]; compute in H; elim H; auto.
Qed.
Lemma spec_gcd : forall a b, Zis_gcd [|a|] [|b|] [|gcd31 a b|].
Proof.
intros.
rewrite phi_gcd.
apply Zis_gcd_sym.
apply Zgcdn_is_gcd.
unfold Zgcd_bound.
generalize (phi_bounded b).
destruct [|b|].
unfold size; auto with zarith.
intros (_,H).
cut (Pos.size_nat p <= size)%nat; [ omega | rewrite <- Zpower2_Psize; auto].
intros (H,_); compute in H; elim H; auto.
Qed.
Lemma iter_int31_iter_nat : forall A f i a,
iter_int31 i A f a = iter_nat (Z.abs_nat [|i|]) A f a.
Proof.
intros.
unfold iter_int31.
rewrite <- recrbis_equiv; auto; unfold recrbis.
rewrite <- phibis_aux_equiv.
revert i a; induction size.
simpl; auto.
simpl; intros.
case_eq (firstr i); intros H; rewrite 2 IHn;
unfold phibis_aux; simpl; rewrite ?H; fold (phibis_aux n (shiftr i));
generalize (phibis_aux_pos n (shiftr i)); intros;
set (z := phibis_aux n (shiftr i)) in *; clearbody z;
rewrite <- nat_rect_plus.
f_equal.
rewrite Z.double_spec, <- Z.add_diag.
symmetry; apply Zabs2Nat.inj_add; auto with zarith.
change (iter_nat (S (Z.abs_nat z) + (Z.abs_nat z))%nat A f a =
iter_nat (Z.abs_nat (Z.succ_double z)) A f a); f_equal.
rewrite Z.succ_double_spec, <- Z.add_diag.
rewrite Zabs2Nat.inj_add; auto with zarith.
rewrite Zabs2Nat.inj_add; auto with zarith.
change (Z.abs_nat 1) with 1%nat; omega.
Qed.
Fixpoint addmuldiv31_alt n i j :=
match n with
| O => i
| S n => addmuldiv31_alt n (sneakl (firstl j) i) (shiftl j)
end.
Lemma addmuldiv31_equiv : forall p x y,
addmuldiv31 p x y = addmuldiv31_alt (Z.abs_nat [|p|]) x y.
Proof.
intros.
unfold addmuldiv31.
rewrite iter_int31_iter_nat.
set (n:=Z.abs_nat [|p|]); clearbody n; clear p.
revert x y; induction n.
simpl; auto.
intros.
simpl addmuldiv31_alt.
replace (S n) with (n+1)%nat by (rewrite plus_comm; auto).
rewrite nat_rect_plus; simpl; auto.
Qed.
Lemma spec_add_mul_div : forall x y p, [|p|] <= Zpos 31 ->
[| addmuldiv31 p x y |] =
([|x|] * (2 ^ [|p|]) + [|y|] / (2 ^ ((Zpos 31) - [|p|]))) mod wB.
Proof.
intros.
rewrite addmuldiv31_equiv.
assert ([|p|] = Z.of_nat (Z.abs_nat [|p|])).
rewrite Zabs2Nat.id_abs; symmetry; apply Z.abs_eq.
destruct (phi_bounded p); auto.
rewrite H0; rewrite H0 in H; clear H0; rewrite Zabs2Nat.id.
set (n := Z.abs_nat [|p|]) in *; clearbody n.
assert (n <= 31)%nat.
rewrite Nat2Z.inj_le; auto with zarith.
clear p H; revert x y.
induction n.
simpl Z.of_nat; intros.
rewrite Z.mul_1_r.
replace ([|y|] / 2^(31-0)) with 0.
rewrite Z.add_0_r.
symmetry; apply Zmod_small; apply phi_bounded.
symmetry; apply Zdiv_small; apply phi_bounded.
simpl addmuldiv31_alt; intros.
rewrite IHn; [ | omega ].
case_eq (firstl y); intros.
rewrite phi_twice, Z.double_spec.
rewrite phi_twice_firstl; auto.
change (Z.double [|y|]) with (2*[|y|]).
rewrite Nat2Z.inj_succ, Z.pow_succ_r; auto with zarith.
rewrite Zplus_mod; rewrite Zmult_mod_idemp_l; rewrite <- Zplus_mod.
f_equal.
f_equal.
ring.
replace (31-Z.of_nat n) with (Z.succ(31-Z.succ(Z.of_nat n))) by ring.
rewrite Z.pow_succ_r, <- Zdiv_Zdiv; auto with zarith.
rewrite Z.mul_comm, Z_div_mult; auto with zarith.
rewrite phi_twice_plus_one, Z.succ_double_spec.
rewrite phi_twice; auto.
change (Z.double [|y|]) with (2*[|y|]).
rewrite Nat2Z.inj_succ, Z.pow_succ_r; auto with zarith.
rewrite Zplus_mod; rewrite Zmult_mod_idemp_l; rewrite <- Zplus_mod.
rewrite Z.mul_add_distr_r, Z.mul_1_l, <- Z.add_assoc.
f_equal.
f_equal.
ring.
assert ((2*[|y|]) mod wB = 2*[|y|] - wB).
clear - H. symmetry. apply Zmod_unique with 1; [ | ring ].
generalize (phi_lowerbound _ H) (phi_bounded y).
set (wB' := 2^Z.of_nat (pred size)).
replace wB with (2*wB'); [ omega | ].
unfold wB'. rewrite <- Z.pow_succ_r, <- Nat2Z.inj_succ by (auto with zarith).
f_equal.
rewrite H1.
replace wB with (2^(Z.of_nat n)*2^(31-Z.of_nat n)) by
(rewrite <- Zpower_exp; auto with zarith; f_equal; unfold size; ring).
unfold Z.sub; rewrite <- Z.mul_opp_l.
rewrite Z_div_plus; auto with zarith.
ring_simplify.
replace (31+-Z.of_nat n) with (Z.succ(31-Z.succ(Z.of_nat n))) by ring.
rewrite Z.pow_succ_r, <- Zdiv_Zdiv; auto with zarith.
rewrite Z.mul_comm, Z_div_mult; auto with zarith.
Qed.
Lemma spec_pos_mod : forall w p,
[|ZnZ.pos_mod p w|] = [|w|] mod (2 ^ [|p|]).
Proof.
unfold int31_ops, ZnZ.pos_mod, compare31.
change [|31|] with 31%Z.
assert (forall w p, 31<=p -> [|w|] = [|w|] mod 2^p).
intros.
generalize (phi_bounded w).
symmetry; apply Zmod_small.
split; auto with zarith.
apply Z.lt_le_trans with wB; auto with zarith.
apply Zpower_le_monotone; auto with zarith.
intros.
case_eq ([|p|] ?= 31); intros;
[ apply H; rewrite (Z.compare_eq _ _ H0); auto with zarith | |
apply H; change ([|p|]>31)%Z in H0; auto with zarith ].
change ([|p|]<31) in H0.
rewrite spec_add_mul_div by auto with zarith.
change [|0|] with 0%Z; rewrite Z.mul_0_l, Z.add_0_l.
generalize (phi_bounded p)(phi_bounded w); intros.
assert (31-[|p|]<wB).
apply Z.le_lt_trans with 31%Z; auto with zarith.
compute; auto.
assert ([|31-p|]=31-[|p|]).
unfold sub31; rewrite phi_phi_inv.
change [|31|] with 31%Z.
apply Zmod_small; auto with zarith.
rewrite spec_add_mul_div by (rewrite H4; auto with zarith).
change [|0|] with 0%Z; rewrite Zdiv_0_l, Z.add_0_r.
rewrite H4.
apply shift_unshift_mod_2; auto with zarith.
Qed.
(** Shift operations *)
Lemma spec_head00: forall x, [|x|] = 0 -> [|head031 x|] = Zpos 31.
Proof.
intros.
generalize (phi_inv_phi x).
rewrite H; simpl phi_inv.
intros H'; rewrite <- H'.
simpl; auto.
Qed.
Fixpoint head031_alt n x :=
match n with
| O => 0%nat
| S n => match firstl x with
| D0 => S (head031_alt n (shiftl x))
| D1 => 0%nat
end
end.
Lemma head031_equiv :
forall x, [|head031 x|] = Z.of_nat (head031_alt size x).
Proof.
intros.
case_eq (iszero x); intros.
rewrite (iszero_eq0 _ H).
simpl; auto.
unfold head031, recl.
change On with (phi_inv (Z.of_nat (31-size))).
replace (head031_alt size x) with
(head031_alt size x + (31 - size))%nat by auto.
assert (size <= 31)%nat by auto with arith.
revert x H; induction size; intros.
simpl; auto.
unfold recl_aux; fold recl_aux.
unfold head031_alt; fold head031_alt.
rewrite H.
assert ([|phi_inv (Z.of_nat (31-S n))|] = Z.of_nat (31 - S n)).
rewrite phi_phi_inv.
apply Zmod_small.
split.
change 0 with (Z.of_nat O); apply inj_le; omega.
apply Z.le_lt_trans with (Z.of_nat 31).
apply inj_le; omega.
compute; auto.
case_eq (firstl x); intros; auto.
rewrite plus_Sn_m, plus_n_Sm.
replace (S (31 - S n)) with (31 - n)%nat by omega.
rewrite <- IHn; [ | omega | ].
f_equal; f_equal.
unfold add31.
rewrite H1.
f_equal.
change [|In|] with 1.
replace (31-n)%nat with (S (31 - S n))%nat by omega.
rewrite Nat2Z.inj_succ; ring.
clear - H H2.
rewrite (sneakr_shiftl x) in H.
rewrite H2 in H.
case_eq (iszero (shiftl x)); intros; auto.
rewrite (iszero_eq0 _ H0) in H; discriminate.
Qed.
Lemma phi_nz : forall x, 0 < [|x|] <-> x <> 0%int31.
Proof.
split; intros.
red; intro; subst x; discriminate.
assert ([|x|]<>0%Z).
contradict H.
rewrite <- (phi_inv_phi x); rewrite H; auto.
generalize (phi_bounded x); auto with zarith.
Qed.
Lemma spec_head0 : forall x, 0 < [|x|] ->
wB/ 2 <= 2 ^ ([|head031 x|]) * [|x|] < wB.
Proof.
intros.
rewrite head031_equiv.
assert (nshiftl x size = 0%int31).
apply nshiftl_size.
revert x H H0.
unfold size at 2 5.
induction size.
simpl Z.of_nat.
intros.
compute in H0; rewrite H0 in H; discriminate.
intros.
simpl head031_alt.
case_eq (firstl x); intros.
rewrite (Nat2Z.inj_succ (head031_alt n (shiftl x))), Z.pow_succ_r; auto with zarith.
rewrite <- Z.mul_assoc, Z.mul_comm, <- Z.mul_assoc, <-(Z.mul_comm 2).
rewrite <- Z.double_spec, <- (phi_twice_firstl _ H1).
apply IHn.
rewrite phi_nz; rewrite phi_nz in H; contradict H.
change twice with shiftl in H.
rewrite (sneakr_shiftl x), H1, H; auto.
rewrite <- nshiftl_S_tail; auto.
change (2^(Z.of_nat 0)) with 1; rewrite Z.mul_1_l.
generalize (phi_bounded x); unfold size; split; auto with zarith.
change (2^(Z.of_nat 31)/2) with (2^(Z.of_nat (pred size))).
apply phi_lowerbound; auto.
Qed.
Lemma spec_tail00: forall x, [|x|] = 0 -> [|tail031 x|] = Zpos 31.
Proof.
intros.
generalize (phi_inv_phi x).
rewrite H; simpl phi_inv.
intros H'; rewrite <- H'.
simpl; auto.
Qed.
Fixpoint tail031_alt n x :=
match n with
| O => 0%nat
| S n => match firstr x with
| D0 => S (tail031_alt n (shiftr x))
| D1 => 0%nat
end
end.
Lemma tail031_equiv :
forall x, [|tail031 x|] = Z.of_nat (tail031_alt size x).
Proof.
intros.
case_eq (iszero x); intros.
rewrite (iszero_eq0 _ H).
simpl; auto.
unfold tail031, recr.
change On with (phi_inv (Z.of_nat (31-size))).
replace (tail031_alt size x) with
(tail031_alt size x + (31 - size))%nat by auto.
assert (size <= 31)%nat by auto with arith.
revert x H; induction size; intros.
simpl; auto.
unfold recr_aux; fold recr_aux.
unfold tail031_alt; fold tail031_alt.
rewrite H.
assert ([|phi_inv (Z.of_nat (31-S n))|] = Z.of_nat (31 - S n)).
rewrite phi_phi_inv.
apply Zmod_small.
split.
change 0 with (Z.of_nat O); apply inj_le; omega.
apply Z.le_lt_trans with (Z.of_nat 31).
apply inj_le; omega.
compute; auto.
case_eq (firstr x); intros; auto.
rewrite plus_Sn_m, plus_n_Sm.
replace (S (31 - S n)) with (31 - n)%nat by omega.
rewrite <- IHn; [ | omega | ].
f_equal; f_equal.
unfold add31.
rewrite H1.
f_equal.
change [|In|] with 1.
replace (31-n)%nat with (S (31 - S n))%nat by omega.
rewrite Nat2Z.inj_succ; ring.
clear - H H2.
rewrite (sneakl_shiftr x) in H.
rewrite H2 in H.
case_eq (iszero (shiftr x)); intros; auto.
rewrite (iszero_eq0 _ H0) in H; discriminate.
Qed.
Lemma spec_tail0 : forall x, 0 < [|x|] ->
exists y, 0 <= y /\ [|x|] = (2 * y + 1) * (2 ^ [|tail031 x|]).
Proof.
intros.
rewrite tail031_equiv.
assert (nshiftr x size = 0%int31).
apply nshiftr_size.
revert x H H0.
induction size.
simpl Z.of_nat.
intros.
compute in H0; rewrite H0 in H; discriminate.
intros.
simpl tail031_alt.
case_eq (firstr x); intros.
rewrite (Nat2Z.inj_succ (tail031_alt n (shiftr x))), Z.pow_succ_r; auto with zarith.
destruct (IHn (shiftr x)) as (y & Hy1 & Hy2).
rewrite phi_nz; rewrite phi_nz in H; contradict H.
rewrite (sneakl_shiftr x), H1, H; auto.
rewrite <- nshiftr_S_tail; auto.
exists y; split; auto.
rewrite phi_eqn1; auto.
rewrite Z.double_spec, Hy2; ring.
exists [|shiftr x|].
split.
generalize (phi_bounded (shiftr x)); auto with zarith.
rewrite phi_eqn2; auto.
rewrite Z.succ_double_spec; simpl; ring.
Qed.
(* Sqrt *)
(* Direct transcription of an old proof
of a fortran program in boyer-moore *)
Lemma quotient_by_2 a: a - 1 <= (a/2) + (a/2).
Proof.
case (Z_mod_lt a 2); auto with zarith.
intros H1; rewrite Zmod_eq_full; auto with zarith.
Qed.
Lemma sqrt_main_trick j k: 0 <= j -> 0 <= k ->
(j * k) + j <= ((j + k)/2 + 1) ^ 2.
Proof.
intros Hj; generalize Hj k; pattern j; apply natlike_ind;
auto; clear k j Hj.
intros _ k Hk; repeat rewrite Z.add_0_l.
apply Z.mul_nonneg_nonneg; generalize (Z_div_pos k 2); auto with zarith.
intros j Hj Hrec _ k Hk; pattern k; apply natlike_ind; auto; clear k Hk.
rewrite Z.mul_0_r, Z.add_0_r, Z.add_0_l.
generalize (sqr_pos (Z.succ j / 2)) (quotient_by_2 (Z.succ j));
unfold Z.succ.
rewrite Z.pow_2_r, Z.mul_add_distr_r; repeat rewrite Z.mul_add_distr_l.
auto with zarith.
intros k Hk _.
replace ((Z.succ j + Z.succ k) / 2) with ((j + k)/2 + 1).
generalize (Hrec Hj k Hk) (quotient_by_2 (j + k)).
unfold Z.succ; repeat rewrite Z.pow_2_r;
repeat rewrite Z.mul_add_distr_r; repeat rewrite Z.mul_add_distr_l.
repeat rewrite Z.mul_1_l; repeat rewrite Z.mul_1_r.
auto with zarith.
rewrite Z.add_comm, <- Z_div_plus_full_l; auto with zarith.
apply f_equal2 with (f := Z.div); auto with zarith.
Qed.
Lemma sqrt_main i j: 0 <= i -> 0 < j -> i < ((j + (i/j))/2 + 1) ^ 2.
Proof.
intros Hi Hj.
assert (Hij: 0 <= i/j) by (apply Z_div_pos; auto with zarith).
apply Z.lt_le_trans with (2 := sqrt_main_trick _ _ (Z.lt_le_incl _ _ Hj) Hij).
pattern i at 1; rewrite (Z_div_mod_eq i j); case (Z_mod_lt i j); auto with zarith.
Qed.
Lemma sqrt_init i: 1 < i -> i < (i/2 + 1) ^ 2.
Proof.
intros Hi.
assert (H1: 0 <= i - 2) by auto with zarith.
assert (H2: 1 <= (i / 2) ^ 2); auto with zarith.
replace i with (1* 2 + (i - 2)); auto with zarith.
rewrite Z.pow_2_r, Z_div_plus_full_l; auto with zarith.
generalize (sqr_pos ((i - 2)/ 2)) (Z_div_pos (i - 2) 2).
rewrite Z.mul_add_distr_r; repeat rewrite Z.mul_add_distr_l.
auto with zarith.
generalize (quotient_by_2 i).
rewrite Z.pow_2_r in H2 |- *;
repeat (rewrite Z.mul_add_distr_r ||
rewrite Z.mul_add_distr_l ||
rewrite Z.mul_1_l || rewrite Z.mul_1_r).
auto with zarith.
Qed.
Lemma sqrt_test_true i j: 0 <= i -> 0 < j -> i/j >= j -> j ^ 2 <= i.
Proof.
intros Hi Hj Hd; rewrite Z.pow_2_r.
apply Z.le_trans with (j * (i/j)); auto with zarith.
apply Z_mult_div_ge; auto with zarith.
Qed.
Lemma sqrt_test_false i j: 0 <= i -> 0 < j -> i/j < j -> (j + (i/j))/2 < j.
Proof.
intros Hi Hj H; case (Z.le_gt_cases j ((j + (i/j))/2)); auto.
intros H1; contradict H; apply Z.le_ngt.
assert (2 * j <= j + (i/j)); auto with zarith.
apply Z.le_trans with (2 * ((j + (i/j))/2)); auto with zarith.
apply Z_mult_div_ge; auto with zarith.
Qed.
Lemma sqrt31_step_def rec i j:
sqrt31_step rec i j =
match (fst (i/j) ?= j)%int31 with
Lt => rec i (fst ((j + fst(i/j))/2))%int31
| _ => j
end.
Proof.
unfold sqrt31_step; case div31; intros.
simpl; case compare31; auto.
Qed.
Lemma div31_phi i j: 0 < [|j|] -> [|fst (i/j)%int31|] = [|i|]/[|j|].
intros Hj; generalize (spec_div i j Hj).
case div31; intros q r; simpl @fst.
intros (H1,H2); apply Zdiv_unique with [|r|]; auto with zarith.
rewrite H1; ring.
Qed.
Lemma sqrt31_step_correct rec i j:
0 < [|i|] -> 0 < [|j|] -> [|i|] < ([|j|] + 1) ^ 2 ->
2 * [|j|] < wB ->
(forall j1 : int31,
0 < [|j1|] < [|j|] -> [|i|] < ([|j1|] + 1) ^ 2 ->
[|rec i j1|] ^ 2 <= [|i|] < ([|rec i j1|] + 1) ^ 2) ->
[|sqrt31_step rec i j|] ^ 2 <= [|i|] < ([|sqrt31_step rec i j|] + 1) ^ 2.
Proof.
assert (Hp2: 0 < [|2|]) by exact (eq_refl Lt).
intros Hi Hj Hij H31 Hrec; rewrite sqrt31_step_def.
rewrite spec_compare, div31_phi; auto.
case Z.compare_spec; auto; intros Hc;
try (split; auto; apply sqrt_test_true; auto with zarith; fail).
apply Hrec; repeat rewrite div31_phi; auto with zarith.
replace [|(j + fst (i / j)%int31)|] with ([|j|] + [|i|] / [|j|]).
split.
apply Z.le_succ_l in Hj. change (1 <= [|j|]) in Hj.
Z.le_elim Hj.
replace ([|j|] + [|i|]/[|j|]) with
(1 * 2 + (([|j|] - 2) + [|i|] / [|j|])); try ring.
rewrite Z_div_plus_full_l; auto with zarith.
assert (0 <= [|i|]/ [|j|]) by (apply Z_div_pos; auto with zarith).
assert (0 <= ([|j|] - 2 + [|i|] / [|j|]) / [|2|]) ; auto with zarith.
rewrite <- Hj, Zdiv_1_r.
replace (1 + [|i|])%Z with (1 * 2 + ([|i|] - 1))%Z; try ring.
rewrite Z_div_plus_full_l; auto with zarith.
assert (0 <= ([|i|] - 1) /2)%Z by (apply Z_div_pos; auto with zarith).
change ([|2|]) with 2%Z; auto with zarith.
apply sqrt_test_false; auto with zarith.
rewrite spec_add, div31_phi; auto.
symmetry; apply Zmod_small.
split; auto with zarith.
replace [|j + fst (i / j)%int31|] with ([|j|] + [|i|] / [|j|]).
apply sqrt_main; auto with zarith.
rewrite spec_add, div31_phi; auto.
symmetry; apply Zmod_small.
split; auto with zarith.
Qed.
Lemma iter31_sqrt_correct n rec i j: 0 < [|i|] -> 0 < [|j|] ->
[|i|] < ([|j|] + 1) ^ 2 -> 2 * [|j|] < 2 ^ (Z.of_nat size) ->
(forall j1, 0 < [|j1|] -> 2^(Z.of_nat n) + [|j1|] <= [|j|] ->
[|i|] < ([|j1|] + 1) ^ 2 -> 2 * [|j1|] < 2 ^ (Z.of_nat size) ->
[|rec i j1|] ^ 2 <= [|i|] < ([|rec i j1|] + 1) ^ 2) ->
[|iter31_sqrt n rec i j|] ^ 2 <= [|i|] < ([|iter31_sqrt n rec i j|] + 1) ^ 2.
Proof.
revert rec i j; elim n; unfold iter31_sqrt; fold iter31_sqrt; clear n.
intros rec i j Hi Hj Hij H31 Hrec; apply sqrt31_step_correct; auto with zarith.
intros; apply Hrec; auto with zarith.
rewrite Z.pow_0_r; auto with zarith.
intros n Hrec rec i j Hi Hj Hij H31 HHrec.
apply sqrt31_step_correct; auto.
intros j1 Hj1 Hjp1; apply Hrec; auto with zarith.
intros j2 Hj2 H2j2 Hjp2 Hj31; apply Hrec; auto with zarith.
intros j3 Hj3 Hpj3.
apply HHrec; auto.
rewrite Nat2Z.inj_succ, Z.pow_succ_r.
apply Z.le_trans with (2 ^Z.of_nat n + [|j2|]); auto with zarith.
apply Nat2Z.is_nonneg.
Qed.
Lemma spec_sqrt : forall x,
[|sqrt31 x|] ^ 2 <= [|x|] < ([|sqrt31 x|] + 1) ^ 2.
Proof.
intros i; unfold sqrt31.
rewrite spec_compare. case Z.compare_spec; change [|1|] with 1;
intros Hi; auto with zarith.
repeat rewrite Z.pow_2_r; auto with zarith.
apply iter31_sqrt_correct; auto with zarith.
rewrite div31_phi; change ([|2|]) with 2; auto with zarith.
replace ([|i|]) with (1 * 2 + ([|i|] - 2))%Z; try ring.
assert (0 <= ([|i|] - 2)/2)%Z by (apply Z_div_pos; auto with zarith).
rewrite Z_div_plus_full_l; auto with zarith.
rewrite div31_phi; change ([|2|]) with 2; auto with zarith.
apply sqrt_init; auto.
rewrite div31_phi; change ([|2|]) with 2; auto with zarith.
apply Z.le_lt_trans with ([|i|]).
apply Z_mult_div_ge; auto with zarith.
case (phi_bounded i); auto.
intros j2 H1 H2; contradict H2; apply Z.lt_nge.
rewrite div31_phi; change ([|2|]) with 2; auto with zarith.
apply Z.le_lt_trans with ([|i|]); auto with zarith.
assert (0 <= [|i|]/2)%Z by (apply Z_div_pos; auto with zarith).
apply Z.le_trans with (2 * ([|i|]/2)); auto with zarith.
apply Z_mult_div_ge; auto with zarith.
case (phi_bounded i); unfold size; auto with zarith.
change [|0|] with 0; auto with zarith.
case (phi_bounded i); repeat rewrite Z.pow_2_r; auto with zarith.
Qed.
Lemma sqrt312_step_def rec ih il j:
sqrt312_step rec ih il j =
match (ih ?= j)%int31 with
Eq => j
| Gt => j
| _ =>
match (fst (div3121 ih il j) ?= j)%int31 with
Lt => let m := match j +c fst (div3121 ih il j) with
C0 m1 => fst (m1/2)%int31
| C1 m1 => (fst (m1/2) + v30)%int31
end in rec ih il m
| _ => j
end
end.
Proof.
unfold sqrt312_step; case div3121; intros.
simpl; case compare31; auto.
Qed.
Lemma sqrt312_lower_bound ih il j:
phi2 ih il < ([|j|] + 1) ^ 2 -> [|ih|] <= [|j|].
Proof.
intros H1.
case (phi_bounded j); intros Hbj _.
case (phi_bounded il); intros Hbil _.
case (phi_bounded ih); intros Hbih Hbih1.
assert (([|ih|] < [|j|] + 1)%Z); auto with zarith.
apply Z.square_lt_simpl_nonneg; auto with zarith.
repeat rewrite <-Z.pow_2_r; apply Z.le_lt_trans with (2 := H1).
apply Z.le_trans with ([|ih|] * base)%Z; unfold phi2, base;
try rewrite Z.pow_2_r; auto with zarith.
Qed.
Lemma div312_phi ih il j: (2^30 <= [|j|] -> [|ih|] < [|j|] ->
[|fst (div3121 ih il j)|] = phi2 ih il/[|j|])%Z.
Proof.
intros Hj Hj1.
generalize (spec_div21 ih il j Hj Hj1).
case div3121; intros q r (Hq, Hr).
apply Zdiv_unique with (phi r); auto with zarith.
simpl @fst; apply eq_trans with (1 := Hq); ring.
Qed.
Lemma sqrt312_step_correct rec ih il j:
2 ^ 29 <= [|ih|] -> 0 < [|j|] -> phi2 ih il < ([|j|] + 1) ^ 2 ->
(forall j1, 0 < [|j1|] < [|j|] -> phi2 ih il < ([|j1|] + 1) ^ 2 ->
[|rec ih il j1|] ^ 2 <= phi2 ih il < ([|rec ih il j1|] + 1) ^ 2) ->
[|sqrt312_step rec ih il j|] ^ 2 <= phi2 ih il
< ([|sqrt312_step rec ih il j|] + 1) ^ 2.
Proof.
assert (Hp2: (0 < [|2|])%Z) by exact (eq_refl Lt).
intros Hih Hj Hij Hrec; rewrite sqrt312_step_def.
assert (H1: ([|ih|] <= [|j|])%Z) by (apply sqrt312_lower_bound with il; auto).
case (phi_bounded ih); intros Hih1 _.
case (phi_bounded il); intros Hil1 _.
case (phi_bounded j); intros _ Hj1.
assert (Hp3: (0 < phi2 ih il)).
unfold phi2; apply Z.lt_le_trans with ([|ih|] * base)%Z; auto with zarith.
apply Z.mul_pos_pos; auto with zarith.
apply Z.lt_le_trans with (2:= Hih); auto with zarith.
rewrite spec_compare. case Z.compare_spec; intros Hc1.
split; auto.
apply sqrt_test_true; auto.
unfold phi2, base; auto with zarith.
unfold phi2; rewrite Hc1.
assert (0 <= [|il|]/[|j|]) by (apply Z_div_pos; auto with zarith).
rewrite Z.mul_comm, Z_div_plus_full_l; unfold base; auto with zarith.
simpl wB in Hj1. unfold Z.pow_pos in Hj1. simpl in Hj1. auto with zarith.
case (Z.le_gt_cases (2 ^ 30) [|j|]); intros Hjj.
rewrite spec_compare; case Z.compare_spec;
rewrite div312_phi; auto; intros Hc;
try (split; auto; apply sqrt_test_true; auto with zarith; fail).
apply Hrec.
assert (Hf1: 0 <= phi2 ih il/ [|j|]) by (apply Z_div_pos; auto with zarith).
apply Z.le_succ_l in Hj. change (1 <= [|j|]) in Hj.
Z.le_elim Hj.
2: contradict Hc; apply Z.le_ngt; rewrite <- Hj, Zdiv_1_r; auto with zarith.
assert (Hf3: 0 < ([|j|] + phi2 ih il / [|j|]) / 2).
replace ([|j|] + phi2 ih il/ [|j|])%Z with
(1 * 2 + (([|j|] - 2) + phi2 ih il / [|j|])); try ring.
rewrite Z_div_plus_full_l; auto with zarith.
assert (0 <= ([|j|] - 2 + phi2 ih il / [|j|]) / 2) ; auto with zarith.
assert (Hf4: ([|j|] + phi2 ih il / [|j|]) / 2 < [|j|]).
apply sqrt_test_false; auto with zarith.
generalize (spec_add_c j (fst (div3121 ih il j))).
unfold interp_carry; case add31c; intros r;
rewrite div312_phi; auto with zarith.
rewrite div31_phi; change [|2|] with 2%Z; auto with zarith.
intros HH; rewrite HH; clear HH; auto with zarith.
rewrite spec_add, div31_phi; change [|2|] with 2%Z; auto.
rewrite Z.mul_1_l; intros HH.
rewrite Z.add_comm, <- Z_div_plus_full_l; auto with zarith.
change (phi v30 * 2) with (2 ^ Z.of_nat size).
rewrite HH, Zmod_small; auto with zarith.
replace (phi
match j +c fst (div3121 ih il j) with
| C0 m1 => fst (m1 / 2)%int31
| C1 m1 => fst (m1 / 2)%int31 + v30
end) with ((([|j|] + (phi2 ih il)/([|j|]))/2)).
apply sqrt_main; auto with zarith.
generalize (spec_add_c j (fst (div3121 ih il j))).
unfold interp_carry; case add31c; intros r;
rewrite div312_phi; auto with zarith.
rewrite div31_phi; auto with zarith.
intros HH; rewrite HH; auto with zarith.
intros HH; rewrite <- HH.
change (1 * 2 ^ Z.of_nat size) with (phi (v30) * 2).
rewrite Z_div_plus_full_l; auto with zarith.
rewrite Z.add_comm.
rewrite spec_add, Zmod_small.
rewrite div31_phi; auto.
split; auto with zarith.
case (phi_bounded (fst (r/2)%int31));
case (phi_bounded v30); auto with zarith.
rewrite div31_phi; change (phi 2) with 2%Z; auto.
change (2 ^Z.of_nat size) with (base/2 + phi v30).
assert (phi r / 2 < base/2); auto with zarith.
apply Z.mul_lt_mono_pos_r with 2; auto with zarith.
change (base/2 * 2) with base.
apply Z.le_lt_trans with (phi r).
rewrite Z.mul_comm; apply Z_mult_div_ge; auto with zarith.
case (phi_bounded r); auto with zarith.
contradict Hij; apply Z.le_ngt.
assert ((1 + [|j|]) <= 2 ^ 30); auto with zarith.
apply Z.le_trans with ((2 ^ 30) * (2 ^ 30)); auto with zarith.
assert (0 <= 1 + [|j|]); auto with zarith.
apply Z.mul_le_mono_nonneg; auto with zarith.
change ((2 ^ 30) * (2 ^ 30)) with ((2 ^ 29) * base).
apply Z.le_trans with ([|ih|] * base); auto with zarith.
unfold phi2, base; auto with zarith.
split; auto.
apply sqrt_test_true; auto.
unfold phi2, base; auto with zarith.
apply Z.le_ge; apply Z.le_trans with (([|j|] * base)/[|j|]).
rewrite Z.mul_comm, Z_div_mult; auto with zarith.
apply Z.ge_le; apply Z_div_ge; auto with zarith.
Qed.
Lemma iter312_sqrt_correct n rec ih il j:
2^29 <= [|ih|] -> 0 < [|j|] -> phi2 ih il < ([|j|] + 1) ^ 2 ->
(forall j1, 0 < [|j1|] -> 2^(Z.of_nat n) + [|j1|] <= [|j|] ->
phi2 ih il < ([|j1|] + 1) ^ 2 ->
[|rec ih il j1|] ^ 2 <= phi2 ih il < ([|rec ih il j1|] + 1) ^ 2) ->
[|iter312_sqrt n rec ih il j|] ^ 2 <= phi2 ih il
< ([|iter312_sqrt n rec ih il j|] + 1) ^ 2.
Proof.
revert rec ih il j; elim n; unfold iter312_sqrt; fold iter312_sqrt; clear n.
intros rec ih il j Hi Hj Hij Hrec; apply sqrt312_step_correct; auto with zarith.
intros; apply Hrec; auto with zarith.
rewrite Z.pow_0_r; auto with zarith.
intros n Hrec rec ih il j Hi Hj Hij HHrec.
apply sqrt312_step_correct; auto.
intros j1 Hj1 Hjp1; apply Hrec; auto with zarith.
intros j2 Hj2 H2j2 Hjp2; apply Hrec; auto with zarith.
intros j3 Hj3 Hpj3.
apply HHrec; auto.
rewrite Nat2Z.inj_succ, Z.pow_succ_r.
apply Z.le_trans with (2 ^Z.of_nat n + [|j2|])%Z; auto with zarith.
apply Nat2Z.is_nonneg.
Qed.
(* Avoid expanding [iter312_sqrt] before variables in the context. *)
Strategy 1 [iter312_sqrt].
Lemma spec_sqrt2 : forall x y,
wB/ 4 <= [|x|] ->
let (s,r) := sqrt312 x y in
[||WW x y||] = [|s|] ^ 2 + [+|r|] /\
[+|r|] <= 2 * [|s|].
Proof.
intros ih il Hih; unfold sqrt312.
change [||WW ih il||] with (phi2 ih il).
assert (Hbin: forall s, s * s + 2* s + 1 = (s + 1) ^ 2) by
(intros s; ring).
assert (Hb: 0 <= base) by (red; intros HH; discriminate).
assert (Hi2: phi2 ih il < (phi Tn + 1) ^ 2).
{ change ((phi Tn + 1) ^ 2) with (2^62).
apply Z.le_lt_trans with ((2^31 -1) * base + (2^31 - 1)); auto with zarith.
2: simpl; unfold Z.pow_pos; simpl; auto with zarith.
case (phi_bounded ih); case (phi_bounded il); intros H1 H2 H3 H4.
unfold base, Z.pow, Z.pow_pos in H2,H4; simpl in H2,H4.
unfold phi2. cbn [Z.pow Z.pow_pos Pos.iter]. auto with zarith. }
case (iter312_sqrt_correct 31 (fun _ _ j => j) ih il Tn); auto with zarith.
change [|Tn|] with 2147483647; auto with zarith.
intros j1 _ HH; contradict HH.
apply Z.lt_nge.
change [|Tn|] with 2147483647; auto with zarith.
change (2 ^ Z.of_nat 31) with 2147483648; auto with zarith.
case (phi_bounded j1); auto with zarith.
set (s := iter312_sqrt 31 (fun _ _ j : int31 => j) ih il Tn).
intros Hs1 Hs2.
generalize (spec_mul_c s s); case mul31c.
simpl zn2z_to_Z; intros HH.
assert ([|s|] = 0).
{ symmetry in HH. rewrite Z.mul_eq_0 in HH. destruct HH; auto. }
contradict Hs2; apply Z.le_ngt; rewrite H.
change ((0 + 1) ^ 2) with 1.
apply Z.le_trans with (2 ^ Z.of_nat size / 4 * base).
simpl; auto with zarith.
apply Z.le_trans with ([|ih|] * base); auto with zarith.
unfold phi2; case (phi_bounded il); auto with zarith.
intros ih1 il1.
change [||WW ih1 il1||] with (phi2 ih1 il1).
intros Hihl1.
generalize (spec_sub_c il il1).
case sub31c; intros il2 Hil2.
rewrite spec_compare; case Z.compare_spec.
unfold interp_carry in *.
intros H1; split.
rewrite Z.pow_2_r, <- Hihl1.
unfold phi2; ring[Hil2 H1].
replace [|il2|] with (phi2 ih il - phi2 ih1 il1).
rewrite Hihl1.
rewrite <-Hbin in Hs2; auto with zarith.
unfold phi2; rewrite H1, Hil2; ring.
unfold interp_carry.
intros H1; contradict Hs1.
apply Z.lt_nge; rewrite Z.pow_2_r, <-Hihl1.
unfold phi2.
case (phi_bounded il); intros _ H2.
apply Z.lt_le_trans with (([|ih|] + 1) * base + 0).
rewrite Z.mul_add_distr_r, Z.add_0_r; auto with zarith.
case (phi_bounded il1); intros H3 _.
apply Z.add_le_mono; auto with zarith.
unfold interp_carry in *; change (1 * 2 ^ Z.of_nat size) with base.
rewrite Z.pow_2_r, <- Hihl1, Hil2.
intros H1.
rewrite <- Z.le_succ_l, <- Z.add_1_r in H1.
Z.le_elim H1.
contradict Hs2; apply Z.le_ngt.
replace (([|s|] + 1) ^ 2) with (phi2 ih1 il1 + 2 * [|s|] + 1).
unfold phi2.
case (phi_bounded il); intros Hpil _.
assert (Hl1l: [|il1|] <= [|il|]).
{ case (phi_bounded il2); rewrite Hil2; auto with zarith. }
assert ([|ih1|] * base + 2 * [|s|] + 1 <= [|ih|] * base); auto with zarith.
case (phi_bounded s); change (2 ^ Z.of_nat size) with base; intros _ Hps.
case (phi_bounded ih1); intros Hpih1 _; auto with zarith.
apply Z.le_trans with (([|ih1|] + 2) * base); auto with zarith.
rewrite Z.mul_add_distr_r.
assert (2 * [|s|] + 1 <= 2 * base); auto with zarith.
rewrite Hihl1, Hbin; auto.
split.
unfold phi2; rewrite <- H1; ring.
replace (base + ([|il|] - [|il1|])) with (phi2 ih il - ([|s|] * [|s|])).
rewrite <-Hbin in Hs2; auto with zarith.
rewrite <- Hihl1; unfold phi2; rewrite <- H1; ring.
unfold interp_carry in Hil2 |- *.
unfold interp_carry; change (1 * 2 ^ Z.of_nat size) with base.
assert (Hsih: [|ih - 1|] = [|ih|] - 1).
{ rewrite spec_sub, Zmod_small; auto; change [|1|] with 1.
case (phi_bounded ih); intros H1 H2.
generalize Hih; change (2 ^ Z.of_nat size / 4) with 536870912.
split; auto with zarith. }
rewrite spec_compare; case Z.compare_spec.
rewrite Hsih.
intros H1; split.
rewrite Z.pow_2_r, <- Hihl1.
unfold phi2; rewrite <-H1.
transitivity ([|ih|] * base + [|il1|] + ([|il|] - [|il1|])).
ring.
rewrite <-Hil2.
change (2 ^ Z.of_nat size) with base; ring.
replace [|il2|] with (phi2 ih il - phi2 ih1 il1).
rewrite Hihl1.
rewrite <-Hbin in Hs2; auto with zarith.
unfold phi2.
rewrite <-H1.
ring_simplify.
transitivity (base + ([|il|] - [|il1|])).
ring.
rewrite <-Hil2.
change (2 ^ Z.of_nat size) with base; ring.
rewrite Hsih; intros H1.
assert (He: [|ih|] = [|ih1|]).
{ apply Z.le_antisymm; auto with zarith.
case (Z.le_gt_cases [|ih1|] [|ih|]); auto; intros H2.
contradict Hs1; apply Z.lt_nge; rewrite Z.pow_2_r, <-Hihl1.
unfold phi2.
case (phi_bounded il); change (2 ^ Z.of_nat size) with base;
intros _ Hpil1.
apply Z.lt_le_trans with (([|ih|] + 1) * base).
rewrite Z.mul_add_distr_r, Z.mul_1_l; auto with zarith.
case (phi_bounded il1); intros Hpil2 _.
apply Z.le_trans with (([|ih1|]) * base); auto with zarith. }
rewrite Z.pow_2_r, <-Hihl1; unfold phi2; rewrite <-He.
contradict Hs1; apply Z.lt_nge; rewrite Z.pow_2_r, <-Hihl1.
unfold phi2; rewrite He.
assert (phi il - phi il1 < 0); auto with zarith.
rewrite <-Hil2.
case (phi_bounded il2); auto with zarith.
intros H1.
rewrite Z.pow_2_r, <-Hihl1.
assert (H2 : [|ih1|]+2 <= [|ih|]); auto with zarith.
Z.le_elim H2.
contradict Hs2; apply Z.le_ngt.
replace (([|s|] + 1) ^ 2) with (phi2 ih1 il1 + 2 * [|s|] + 1).
unfold phi2.
assert ([|ih1|] * base + 2 * phi s + 1 <= [|ih|] * base + ([|il|] - [|il1|]));
auto with zarith.
rewrite <-Hil2.
change (-1 * 2 ^ Z.of_nat size) with (-base).
case (phi_bounded il2); intros Hpil2 _.
apply Z.le_trans with ([|ih|] * base + - base); auto with zarith.
case (phi_bounded s); change (2 ^ Z.of_nat size) with base; intros _ Hps.
assert (2 * [|s|] + 1 <= 2 * base); auto with zarith.
apply Z.le_trans with ([|ih1|] * base + 2 * base); auto with zarith.
assert (Hi: ([|ih1|] + 3) * base <= [|ih|] * base); auto with zarith.
rewrite Z.mul_add_distr_r in Hi; auto with zarith.
rewrite Hihl1, Hbin; auto.
unfold phi2; rewrite <-H2.
split.
replace [|il|] with (([|il|] - [|il1|]) + [|il1|]); try ring.
rewrite <-Hil2.
change (-1 * 2 ^ Z.of_nat size) with (-base); ring.
replace (base + [|il2|]) with (phi2 ih il - phi2 ih1 il1).
rewrite Hihl1.
rewrite <-Hbin in Hs2; auto with zarith.
unfold phi2; rewrite <-H2.
replace [|il|] with (([|il|] - [|il1|]) + [|il1|]); try ring.
rewrite <-Hil2.
change (-1 * 2 ^ Z.of_nat size) with (-base); ring.
Qed.
(** [iszero] *)
Lemma spec_eq0 : forall x, ZnZ.eq0 x = true -> [|x|] = 0.
Proof.
clear; unfold ZnZ.eq0, int31_ops.
unfold compare31; intros.
change [|0|] with 0 in H.
apply Z.compare_eq.
now destruct ([|x|] ?= 0).
Qed.
(* Even *)
Lemma spec_is_even : forall x,
if ZnZ.is_even x then [|x|] mod 2 = 0 else [|x|] mod 2 = 1.
Proof.
unfold ZnZ.is_even, int31_ops; intros.
generalize (spec_div x 2).
destruct (x/2)%int31 as (q,r); intros.
unfold compare31.
change [|2|] with 2 in H.
change [|0|] with 0.
destruct H; auto with zarith.
replace ([|x|] mod 2) with [|r|].
destruct H; auto with zarith.
case Z.compare_spec; auto with zarith.
apply Zmod_unique with [|q|]; auto with zarith.
Qed.
(* Bitwise *)
Lemma log2_phi_bounded x : Z.log2 [|x|] < Z.of_nat size.
Proof.
destruct (phi_bounded x) as (H,H').
Z.le_elim H.
- now apply Z.log2_lt_pow2.
- now rewrite <- H.
Qed.
Lemma spec_lor x y : [| ZnZ.lor x y |] = Z.lor [|x|] [|y|].
Proof.
unfold ZnZ.lor,int31_ops. unfold lor31.
rewrite phi_phi_inv.
apply Z.mod_small; split; trivial.
- apply Z.lor_nonneg; split; apply phi_bounded.
- apply Z.log2_lt_cancel. rewrite Z.log2_pow2 by easy.
rewrite Z.log2_lor; try apply phi_bounded.
apply Z.max_lub_lt; apply log2_phi_bounded.
Qed.
Lemma spec_land x y : [| ZnZ.land x y |] = Z.land [|x|] [|y|].
Proof.
unfold ZnZ.land, int31_ops. unfold land31.
rewrite phi_phi_inv.
apply Z.mod_small; split; trivial.
- apply Z.land_nonneg; left; apply phi_bounded.
- apply Z.log2_lt_cancel. rewrite Z.log2_pow2 by easy.
eapply Z.le_lt_trans.
apply Z.log2_land; try apply phi_bounded.
apply Z.min_lt_iff; left; apply log2_phi_bounded.
Qed.
Lemma spec_lxor x y : [| ZnZ.lxor x y |] = Z.lxor [|x|] [|y|].
Proof.
unfold ZnZ.lxor, int31_ops. unfold lxor31.
rewrite phi_phi_inv.
apply Z.mod_small; split; trivial.
- apply Z.lxor_nonneg; split; intros; apply phi_bounded.
- apply Z.log2_lt_cancel. rewrite Z.log2_pow2 by easy.
eapply Z.le_lt_trans.
apply Z.log2_lxor; try apply phi_bounded.
apply Z.max_lub_lt; apply log2_phi_bounded.
Qed.
Global Instance int31_specs : ZnZ.Specs int31_ops := {
spec_to_Z := phi_bounded;
spec_of_pos := positive_to_int31_spec;
spec_zdigits := spec_zdigits;
spec_more_than_1_digit := spec_more_than_1_digit;
spec_0 := spec_0;
spec_1 := spec_1;
spec_m1 := spec_m1;
spec_compare := spec_compare;
spec_eq0 := spec_eq0;
spec_opp_c := spec_opp_c;
spec_opp := spec_opp;
spec_opp_carry := spec_opp_carry;
spec_succ_c := spec_succ_c;
spec_add_c := spec_add_c;
spec_add_carry_c := spec_add_carry_c;
spec_succ := spec_succ;
spec_add := spec_add;
spec_add_carry := spec_add_carry;
spec_pred_c := spec_pred_c;
spec_sub_c := spec_sub_c;
spec_sub_carry_c := spec_sub_carry_c;
spec_pred := spec_pred;
spec_sub := spec_sub;
spec_sub_carry := spec_sub_carry;
spec_mul_c := spec_mul_c;
spec_mul := spec_mul;
spec_square_c := spec_square_c;
spec_div21 := spec_div21;
spec_div_gt := fun a b _ => spec_div a b;
spec_div := spec_div;
spec_modulo_gt := fun a b _ => spec_mod a b;
spec_modulo := spec_mod;
spec_gcd_gt := fun a b _ => spec_gcd a b;
spec_gcd := spec_gcd;
spec_head00 := spec_head00;
spec_head0 := spec_head0;
spec_tail00 := spec_tail00;
spec_tail0 := spec_tail0;
spec_add_mul_div := spec_add_mul_div;
spec_pos_mod := spec_pos_mod;
spec_is_even := spec_is_even;
spec_sqrt2 := spec_sqrt2;
spec_sqrt := spec_sqrt;
spec_lor := spec_lor;
spec_land := spec_land;
spec_lxor := spec_lxor }.
End Int31_Specs.
Module Int31Cyclic <: CyclicType.
Definition t := int31.
Definition ops := int31_ops.
Definition specs := int31_specs.
End Int31Cyclic.
|
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2013.
module t
(
input logic clk,
input logic daten,
input logic [8:0] datval,
output logic signed [3:0][3:0][35:0] datao
);
logic signed [3:0][3:0][3:0][8:0] datat;
genvar i;
generate
for (i=0; i<4; i++)begin
testio dut(.clk(clk), .arr3d_in(datat[i]), .arr2d_out(datao[i]));
end
endgenerate
genvar j;
generate
for (i=0; i<4; i++) begin
for (j=0; j<4; j++) begin
always_comb datat[i][j][0] = daten ? 9'h0 : datval;
always_comb datat[i][j][1] = daten ? 9'h1 : datval;
always_comb datat[i][j][2] = daten ? 9'h2 : datval;
always_comb datat[i][j][3] = daten ? 9'h3 : datval;
end
end
endgenerate
endmodule
module testio
(
input clk,
input logic signed [3:0] [3:0] [8:0] arr3d_in,
output logic signed [3:0] [35:0] arr2d_out
);
logic signed [3:0] [35:0] ar2d_out_pre;
always_comb ar2d_out_pre[0][35:0] = {arr3d_in[0][0][8:0], arr3d_in[0][1][8:0], arr3d_in[0][2][8:0], arr3d_in[0][3][8:0]};
always_comb ar2d_out_pre[0][35:0] = {arr3d_in[0][0][8:0], arr3d_in[0][1][8:0], arr3d_in[0][2][8:0], arr3d_in[0][3][8:0]};
always_comb ar2d_out_pre[0][35:0] = {arr3d_in[0][0][8:0], arr3d_in[0][1][8:0], arr3d_in[0][2][8:0], arr3d_in[0][3][8:0]};
always_comb ar2d_out_pre[0][35:0] = {arr3d_in[0][0][8:0], arr3d_in[0][1][8:0], arr3d_in[0][2][8:0], arr3d_in[0][3][8:0]};
always_ff @(posedge clk) begin
if (clk)
arr2d_out <= ar2d_out_pre;
end
endmodule
|
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2013.
module t
(
input logic clk,
input logic daten,
input logic [8:0] datval,
output logic signed [3:0][3:0][35:0] datao
);
logic signed [3:0][3:0][3:0][8:0] datat;
genvar i;
generate
for (i=0; i<4; i++)begin
testio dut(.clk(clk), .arr3d_in(datat[i]), .arr2d_out(datao[i]));
end
endgenerate
genvar j;
generate
for (i=0; i<4; i++) begin
for (j=0; j<4; j++) begin
always_comb datat[i][j][0] = daten ? 9'h0 : datval;
always_comb datat[i][j][1] = daten ? 9'h1 : datval;
always_comb datat[i][j][2] = daten ? 9'h2 : datval;
always_comb datat[i][j][3] = daten ? 9'h3 : datval;
end
end
endgenerate
endmodule
module testio
(
input clk,
input logic signed [3:0] [3:0] [8:0] arr3d_in,
output logic signed [3:0] [35:0] arr2d_out
);
logic signed [3:0] [35:0] ar2d_out_pre;
always_comb ar2d_out_pre[0][35:0] = {arr3d_in[0][0][8:0], arr3d_in[0][1][8:0], arr3d_in[0][2][8:0], arr3d_in[0][3][8:0]};
always_comb ar2d_out_pre[0][35:0] = {arr3d_in[0][0][8:0], arr3d_in[0][1][8:0], arr3d_in[0][2][8:0], arr3d_in[0][3][8:0]};
always_comb ar2d_out_pre[0][35:0] = {arr3d_in[0][0][8:0], arr3d_in[0][1][8:0], arr3d_in[0][2][8:0], arr3d_in[0][3][8:0]};
always_comb ar2d_out_pre[0][35:0] = {arr3d_in[0][0][8:0], arr3d_in[0][1][8:0], arr3d_in[0][2][8:0], arr3d_in[0][3][8:0]};
always_ff @(posedge clk) begin
if (clk)
arr2d_out <= ar2d_out_pre;
end
endmodule
|
//*****************************************************************************
// (c) Copyright 2008 - 2013 Xilinx, Inc. All rights reserved.
//
// This file contains confidential and proprietary information
// of Xilinx, Inc. and is protected under U.S. and
// international copyright and other intellectual property
// laws.
//
// DISCLAIMER
// This disclaimer is not a license and does not grant any
// rights to the materials distributed herewith. Except as
// otherwise provided in a valid license issued to you by
// Xilinx, and to the maximum extent permitted by applicable
// law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND
// WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES
// AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
// BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-
// INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and
// (2) Xilinx shall not be liable (whether in contract or tort,
// including negligence, or under any other theory of
// liability) for any loss or damage of any kind or nature
// related to, arising under or in connection with these
// materials, including for any direct, or any indirect,
// special, incidental, or consequential loss or damage
// (including loss of data, profits, goodwill, or any type of
// loss or damage suffered as a result of any action brought
// by a third party) even if such damage or loss was
// reasonably foreseeable or Xilinx had been advised of the
// possibility of the same.
//
// CRITICAL APPLICATIONS
// Xilinx products are not designed or intended to be fail-
// safe, or for use in any application requiring fail-safe
// performance, such as life-support or safety devices or
// systems, Class III medical devices, nuclear facilities,
// applications related to the deployment of airbags, or any
// other applications that could lead to death, personal
// injury, or severe property or environmental damage
// (individually and collectively, "Critical
// Applications"). Customer assumes the sole risk and
// liability of any use of Xilinx products in Critical
// Applications, subject only to applicable laws and
// regulations governing limitations on product liability.
//
// THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS
// PART OF THIS FILE AT ALL TIMES.
//
//*****************************************************************************
// ____ ____
// / /\/ /
// /___/ \ / Vendor : Xilinx
// \ \ \/ Version : %version
// \ \ Application : MIG
// / / Filename : ecc_buf.v
// /___/ /\ Date Last Modified : $date$
// \ \ / \ Date Created : Tue Jun 30 2009
// \___\/\___\
//
//Device : 7-Series
//Design Name : DDR3 SDRAM
//Purpose :
//Reference :
//Revision History :
//*****************************************************************************
`timescale 1ps/1ps
module mig_7series_v1_9_ecc_buf
#(
parameter TCQ = 100,
parameter PAYLOAD_WIDTH = 64,
parameter DATA_BUF_ADDR_WIDTH = 4,
parameter DATA_BUF_OFFSET_WIDTH = 1,
parameter DATA_WIDTH = 64,
parameter nCK_PER_CLK = 4
)
(
/*AUTOARG*/
// Outputs
rd_merge_data,
// Inputs
clk, rst, rd_data_addr, rd_data_offset, wr_data_addr,
wr_data_offset, rd_data, wr_ecc_buf
);
input clk;
input rst;
// RMW architecture supports only 16 data buffer entries.
// Allow DATA_BUF_ADDR_WIDTH to be greater than 4, but
// assume the upper bits are used for tagging.
input [DATA_BUF_ADDR_WIDTH-1:0] rd_data_addr;
input [DATA_BUF_OFFSET_WIDTH-1:0] rd_data_offset;
wire [4:0] buf_wr_addr;
input [DATA_BUF_ADDR_WIDTH-1:0] wr_data_addr;
input [DATA_BUF_OFFSET_WIDTH-1:0] wr_data_offset;
reg [4:0] buf_rd_addr_r;
generate
if (DATA_BUF_ADDR_WIDTH >= 4) begin : ge_4_addr_bits
always @(posedge clk)
buf_rd_addr_r <= #TCQ{wr_data_addr[3:0], wr_data_offset};
assign buf_wr_addr = {rd_data_addr[3:0], rd_data_offset};
end
else begin : lt_4_addr_bits
always @(posedge clk)
buf_rd_addr_r <= #TCQ{{4-DATA_BUF_ADDR_WIDTH{1'b0}},
wr_data_addr[DATA_BUF_ADDR_WIDTH-1:0],
wr_data_offset};
assign buf_wr_addr = {{4-DATA_BUF_ADDR_WIDTH{1'b0}},
rd_data_addr[DATA_BUF_ADDR_WIDTH-1:0],
rd_data_offset};
end
endgenerate
input [2*nCK_PER_CLK*PAYLOAD_WIDTH-1:0] rd_data;
reg [2*nCK_PER_CLK*DATA_WIDTH-1:0] payload;
integer h;
always @(/*AS*/rd_data)
for (h=0; h<2*nCK_PER_CLK; h=h+1)
payload[h*DATA_WIDTH+:DATA_WIDTH] =
rd_data[h*PAYLOAD_WIDTH+:DATA_WIDTH];
input wr_ecc_buf;
localparam BUF_WIDTH = 2*nCK_PER_CLK*DATA_WIDTH;
localparam FULL_RAM_CNT = (BUF_WIDTH/6);
localparam REMAINDER = BUF_WIDTH % 6;
localparam RAM_CNT = FULL_RAM_CNT + ((REMAINDER == 0 ) ? 0 : 1);
localparam RAM_WIDTH = (RAM_CNT*6);
wire [RAM_WIDTH-1:0] buf_out_data;
generate
begin : ram_buf
wire [RAM_WIDTH-1:0] buf_in_data;
if (REMAINDER == 0)
assign buf_in_data = payload;
else
assign buf_in_data = {{6-REMAINDER{1'b0}}, payload};
genvar i;
for (i=0; i<RAM_CNT; i=i+1) begin : rd_buffer_ram
RAM32M
#(.INIT_A(64'h0000000000000000),
.INIT_B(64'h0000000000000000),
.INIT_C(64'h0000000000000000),
.INIT_D(64'h0000000000000000)
) RAM32M0 (
.DOA(buf_out_data[((i*6)+4)+:2]),
.DOB(buf_out_data[((i*6)+2)+:2]),
.DOC(buf_out_data[((i*6)+0)+:2]),
.DOD(),
.DIA(buf_in_data[((i*6)+4)+:2]),
.DIB(buf_in_data[((i*6)+2)+:2]),
.DIC(buf_in_data[((i*6)+0)+:2]),
.DID(2'b0),
.ADDRA(buf_rd_addr_r),
.ADDRB(buf_rd_addr_r),
.ADDRC(buf_rd_addr_r),
.ADDRD(buf_wr_addr),
.WE(wr_ecc_buf),
.WCLK(clk)
);
end // block: rd_buffer_ram
end
endgenerate
output wire [2*nCK_PER_CLK*DATA_WIDTH-1:0] rd_merge_data;
assign rd_merge_data = buf_out_data[2*nCK_PER_CLK*DATA_WIDTH-1:0];
endmodule
|
//*****************************************************************************
// (c) Copyright 2008 - 2013 Xilinx, Inc. All rights reserved.
//
// This file contains confidential and proprietary information
// of Xilinx, Inc. and is protected under U.S. and
// international copyright and other intellectual property
// laws.
//
// DISCLAIMER
// This disclaimer is not a license and does not grant any
// rights to the materials distributed herewith. Except as
// otherwise provided in a valid license issued to you by
// Xilinx, and to the maximum extent permitted by applicable
// law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND
// WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES
// AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
// BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-
// INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and
// (2) Xilinx shall not be liable (whether in contract or tort,
// including negligence, or under any other theory of
// liability) for any loss or damage of any kind or nature
// related to, arising under or in connection with these
// materials, including for any direct, or any indirect,
// special, incidental, or consequential loss or damage
// (including loss of data, profits, goodwill, or any type of
// loss or damage suffered as a result of any action brought
// by a third party) even if such damage or loss was
// reasonably foreseeable or Xilinx had been advised of the
// possibility of the same.
//
// CRITICAL APPLICATIONS
// Xilinx products are not designed or intended to be fail-
// safe, or for use in any application requiring fail-safe
// performance, such as life-support or safety devices or
// systems, Class III medical devices, nuclear facilities,
// applications related to the deployment of airbags, or any
// other applications that could lead to death, personal
// injury, or severe property or environmental damage
// (individually and collectively, "Critical
// Applications"). Customer assumes the sole risk and
// liability of any use of Xilinx products in Critical
// Applications, subject only to applicable laws and
// regulations governing limitations on product liability.
//
// THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS
// PART OF THIS FILE AT ALL TIMES.
//
//*****************************************************************************
// ____ ____
// / /\/ /
// /___/ \ / Vendor : Xilinx
// \ \ \/ Version : %version
// \ \ Application : MIG
// / / Filename : ecc_buf.v
// /___/ /\ Date Last Modified : $date$
// \ \ / \ Date Created : Tue Jun 30 2009
// \___\/\___\
//
//Device : 7-Series
//Design Name : DDR3 SDRAM
//Purpose :
//Reference :
//Revision History :
//*****************************************************************************
`timescale 1ps/1ps
module mig_7series_v1_9_ecc_buf
#(
parameter TCQ = 100,
parameter PAYLOAD_WIDTH = 64,
parameter DATA_BUF_ADDR_WIDTH = 4,
parameter DATA_BUF_OFFSET_WIDTH = 1,
parameter DATA_WIDTH = 64,
parameter nCK_PER_CLK = 4
)
(
/*AUTOARG*/
// Outputs
rd_merge_data,
// Inputs
clk, rst, rd_data_addr, rd_data_offset, wr_data_addr,
wr_data_offset, rd_data, wr_ecc_buf
);
input clk;
input rst;
// RMW architecture supports only 16 data buffer entries.
// Allow DATA_BUF_ADDR_WIDTH to be greater than 4, but
// assume the upper bits are used for tagging.
input [DATA_BUF_ADDR_WIDTH-1:0] rd_data_addr;
input [DATA_BUF_OFFSET_WIDTH-1:0] rd_data_offset;
wire [4:0] buf_wr_addr;
input [DATA_BUF_ADDR_WIDTH-1:0] wr_data_addr;
input [DATA_BUF_OFFSET_WIDTH-1:0] wr_data_offset;
reg [4:0] buf_rd_addr_r;
generate
if (DATA_BUF_ADDR_WIDTH >= 4) begin : ge_4_addr_bits
always @(posedge clk)
buf_rd_addr_r <= #TCQ{wr_data_addr[3:0], wr_data_offset};
assign buf_wr_addr = {rd_data_addr[3:0], rd_data_offset};
end
else begin : lt_4_addr_bits
always @(posedge clk)
buf_rd_addr_r <= #TCQ{{4-DATA_BUF_ADDR_WIDTH{1'b0}},
wr_data_addr[DATA_BUF_ADDR_WIDTH-1:0],
wr_data_offset};
assign buf_wr_addr = {{4-DATA_BUF_ADDR_WIDTH{1'b0}},
rd_data_addr[DATA_BUF_ADDR_WIDTH-1:0],
rd_data_offset};
end
endgenerate
input [2*nCK_PER_CLK*PAYLOAD_WIDTH-1:0] rd_data;
reg [2*nCK_PER_CLK*DATA_WIDTH-1:0] payload;
integer h;
always @(/*AS*/rd_data)
for (h=0; h<2*nCK_PER_CLK; h=h+1)
payload[h*DATA_WIDTH+:DATA_WIDTH] =
rd_data[h*PAYLOAD_WIDTH+:DATA_WIDTH];
input wr_ecc_buf;
localparam BUF_WIDTH = 2*nCK_PER_CLK*DATA_WIDTH;
localparam FULL_RAM_CNT = (BUF_WIDTH/6);
localparam REMAINDER = BUF_WIDTH % 6;
localparam RAM_CNT = FULL_RAM_CNT + ((REMAINDER == 0 ) ? 0 : 1);
localparam RAM_WIDTH = (RAM_CNT*6);
wire [RAM_WIDTH-1:0] buf_out_data;
generate
begin : ram_buf
wire [RAM_WIDTH-1:0] buf_in_data;
if (REMAINDER == 0)
assign buf_in_data = payload;
else
assign buf_in_data = {{6-REMAINDER{1'b0}}, payload};
genvar i;
for (i=0; i<RAM_CNT; i=i+1) begin : rd_buffer_ram
RAM32M
#(.INIT_A(64'h0000000000000000),
.INIT_B(64'h0000000000000000),
.INIT_C(64'h0000000000000000),
.INIT_D(64'h0000000000000000)
) RAM32M0 (
.DOA(buf_out_data[((i*6)+4)+:2]),
.DOB(buf_out_data[((i*6)+2)+:2]),
.DOC(buf_out_data[((i*6)+0)+:2]),
.DOD(),
.DIA(buf_in_data[((i*6)+4)+:2]),
.DIB(buf_in_data[((i*6)+2)+:2]),
.DIC(buf_in_data[((i*6)+0)+:2]),
.DID(2'b0),
.ADDRA(buf_rd_addr_r),
.ADDRB(buf_rd_addr_r),
.ADDRC(buf_rd_addr_r),
.ADDRD(buf_wr_addr),
.WE(wr_ecc_buf),
.WCLK(clk)
);
end // block: rd_buffer_ram
end
endgenerate
output wire [2*nCK_PER_CLK*DATA_WIDTH-1:0] rd_merge_data;
assign rd_merge_data = buf_out_data[2*nCK_PER_CLK*DATA_WIDTH-1:0];
endmodule
|
//*****************************************************************************
// (c) Copyright 2008 - 2013 Xilinx, Inc. All rights reserved.
//
// This file contains confidential and proprietary information
// of Xilinx, Inc. and is protected under U.S. and
// international copyright and other intellectual property
// laws.
//
// DISCLAIMER
// This disclaimer is not a license and does not grant any
// rights to the materials distributed herewith. Except as
// otherwise provided in a valid license issued to you by
// Xilinx, and to the maximum extent permitted by applicable
// law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND
// WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES
// AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
// BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-
// INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and
// (2) Xilinx shall not be liable (whether in contract or tort,
// including negligence, or under any other theory of
// liability) for any loss or damage of any kind or nature
// related to, arising under or in connection with these
// materials, including for any direct, or any indirect,
// special, incidental, or consequential loss or damage
// (including loss of data, profits, goodwill, or any type of
// loss or damage suffered as a result of any action brought
// by a third party) even if such damage or loss was
// reasonably foreseeable or Xilinx had been advised of the
// possibility of the same.
//
// CRITICAL APPLICATIONS
// Xilinx products are not designed or intended to be fail-
// safe, or for use in any application requiring fail-safe
// performance, such as life-support or safety devices or
// systems, Class III medical devices, nuclear facilities,
// applications related to the deployment of airbags, or any
// other applications that could lead to death, personal
// injury, or severe property or environmental damage
// (individually and collectively, "Critical
// Applications"). Customer assumes the sole risk and
// liability of any use of Xilinx products in Critical
// Applications, subject only to applicable laws and
// regulations governing limitations on product liability.
//
// THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS
// PART OF THIS FILE AT ALL TIMES.
//
//*****************************************************************************
// ____ ____
// / /\/ /
// /___/ \ / Vendor : Xilinx
// \ \ \/ Version : %version
// \ \ Application : MIG
// / / Filename : ecc_buf.v
// /___/ /\ Date Last Modified : $date$
// \ \ / \ Date Created : Tue Jun 30 2009
// \___\/\___\
//
//Device : 7-Series
//Design Name : DDR3 SDRAM
//Purpose :
//Reference :
//Revision History :
//*****************************************************************************
`timescale 1ps/1ps
module mig_7series_v1_9_ecc_buf
#(
parameter TCQ = 100,
parameter PAYLOAD_WIDTH = 64,
parameter DATA_BUF_ADDR_WIDTH = 4,
parameter DATA_BUF_OFFSET_WIDTH = 1,
parameter DATA_WIDTH = 64,
parameter nCK_PER_CLK = 4
)
(
/*AUTOARG*/
// Outputs
rd_merge_data,
// Inputs
clk, rst, rd_data_addr, rd_data_offset, wr_data_addr,
wr_data_offset, rd_data, wr_ecc_buf
);
input clk;
input rst;
// RMW architecture supports only 16 data buffer entries.
// Allow DATA_BUF_ADDR_WIDTH to be greater than 4, but
// assume the upper bits are used for tagging.
input [DATA_BUF_ADDR_WIDTH-1:0] rd_data_addr;
input [DATA_BUF_OFFSET_WIDTH-1:0] rd_data_offset;
wire [4:0] buf_wr_addr;
input [DATA_BUF_ADDR_WIDTH-1:0] wr_data_addr;
input [DATA_BUF_OFFSET_WIDTH-1:0] wr_data_offset;
reg [4:0] buf_rd_addr_r;
generate
if (DATA_BUF_ADDR_WIDTH >= 4) begin : ge_4_addr_bits
always @(posedge clk)
buf_rd_addr_r <= #TCQ{wr_data_addr[3:0], wr_data_offset};
assign buf_wr_addr = {rd_data_addr[3:0], rd_data_offset};
end
else begin : lt_4_addr_bits
always @(posedge clk)
buf_rd_addr_r <= #TCQ{{4-DATA_BUF_ADDR_WIDTH{1'b0}},
wr_data_addr[DATA_BUF_ADDR_WIDTH-1:0],
wr_data_offset};
assign buf_wr_addr = {{4-DATA_BUF_ADDR_WIDTH{1'b0}},
rd_data_addr[DATA_BUF_ADDR_WIDTH-1:0],
rd_data_offset};
end
endgenerate
input [2*nCK_PER_CLK*PAYLOAD_WIDTH-1:0] rd_data;
reg [2*nCK_PER_CLK*DATA_WIDTH-1:0] payload;
integer h;
always @(/*AS*/rd_data)
for (h=0; h<2*nCK_PER_CLK; h=h+1)
payload[h*DATA_WIDTH+:DATA_WIDTH] =
rd_data[h*PAYLOAD_WIDTH+:DATA_WIDTH];
input wr_ecc_buf;
localparam BUF_WIDTH = 2*nCK_PER_CLK*DATA_WIDTH;
localparam FULL_RAM_CNT = (BUF_WIDTH/6);
localparam REMAINDER = BUF_WIDTH % 6;
localparam RAM_CNT = FULL_RAM_CNT + ((REMAINDER == 0 ) ? 0 : 1);
localparam RAM_WIDTH = (RAM_CNT*6);
wire [RAM_WIDTH-1:0] buf_out_data;
generate
begin : ram_buf
wire [RAM_WIDTH-1:0] buf_in_data;
if (REMAINDER == 0)
assign buf_in_data = payload;
else
assign buf_in_data = {{6-REMAINDER{1'b0}}, payload};
genvar i;
for (i=0; i<RAM_CNT; i=i+1) begin : rd_buffer_ram
RAM32M
#(.INIT_A(64'h0000000000000000),
.INIT_B(64'h0000000000000000),
.INIT_C(64'h0000000000000000),
.INIT_D(64'h0000000000000000)
) RAM32M0 (
.DOA(buf_out_data[((i*6)+4)+:2]),
.DOB(buf_out_data[((i*6)+2)+:2]),
.DOC(buf_out_data[((i*6)+0)+:2]),
.DOD(),
.DIA(buf_in_data[((i*6)+4)+:2]),
.DIB(buf_in_data[((i*6)+2)+:2]),
.DIC(buf_in_data[((i*6)+0)+:2]),
.DID(2'b0),
.ADDRA(buf_rd_addr_r),
.ADDRB(buf_rd_addr_r),
.ADDRC(buf_rd_addr_r),
.ADDRD(buf_wr_addr),
.WE(wr_ecc_buf),
.WCLK(clk)
);
end // block: rd_buffer_ram
end
endgenerate
output wire [2*nCK_PER_CLK*DATA_WIDTH-1:0] rd_merge_data;
assign rd_merge_data = buf_out_data[2*nCK_PER_CLK*DATA_WIDTH-1:0];
endmodule
|
// ----------------------------------------------------------------------
// Copyright (c) 2016, The Regents of the University of California All
// rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// * Neither the name of The Regents of the University of California
// nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL REGENTS OF THE
// UNIVERSITY OF CALIFORNIA BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
// OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
// TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
// ----------------------------------------------------------------------
//----------------------------------------------------------------------------
// Filename: tx_port_buffer_64.v
// Version: 1.00.a
// Verilog Standard: Verilog-2001
// Description: Wraps a FIFO for saving channel data and provides a
// registered read output. Retains unread words from reads that are a length
// which is not a multiple of the data bus width (C_FIFO_DATA_WIDTH). Data is
// available 5 cycles after RD_EN is asserted (not 1, like a traditional FIFO).
// Author: Matt Jacobsen
// History: @mattj: Version 2.0
//-----------------------------------------------------------------------------
`timescale 1ns/1ns
module tx_port_buffer_64 #(
parameter C_FIFO_DATA_WIDTH = 9'd64,
parameter C_FIFO_DEPTH = 512,
// Local parameters
parameter C_FIFO_DEPTH_WIDTH = clog2((2**clog2(C_FIFO_DEPTH))+1),
parameter C_RD_EN_HIST = 2,
parameter C_FIFO_RD_EN_HIST = 2,
parameter C_CONSUME_HIST = 3,
parameter C_COUNT_HIST = 3,
parameter C_LEN_LAST_HIST = 1
)
(
input RST,
input CLK,
input LEN_VALID, // Transfer length is valid
input [0:0] LEN_LSB, // LSBs of transfer length
input LEN_LAST, // Last transfer in transaction
input [C_FIFO_DATA_WIDTH-1:0] WR_DATA, // Input data
input WR_EN, // Input data write enable
output [C_FIFO_DEPTH_WIDTH-1:0] WR_COUNT, // Input data FIFO is full
output [C_FIFO_DATA_WIDTH-1:0] RD_DATA, // Output data
input RD_EN // Output data read enable
);
`include "functions.vh"
reg [1:0] rRdPtr=0, _rRdPtr=0;
reg [1:0] rWrPtr=0, _rWrPtr=0;
reg [3:0] rLenLSB=0, _rLenLSB=0;
reg [3:0] rLenLast=0, _rLenLast=0;
reg rLenValid=0, _rLenValid=0;
reg rRen=0, _rRen=0;
reg [1:0] rCount=0, _rCount=0;
reg [(C_COUNT_HIST*2)-1:0] rCountHist={C_COUNT_HIST{2'd0}}, _rCountHist={C_COUNT_HIST{2'd0}};
reg [C_LEN_LAST_HIST-1:0] rLenLastHist={C_LEN_LAST_HIST{1'd0}}, _rLenLastHist={C_LEN_LAST_HIST{1'd0}};
reg [C_RD_EN_HIST-1:0] rRdEnHist={C_RD_EN_HIST{1'd0}}, _rRdEnHist={C_RD_EN_HIST{1'd0}};
reg rFifoRdEn=0, _rFifoRdEn=0;
reg [C_FIFO_RD_EN_HIST-1:0] rFifoRdEnHist={C_FIFO_RD_EN_HIST{1'd0}}, _rFifoRdEnHist={C_FIFO_RD_EN_HIST{1'd0}};
reg [(C_CONSUME_HIST*2)-1:0] rConsumedHist={C_CONSUME_HIST{2'd0}}, _rConsumedHist={C_CONSUME_HIST{2'd0}};
reg [C_FIFO_DATA_WIDTH-1:0] rFifoData={C_FIFO_DATA_WIDTH{1'd0}}, _rFifoData={C_FIFO_DATA_WIDTH{1'd0}};
reg [95:0] rData=96'd0, _rData=96'd0;
wire [C_FIFO_DATA_WIDTH-1:0] wFifoData;
assign RD_DATA = rData[0 +:C_FIFO_DATA_WIDTH];
// Buffer the input signals that come from outside the tx_port.
always @ (posedge CLK) begin
rLenValid <= #1 (RST ? 1'd0 : _rLenValid);
rRen <= #1 (RST ? 1'd0 : _rRen);
end
always @ (*) begin
_rLenValid = LEN_VALID;
_rRen = RD_EN;
end
// FIFO for storing data from the channel.
(* RAM_STYLE="BLOCK" *)
sync_fifo #(.C_WIDTH(C_FIFO_DATA_WIDTH), .C_DEPTH(C_FIFO_DEPTH), .C_PROVIDE_COUNT(1)) fifo (
.CLK(CLK),
.RST(RST),
.WR_EN(WR_EN),
.WR_DATA(WR_DATA),
.FULL(),
.COUNT(WR_COUNT),
.RD_EN(rFifoRdEn),
.RD_DATA(wFifoData),
.EMPTY()
);
// Manage shifting of data in from the FIFO and shifting of data out once
// it is consumed. We'll keep 3 words of output registers to hold an input
// packet with up to 1 extra word of unread data.
wire wLenOdd = rLenLSB[rRdPtr];
wire wLenLast = rLenLast[rRdPtr];
wire wAfterEnd = (!rRen & rRdEnHist[0]);
wire [1:0] wConsumed = ({(rRdEnHist[0] | (!rRdEnHist[0] & rRdEnHist[1] & rLenLastHist[0])), 1'd0}) - (wAfterEnd & wLenOdd);
always @ (posedge CLK) begin
rCount <= #1 (RST ? 2'd0 : _rCount);
rCountHist <= #1 _rCountHist;
rRdEnHist <= #1 (RST ? {C_RD_EN_HIST{1'd0}} : _rRdEnHist);
rFifoRdEn <= #1 (RST ? 1'd0 : _rFifoRdEn);
rFifoRdEnHist <= #1 (RST ? {C_FIFO_RD_EN_HIST{1'd0}} : _rFifoRdEnHist);
rConsumedHist <= #1 _rConsumedHist;
rLenLastHist <= #1 (RST ? {C_LEN_LAST_HIST{1'd0}} : _rLenLastHist);
rFifoData <= #1 _rFifoData;
rData <= #1 _rData;
end
always @ (*) begin
// Keep track of words in our buffer. Subtract 2 when we reach 2 on RD_EN.
// Add 1 when we finish a sequence of RD_EN that read an odd number of words.
_rCount = rCount + (wAfterEnd & wLenOdd & !wLenLast) - ({rRen & rCount[1], 1'd0}) - ({(wAfterEnd & wLenLast)&rCount[1], (wAfterEnd & wLenLast)&rCount[0]});
_rCountHist = ((rCountHist<<2) | rCount);
// Track read enables in the pipeline.
_rRdEnHist = ((rRdEnHist<<1) | rRen);
_rFifoRdEnHist = ((rFifoRdEnHist<<1) | rFifoRdEn);
// Track delayed length last value
_rLenLastHist = ((rLenLastHist<<1) | wLenLast);
// Calculate the amount to shift out each RD_EN. This is always 2 unless
// it's the last RD_EN in the sequence and the read words length is odd.
_rConsumedHist = ((rConsumedHist<<2) | wConsumed);
// Read from the FIFO unless we have 2 words cached.
_rFifoRdEn = (!rCount[1] & rRen);
// Buffer the FIFO data.
_rFifoData = wFifoData;
// Shift the buffered FIFO data into and the consumed data out of the output register.
if (rFifoRdEnHist[1])
_rData = ((rData>>({rConsumedHist[5:4], 5'd0})) | (rFifoData<<({rCountHist[4], 5'd0})));
else
_rData = (rData>>({rConsumedHist[5:4], 5'd0}));
end
// Buffer up to 4 length LSB values for use to detect unread data that was
// part of a consumed packet. Should only need 2. This is basically a FIFO.
always @ (posedge CLK) begin
rRdPtr <= #1 (RST ? 2'd0 : _rRdPtr);
rWrPtr <= #1 (RST ? 2'd0 : _rWrPtr);
rLenLSB <= #1 _rLenLSB;
rLenLast <= #1 _rLenLast;
end
always @ (*) begin
_rRdPtr = (wAfterEnd ? rRdPtr + 1'd1 : rRdPtr);
_rWrPtr = (rLenValid ? rWrPtr + 1'd1 : rWrPtr);
_rLenLSB = rLenLSB;
_rLenLSB[rWrPtr] = (rLenValid ? (~LEN_LSB + 1'd1) : rLenLSB[rWrPtr]);
_rLenLast = rLenLast;
_rLenLast[rWrPtr] = (rLenValid ? LEN_LAST : rLenLast[rWrPtr]);
end
endmodule
|
// ----------------------------------------------------------------------
// Copyright (c) 2016, The Regents of the University of California All
// rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// * Neither the name of The Regents of the University of California
// nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL REGENTS OF THE
// UNIVERSITY OF CALIFORNIA BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
// OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
// TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
// ----------------------------------------------------------------------
//----------------------------------------------------------------------------
// Filename: ff.v
// Version: 1.00.a
// Verilog Standard: Verilog-2001
// Description: A D/Q flip flop.
// Author: Matt Jacobsen
// History: @mattj: Version 2.0
//-----------------------------------------------------------------------------
`timescale 1ns/1ns
module ff
(
input CLK,
input D,
output reg Q
);
always @ (posedge CLK) begin
Q <= #1 D;
end
endmodule
|
(************************************************************************)
(* v * The Coq Proof Assistant / The Coq Development Team *)
(* <O___,, * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2015 *)
(* \VV/ **************************************************************)
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
(** Base-2 Logarithm *)
Require Import NZAxioms NZMulOrder NZPow.
(** Interface of a log2 function, then its specification on naturals *)
Module Type Log2 (Import A : Typ).
Parameter Inline log2 : t -> t.
End Log2.
Module Type NZLog2Spec (A : NZOrdAxiomsSig')(B : Pow' A)(C : Log2 A).
Import A B C.
Axiom log2_spec : forall a, 0<a -> 2^(log2 a) <= a < 2^(S (log2 a)).
Axiom log2_nonpos : forall a, a<=0 -> log2 a == 0.
End NZLog2Spec.
Module Type NZLog2 (A : NZOrdAxiomsSig)(B : Pow A) := Log2 A <+ NZLog2Spec A B.
(** Derived properties of logarithm *)
Module Type NZLog2Prop
(Import A : NZOrdAxiomsSig')
(Import B : NZPow' A)
(Import C : NZLog2 A B)
(Import D : NZMulOrderProp A)
(Import E : NZPowProp A B D).
(** log2 is always non-negative *)
Lemma log2_nonneg : forall a, 0 <= log2 a.
Proof.
intros a. destruct (le_gt_cases a 0) as [Ha|Ha].
now rewrite log2_nonpos.
destruct (log2_spec a Ha) as (_,LT).
apply lt_succ_r, (pow_gt_1 2). order'.
rewrite <- le_succ_l, <- one_succ in Ha. order.
Qed.
(** A tactic for proving positivity and non-negativity *)
Ltac order_pos :=
((apply add_pos_pos || apply add_nonneg_nonneg ||
apply mul_pos_pos || apply mul_nonneg_nonneg ||
apply pow_nonneg || apply pow_pos_nonneg ||
apply log2_nonneg || apply (le_le_succ_r 0));
order_pos) (* in case of success of an apply, we recurse *)
|| order'. (* otherwise *)
(** The spec of log2 indeed determines it *)
Lemma log2_unique : forall a b, 0<=b -> 2^b<=a<2^(S b) -> log2 a == b.
Proof.
intros a b Hb (LEb,LTb).
assert (Ha : 0 < a).
apply lt_le_trans with (2^b); trivial.
apply pow_pos_nonneg; order'.
assert (Hc := log2_nonneg a).
destruct (log2_spec a Ha) as (LEc,LTc).
assert (log2 a <= b).
apply lt_succ_r, (pow_lt_mono_r_iff 2); try order'.
now apply le_le_succ_r.
assert (b <= log2 a).
apply lt_succ_r, (pow_lt_mono_r_iff 2); try order'.
now apply le_le_succ_r.
order.
Qed.
(** Hence log2 is a morphism. *)
Instance log2_wd : Proper (eq==>eq) log2.
Proof.
intros x x' Hx.
destruct (le_gt_cases x 0).
rewrite 2 log2_nonpos; trivial. reflexivity. now rewrite <- Hx.
apply log2_unique. apply log2_nonneg.
rewrite Hx in *. now apply log2_spec.
Qed.
(** An alternate specification *)
Lemma log2_spec_alt : forall a, 0<a -> exists r,
a == 2^(log2 a) + r /\ 0 <= r < 2^(log2 a).
Proof.
intros a Ha.
destruct (log2_spec _ Ha) as (LE,LT).
destruct (le_exists_sub _ _ LE) as (r & Hr & Hr').
exists r.
split. now rewrite add_comm.
split. trivial.
apply (add_lt_mono_r _ _ (2^log2 a)).
rewrite <- Hr. generalize LT.
rewrite pow_succ_r by order_pos.
rewrite two_succ at 1. now nzsimpl.
Qed.
Lemma log2_unique' : forall a b c, 0<=b -> 0<=c<2^b ->
a == 2^b + c -> log2 a == b.
Proof.
intros a b c Hb (Hc,H) EQ.
apply log2_unique. trivial.
rewrite EQ.
split.
rewrite <- add_0_r at 1. now apply add_le_mono_l.
rewrite pow_succ_r by order.
rewrite two_succ at 2. nzsimpl. now apply add_lt_mono_l.
Qed.
(** log2 is exact on powers of 2 *)
Lemma log2_pow2 : forall a, 0<=a -> log2 (2^a) == a.
Proof.
intros a Ha.
apply log2_unique' with 0; trivial.
split; order_pos. now nzsimpl.
Qed.
(** log2 and predecessors of powers of 2 *)
Lemma log2_pred_pow2 : forall a, 0<a -> log2 (P (2^a)) == P a.
Proof.
intros a Ha.
assert (Ha' : S (P a) == a) by (now rewrite lt_succ_pred with 0).
apply log2_unique.
apply lt_succ_r; order.
rewrite <-le_succ_l, <-lt_succ_r, Ha'.
rewrite lt_succ_pred with 0.
split; try easy. apply pow_lt_mono_r_iff; try order'.
rewrite succ_lt_mono, Ha'. apply lt_succ_diag_r.
apply pow_pos_nonneg; order'.
Qed.
(** log2 and basic constants *)
Lemma log2_1 : log2 1 == 0.
Proof.
rewrite <- (pow_0_r 2). now apply log2_pow2.
Qed.
Lemma log2_2 : log2 2 == 1.
Proof.
rewrite <- (pow_1_r 2). apply log2_pow2; order'.
Qed.
(** log2 n is strictly positive for 1<n *)
Lemma log2_pos : forall a, 1<a -> 0 < log2 a.
Proof.
intros a Ha.
assert (Ha' : 0 < a) by order'.
assert (H := log2_nonneg a). le_elim H; trivial.
generalize (log2_spec a Ha'). rewrite <- H in *. nzsimpl; try order.
intros (_,H'). rewrite two_succ in H'. apply lt_succ_r in H'; order.
Qed.
(** Said otherwise, log2 is null only below 1 *)
Lemma log2_null : forall a, log2 a == 0 <-> a <= 1.
Proof.
intros a. split; intros H.
destruct (le_gt_cases a 1) as [Ha|Ha]; trivial.
generalize (log2_pos a Ha); order.
le_elim H.
apply log2_nonpos. apply lt_succ_r. now rewrite <- one_succ.
rewrite H. apply log2_1.
Qed.
(** log2 is a monotone function (but not a strict one) *)
Lemma log2_le_mono : forall a b, a<=b -> log2 a <= log2 b.
Proof.
intros a b H.
destruct (le_gt_cases a 0) as [Ha|Ha].
rewrite log2_nonpos; order_pos.
assert (Hb : 0 < b) by order.
destruct (log2_spec a Ha) as (LEa,_).
destruct (log2_spec b Hb) as (_,LTb).
apply lt_succ_r, (pow_lt_mono_r_iff 2); order_pos.
Qed.
(** No reverse result for <=, consider for instance log2 3 <= log2 2 *)
Lemma log2_lt_cancel : forall a b, log2 a < log2 b -> a < b.
Proof.
intros a b H.
destruct (le_gt_cases b 0) as [Hb|Hb].
rewrite (log2_nonpos b) in H; trivial.
generalize (log2_nonneg a); order.
destruct (le_gt_cases a 0) as [Ha|Ha]. order.
destruct (log2_spec a Ha) as (_,LTa).
destruct (log2_spec b Hb) as (LEb,_).
apply le_succ_l in H.
apply (pow_le_mono_r_iff 2) in H; order_pos.
Qed.
(** When left side is a power of 2, we have an equivalence for <= *)
Lemma log2_le_pow2 : forall a b, 0<a -> (2^b<=a <-> b <= log2 a).
Proof.
intros a b Ha.
split; intros H.
destruct (lt_ge_cases b 0) as [Hb|Hb].
generalize (log2_nonneg a); order.
rewrite <- (log2_pow2 b); trivial. now apply log2_le_mono.
transitivity (2^(log2 a)).
apply pow_le_mono_r; order'.
now destruct (log2_spec a Ha).
Qed.
(** When right side is a square, we have an equivalence for < *)
Lemma log2_lt_pow2 : forall a b, 0<a -> (a<2^b <-> log2 a < b).
Proof.
intros a b Ha.
split; intros H.
destruct (lt_ge_cases b 0) as [Hb|Hb].
rewrite pow_neg_r in H; order.
apply (pow_lt_mono_r_iff 2); try order_pos.
apply le_lt_trans with a; trivial.
now destruct (log2_spec a Ha).
destruct (lt_ge_cases b 0) as [Hb|Hb].
generalize (log2_nonneg a); order.
apply log2_lt_cancel; try order.
now rewrite log2_pow2.
Qed.
(** Comparing log2 and identity *)
Lemma log2_lt_lin : forall a, 0<a -> log2 a < a.
Proof.
intros a Ha.
apply (pow_lt_mono_r_iff 2); try order_pos.
apply le_lt_trans with a.
now destruct (log2_spec a Ha).
apply pow_gt_lin_r; order'.
Qed.
Lemma log2_le_lin : forall a, 0<=a -> log2 a <= a.
Proof.
intros a Ha.
le_elim Ha.
now apply lt_le_incl, log2_lt_lin.
rewrite <- Ha, log2_nonpos; order.
Qed.
(** Log2 and multiplication. *)
(** Due to rounding error, we don't have the usual
[log2 (a*b) = log2 a + log2 b] but we may be off by 1 at most *)
Lemma log2_mul_below : forall a b, 0<a -> 0<b ->
log2 a + log2 b <= log2 (a*b).
Proof.
intros a b Ha Hb.
apply log2_le_pow2; try order_pos.
rewrite pow_add_r by order_pos.
apply mul_le_mono_nonneg; try apply log2_spec; order_pos.
Qed.
Lemma log2_mul_above : forall a b, 0<=a -> 0<=b ->
log2 (a*b) <= log2 a + log2 b + 1.
Proof.
intros a b Ha Hb.
le_elim Ha.
le_elim Hb.
apply lt_succ_r.
rewrite add_1_r, <- add_succ_r, <- add_succ_l.
apply log2_lt_pow2; try order_pos.
rewrite pow_add_r by order_pos.
apply mul_lt_mono_nonneg; try order; now apply log2_spec.
rewrite <- Hb. nzsimpl. rewrite log2_nonpos; order_pos.
rewrite <- Ha. nzsimpl. rewrite log2_nonpos; order_pos.
Qed.
(** And we can't find better approximations in general.
- The lower bound is exact for powers of 2.
- Concerning the upper bound, for any c>1, take a=b=2^c-1,
then log2 (a*b) = c+c -1 while (log2 a) = (log2 b) = c-1
*)
(** At least, we get back the usual equation when we multiply by 2 (or 2^k) *)
Lemma log2_mul_pow2 : forall a b, 0<a -> 0<=b -> log2 (a*2^b) == b + log2 a.
Proof.
intros a b Ha Hb.
apply log2_unique; try order_pos. split.
rewrite pow_add_r, mul_comm; try order_pos.
apply mul_le_mono_nonneg_r. order_pos. now apply log2_spec.
rewrite <-add_succ_r, pow_add_r, mul_comm; try order_pos.
apply mul_lt_mono_pos_l. order_pos. now apply log2_spec.
Qed.
Lemma log2_double : forall a, 0<a -> log2 (2*a) == S (log2 a).
Proof.
intros a Ha. generalize (log2_mul_pow2 a 1 Ha le_0_1). now nzsimpl'.
Qed.
(** Two numbers with same log2 cannot be far away. *)
Lemma log2_same : forall a b, 0<a -> 0<b -> log2 a == log2 b -> a < 2*b.
Proof.
intros a b Ha Hb H.
apply log2_lt_cancel. rewrite log2_double, H by trivial.
apply lt_succ_diag_r.
Qed.
(** Log2 and successor :
- the log2 function climbs by at most 1 at a time
- otherwise it stays at the same value
- the +1 steps occur for powers of two
*)
Lemma log2_succ_le : forall a, log2 (S a) <= S (log2 a).
Proof.
intros a.
destruct (lt_trichotomy 0 a) as [LT|[EQ|LT]].
apply (pow_le_mono_r_iff 2); try order_pos.
transitivity (S a).
apply log2_spec.
apply lt_succ_r; order.
now apply le_succ_l, log2_spec.
rewrite <- EQ, <- one_succ, log2_1; order_pos.
rewrite 2 log2_nonpos. order_pos. order'. now rewrite le_succ_l.
Qed.
Lemma log2_succ_or : forall a,
log2 (S a) == S (log2 a) \/ log2 (S a) == log2 a.
Proof.
intros.
destruct (le_gt_cases (log2 (S a)) (log2 a)) as [H|H].
right. generalize (log2_le_mono _ _ (le_succ_diag_r a)); order.
left. apply le_succ_l in H. generalize (log2_succ_le a); order.
Qed.
Lemma log2_eq_succ_is_pow2 : forall a,
log2 (S a) == S (log2 a) -> exists b, S a == 2^b.
Proof.
intros a H.
destruct (le_gt_cases a 0) as [Ha|Ha].
rewrite 2 (proj2 (log2_null _)) in H. generalize (lt_succ_diag_r 0); order.
order'. apply le_succ_l. order'.
assert (Ha' : 0 < S a) by (apply lt_succ_r; order).
exists (log2 (S a)).
generalize (proj1 (log2_spec (S a) Ha')) (proj2 (log2_spec a Ha)).
rewrite <- le_succ_l, <- H. order.
Qed.
Lemma log2_eq_succ_iff_pow2 : forall a, 0<a ->
(log2 (S a) == S (log2 a) <-> exists b, S a == 2^b).
Proof.
intros a Ha.
split. apply log2_eq_succ_is_pow2.
intros (b,Hb).
assert (Hb' : 0 < b).
apply (pow_gt_1 2); try order'; now rewrite <- Hb, one_succ, <- succ_lt_mono.
rewrite Hb, log2_pow2; try order'.
setoid_replace a with (P (2^b)). rewrite log2_pred_pow2; trivial.
symmetry; now apply lt_succ_pred with 0.
apply succ_inj. rewrite Hb. symmetry. apply lt_succ_pred with 0.
rewrite <- Hb, lt_succ_r; order.
Qed.
Lemma log2_succ_double : forall a, 0<a -> log2 (2*a+1) == S (log2 a).
Proof.
intros a Ha.
rewrite add_1_r.
destruct (log2_succ_or (2*a)) as [H|H]; [exfalso|now rewrite H, log2_double].
apply log2_eq_succ_is_pow2 in H. destruct H as (b,H).
destruct (lt_trichotomy b 0) as [LT|[EQ|LT]].
rewrite pow_neg_r in H; trivial.
apply (mul_pos_pos 2), succ_lt_mono in Ha; try order'.
rewrite <- one_succ in Ha. order'.
rewrite EQ, pow_0_r in H.
apply (mul_pos_pos 2), succ_lt_mono in Ha; try order'.
rewrite <- one_succ in Ha. order'.
assert (EQ:=lt_succ_pred 0 b LT).
rewrite <- EQ, pow_succ_r in H; [|now rewrite <- lt_succ_r, EQ].
destruct (lt_ge_cases a (2^(P b))) as [LT'|LE'].
generalize (mul_2_mono_l _ _ LT'). rewrite add_1_l. order.
rewrite (mul_le_mono_pos_l _ _ 2) in LE'; try order'.
rewrite <- H in LE'. apply le_succ_l in LE'. order.
Qed.
(** Log2 and addition *)
Lemma log2_add_le : forall a b, a~=1 -> b~=1 -> log2 (a+b) <= log2 a + log2 b.
Proof.
intros a b Ha Hb.
destruct (lt_trichotomy a 1) as [Ha'|[Ha'|Ha']]; [|order|].
rewrite one_succ, lt_succ_r in Ha'.
rewrite (log2_nonpos a); trivial. nzsimpl. apply log2_le_mono.
rewrite <- (add_0_l b) at 2. now apply add_le_mono.
destruct (lt_trichotomy b 1) as [Hb'|[Hb'|Hb']]; [|order|].
rewrite one_succ, lt_succ_r in Hb'.
rewrite (log2_nonpos b); trivial. nzsimpl. apply log2_le_mono.
rewrite <- (add_0_r a) at 2. now apply add_le_mono.
clear Ha Hb.
apply lt_succ_r.
apply log2_lt_pow2; try order_pos.
rewrite pow_succ_r by order_pos.
rewrite two_succ, one_succ at 1. nzsimpl.
apply add_lt_mono.
apply lt_le_trans with (2^(S (log2 a))). apply log2_spec; order'.
apply pow_le_mono_r. order'. rewrite <- add_1_r. apply add_le_mono_l.
rewrite one_succ; now apply le_succ_l, log2_pos.
apply lt_le_trans with (2^(S (log2 b))). apply log2_spec; order'.
apply pow_le_mono_r. order'. rewrite <- add_1_l. apply add_le_mono_r.
rewrite one_succ; now apply le_succ_l, log2_pos.
Qed.
(** The sum of two log2 is less than twice the log2 of the sum.
The large inequality is obvious thanks to monotonicity.
The strict one requires some more work. This is almost
a convexity inequality for points [2a], [2b] and their middle [a+b] :
ideally, we would have [2*log(a+b) >= log(2a)+log(2b) = 2+log a+log b].
Here, we cannot do better: consider for instance a=2 b=4, then 1+2<2*2
*)
Lemma add_log2_lt : forall a b, 0<a -> 0<b ->
log2 a + log2 b < 2 * log2 (a+b).
Proof.
intros a b Ha Hb. nzsimpl'.
assert (H : log2 a <= log2 (a+b)).
apply log2_le_mono. rewrite <- (add_0_r a) at 1. apply add_le_mono; order.
assert (H' : log2 b <= log2 (a+b)).
apply log2_le_mono. rewrite <- (add_0_l b) at 1. apply add_le_mono; order.
le_elim H.
apply lt_le_trans with (log2 (a+b) + log2 b).
now apply add_lt_mono_r. now apply add_le_mono_l.
rewrite <- H at 1. apply add_lt_mono_l.
le_elim H'; trivial.
symmetry in H. apply log2_same in H; try order_pos.
symmetry in H'. apply log2_same in H'; try order_pos.
revert H H'. nzsimpl'. rewrite <- add_lt_mono_l, <- add_lt_mono_r; order.
Qed.
End NZLog2Prop.
Module NZLog2UpProp
(Import A : NZDecOrdAxiomsSig')
(Import B : NZPow' A)
(Import C : NZLog2 A B)
(Import D : NZMulOrderProp A)
(Import E : NZPowProp A B D)
(Import F : NZLog2Prop A B C D E).
(** * [log2_up] : a binary logarithm that rounds up instead of down *)
(** For once, we define instead of axiomatizing, thanks to log2 *)
Definition log2_up a :=
match compare 1 a with
| Lt => S (log2 (P a))
| _ => 0
end.
Lemma log2_up_eqn0 : forall a, a<=1 -> log2_up a == 0.
Proof.
intros a Ha. unfold log2_up. case compare_spec; try order.
Qed.
Lemma log2_up_eqn : forall a, 1<a -> log2_up a == S (log2 (P a)).
Proof.
intros a Ha. unfold log2_up. case compare_spec; try order.
Qed.
Lemma log2_up_spec : forall a, 1<a ->
2^(P (log2_up a)) < a <= 2^(log2_up a).
Proof.
intros a Ha.
rewrite log2_up_eqn; trivial.
rewrite pred_succ.
rewrite <- (lt_succ_pred 1 a Ha) at 2 3.
rewrite lt_succ_r, le_succ_l.
apply log2_spec.
apply succ_lt_mono. now rewrite (lt_succ_pred 1 a Ha), <- one_succ.
Qed.
Lemma log2_up_nonpos : forall a, a<=0 -> log2_up a == 0.
Proof.
intros. apply log2_up_eqn0. order'.
Qed.
Instance log2_up_wd : Proper (eq==>eq) log2_up.
Proof.
assert (Proper (eq==>eq==>Logic.eq) compare).
repeat red; intros; do 2 case compare_spec; trivial; order.
intros a a' Ha. unfold log2_up. rewrite Ha at 1.
case compare; now rewrite ?Ha.
Qed.
(** [log2_up] is always non-negative *)
Lemma log2_up_nonneg : forall a, 0 <= log2_up a.
Proof.
intros a. unfold log2_up. case compare_spec; try order.
intros. apply le_le_succ_r, log2_nonneg.
Qed.
(** The spec of [log2_up] indeed determines it *)
Lemma log2_up_unique : forall a b, 0<b -> 2^(P b)<a<=2^b -> log2_up a == b.
Proof.
intros a b Hb (LEb,LTb).
assert (Ha : 1 < a).
apply le_lt_trans with (2^(P b)); trivial.
rewrite one_succ. apply le_succ_l.
apply pow_pos_nonneg. order'. apply lt_succ_r.
now rewrite (lt_succ_pred 0 b Hb).
assert (Hc := log2_up_nonneg a).
destruct (log2_up_spec a Ha) as (LTc,LEc).
assert (b <= log2_up a).
apply lt_succ_r. rewrite <- (lt_succ_pred 0 b Hb).
rewrite <- succ_lt_mono.
apply (pow_lt_mono_r_iff 2); try order'.
assert (Hc' : 0 < log2_up a) by order.
assert (log2_up a <= b).
apply lt_succ_r. rewrite <- (lt_succ_pred 0 _ Hc').
rewrite <- succ_lt_mono.
apply (pow_lt_mono_r_iff 2); try order'.
order.
Qed.
(** [log2_up] is exact on powers of 2 *)
Lemma log2_up_pow2 : forall a, 0<=a -> log2_up (2^a) == a.
Proof.
intros a Ha.
le_elim Ha.
apply log2_up_unique; trivial.
split; try order.
apply pow_lt_mono_r; try order'.
rewrite <- (lt_succ_pred 0 a Ha) at 2.
now apply lt_succ_r.
now rewrite <- Ha, pow_0_r, log2_up_eqn0.
Qed.
(** [log2_up] and successors of powers of 2 *)
Lemma log2_up_succ_pow2 : forall a, 0<=a -> log2_up (S (2^a)) == S a.
Proof.
intros a Ha.
rewrite log2_up_eqn, pred_succ, log2_pow2; try easy.
rewrite one_succ, <- succ_lt_mono. apply pow_pos_nonneg; order'.
Qed.
(** Basic constants *)
Lemma log2_up_1 : log2_up 1 == 0.
Proof.
now apply log2_up_eqn0.
Qed.
Lemma log2_up_2 : log2_up 2 == 1.
Proof.
rewrite <- (pow_1_r 2). apply log2_up_pow2; order'.
Qed.
(** Links between log2 and [log2_up] *)
Lemma le_log2_log2_up : forall a, log2 a <= log2_up a.
Proof.
intros a. unfold log2_up. case compare_spec; intros H.
rewrite <- H, log2_1. order.
rewrite <- (lt_succ_pred 1 a H) at 1. apply log2_succ_le.
rewrite log2_nonpos. order. now rewrite <-lt_succ_r, <-one_succ.
Qed.
Lemma le_log2_up_succ_log2 : forall a, log2_up a <= S (log2 a).
Proof.
intros a. unfold log2_up. case compare_spec; intros H; try order_pos.
rewrite <- succ_le_mono. apply log2_le_mono.
rewrite <- (lt_succ_pred 1 a H) at 2. apply le_succ_diag_r.
Qed.
Lemma log2_log2_up_spec : forall a, 0<a ->
2^log2 a <= a <= 2^log2_up a.
Proof.
intros a H. split.
now apply log2_spec.
rewrite <-le_succ_l, <-one_succ in H. le_elim H.
now apply log2_up_spec.
now rewrite <-H, log2_up_1, pow_0_r.
Qed.
Lemma log2_log2_up_exact :
forall a, 0<a -> (log2 a == log2_up a <-> exists b, a == 2^b).
Proof.
intros a Ha.
split. intros. exists (log2 a).
generalize (log2_log2_up_spec a Ha). rewrite <-H.
destruct 1; order.
intros (b,Hb). rewrite Hb.
destruct (le_gt_cases 0 b).
now rewrite log2_pow2, log2_up_pow2.
rewrite pow_neg_r; trivial. now rewrite log2_nonpos, log2_up_nonpos.
Qed.
(** [log2_up] n is strictly positive for 1<n *)
Lemma log2_up_pos : forall a, 1<a -> 0 < log2_up a.
Proof.
intros. rewrite log2_up_eqn; trivial. apply lt_succ_r; order_pos.
Qed.
(** Said otherwise, [log2_up] is null only below 1 *)
Lemma log2_up_null : forall a, log2_up a == 0 <-> a <= 1.
Proof.
intros a. split; intros H.
destruct (le_gt_cases a 1) as [Ha|Ha]; trivial.
generalize (log2_up_pos a Ha); order.
now apply log2_up_eqn0.
Qed.
(** [log2_up] is a monotone function (but not a strict one) *)
Lemma log2_up_le_mono : forall a b, a<=b -> log2_up a <= log2_up b.
Proof.
intros a b H.
destruct (le_gt_cases a 1) as [Ha|Ha].
rewrite log2_up_eqn0; trivial. apply log2_up_nonneg.
rewrite 2 log2_up_eqn; try order.
rewrite <- succ_le_mono. apply log2_le_mono, succ_le_mono.
rewrite 2 lt_succ_pred with 1; order.
Qed.
(** No reverse result for <=, consider for instance log2_up 4 <= log2_up 3 *)
Lemma log2_up_lt_cancel : forall a b, log2_up a < log2_up b -> a < b.
Proof.
intros a b H.
destruct (le_gt_cases b 1) as [Hb|Hb].
rewrite (log2_up_eqn0 b) in H; trivial.
generalize (log2_up_nonneg a); order.
destruct (le_gt_cases a 1) as [Ha|Ha]. order.
rewrite 2 log2_up_eqn in H; try order.
rewrite <- succ_lt_mono in H. apply log2_lt_cancel, succ_lt_mono in H.
rewrite 2 lt_succ_pred with 1 in H; order.
Qed.
(** When left side is a power of 2, we have an equivalence for < *)
Lemma log2_up_lt_pow2 : forall a b, 0<a -> (2^b<a <-> b < log2_up a).
Proof.
intros a b Ha.
split; intros H.
destruct (lt_ge_cases b 0) as [Hb|Hb].
generalize (log2_up_nonneg a); order.
apply (pow_lt_mono_r_iff 2). order'. apply log2_up_nonneg.
apply lt_le_trans with a; trivial.
apply (log2_up_spec a).
apply le_lt_trans with (2^b); trivial.
rewrite one_succ, le_succ_l. apply pow_pos_nonneg; order'.
destruct (lt_ge_cases b 0) as [Hb|Hb].
now rewrite pow_neg_r.
rewrite <- (log2_up_pow2 b) in H; trivial. now apply log2_up_lt_cancel.
Qed.
(** When right side is a square, we have an equivalence for <= *)
Lemma log2_up_le_pow2 : forall a b, 0<a -> (a<=2^b <-> log2_up a <= b).
Proof.
intros a b Ha.
split; intros H.
destruct (lt_ge_cases b 0) as [Hb|Hb].
rewrite pow_neg_r in H; order.
rewrite <- (log2_up_pow2 b); trivial. now apply log2_up_le_mono.
transitivity (2^(log2_up a)).
now apply log2_log2_up_spec.
apply pow_le_mono_r; order'.
Qed.
(** Comparing [log2_up] and identity *)
Lemma log2_up_lt_lin : forall a, 0<a -> log2_up a < a.
Proof.
intros a Ha.
assert (H : S (P a) == a) by (now apply lt_succ_pred with 0).
rewrite <- H at 2. apply lt_succ_r. apply log2_up_le_pow2; trivial.
rewrite <- H at 1. apply le_succ_l.
apply pow_gt_lin_r. order'. apply lt_succ_r; order.
Qed.
Lemma log2_up_le_lin : forall a, 0<=a -> log2_up a <= a.
Proof.
intros a Ha.
le_elim Ha.
now apply lt_le_incl, log2_up_lt_lin.
rewrite <- Ha, log2_up_nonpos; order.
Qed.
(** [log2_up] and multiplication. *)
(** Due to rounding error, we don't have the usual
[log2_up (a*b) = log2_up a + log2_up b] but we may be off by 1 at most *)
Lemma log2_up_mul_above : forall a b, 0<=a -> 0<=b ->
log2_up (a*b) <= log2_up a + log2_up b.
Proof.
intros a b Ha Hb.
assert (Ha':=log2_up_nonneg a).
assert (Hb':=log2_up_nonneg b).
le_elim Ha.
le_elim Hb.
apply log2_up_le_pow2; try order_pos.
rewrite pow_add_r; trivial.
apply mul_le_mono_nonneg; try apply log2_log2_up_spec; order'.
rewrite <- Hb. nzsimpl. rewrite log2_up_nonpos; order_pos.
rewrite <- Ha. nzsimpl. rewrite log2_up_nonpos; order_pos.
Qed.
Lemma log2_up_mul_below : forall a b, 0<a -> 0<b ->
log2_up a + log2_up b <= S (log2_up (a*b)).
Proof.
intros a b Ha Hb.
rewrite <-le_succ_l, <-one_succ in Ha. le_elim Ha.
rewrite <-le_succ_l, <-one_succ in Hb. le_elim Hb.
assert (Ha' : 0 < log2_up a) by (apply log2_up_pos; trivial).
assert (Hb' : 0 < log2_up b) by (apply log2_up_pos; trivial).
rewrite <- (lt_succ_pred 0 (log2_up a)); trivial.
rewrite <- (lt_succ_pred 0 (log2_up b)); trivial.
nzsimpl. rewrite <- succ_le_mono, le_succ_l.
apply (pow_lt_mono_r_iff 2). order'. apply log2_up_nonneg.
rewrite pow_add_r; try (apply lt_succ_r; rewrite (lt_succ_pred 0); trivial).
apply lt_le_trans with (a*b).
apply mul_lt_mono_nonneg; try order_pos; try now apply log2_up_spec.
apply log2_up_spec.
setoid_replace 1 with (1*1) by now nzsimpl.
apply mul_lt_mono_nonneg; order'.
rewrite <- Hb, log2_up_1; nzsimpl. apply le_succ_diag_r.
rewrite <- Ha, log2_up_1; nzsimpl. apply le_succ_diag_r.
Qed.
(** And we can't find better approximations in general.
- The upper bound is exact for powers of 2.
- Concerning the lower bound, for any c>1, take a=b=2^c+1,
then [log2_up (a*b) = c+c +1] while [(log2_up a) = (log2_up b) = c+1]
*)
(** At least, we get back the usual equation when we multiply by 2 (or 2^k) *)
Lemma log2_up_mul_pow2 : forall a b, 0<a -> 0<=b ->
log2_up (a*2^b) == b + log2_up a.
Proof.
intros a b Ha Hb.
rewrite <- le_succ_l, <- one_succ in Ha; le_elim Ha.
apply log2_up_unique. apply add_nonneg_pos; trivial. now apply log2_up_pos.
split.
assert (EQ := lt_succ_pred 0 _ (log2_up_pos _ Ha)).
rewrite <- EQ. nzsimpl. rewrite pow_add_r, mul_comm; trivial.
apply mul_lt_mono_pos_r. order_pos. now apply log2_up_spec.
rewrite <- lt_succ_r, EQ. now apply log2_up_pos.
rewrite pow_add_r, mul_comm; trivial.
apply mul_le_mono_nonneg_l. order_pos. now apply log2_up_spec.
apply log2_up_nonneg.
now rewrite <- Ha, mul_1_l, log2_up_1, add_0_r, log2_up_pow2.
Qed.
Lemma log2_up_double : forall a, 0<a -> log2_up (2*a) == S (log2_up a).
Proof.
intros a Ha. generalize (log2_up_mul_pow2 a 1 Ha le_0_1). now nzsimpl'.
Qed.
(** Two numbers with same [log2_up] cannot be far away. *)
Lemma log2_up_same : forall a b, 0<a -> 0<b -> log2_up a == log2_up b -> a < 2*b.
Proof.
intros a b Ha Hb H.
apply log2_up_lt_cancel. rewrite log2_up_double, H by trivial.
apply lt_succ_diag_r.
Qed.
(** [log2_up] and successor :
- the [log2_up] function climbs by at most 1 at a time
- otherwise it stays at the same value
- the +1 steps occur after powers of two
*)
Lemma log2_up_succ_le : forall a, log2_up (S a) <= S (log2_up a).
Proof.
intros a.
destruct (lt_trichotomy 1 a) as [LT|[EQ|LT]].
rewrite 2 log2_up_eqn; trivial.
rewrite pred_succ, <- succ_le_mono. rewrite <-(lt_succ_pred 1 a LT) at 1.
apply log2_succ_le.
apply lt_succ_r; order.
rewrite <- EQ, <- two_succ, log2_up_1, log2_up_2. now nzsimpl'.
rewrite 2 log2_up_eqn0. order_pos. order'. now rewrite le_succ_l.
Qed.
Lemma log2_up_succ_or : forall a,
log2_up (S a) == S (log2_up a) \/ log2_up (S a) == log2_up a.
Proof.
intros.
destruct (le_gt_cases (log2_up (S a)) (log2_up a)).
right. generalize (log2_up_le_mono _ _ (le_succ_diag_r a)); order.
left. apply le_succ_l in H. generalize (log2_up_succ_le a); order.
Qed.
Lemma log2_up_eq_succ_is_pow2 : forall a,
log2_up (S a) == S (log2_up a) -> exists b, a == 2^b.
Proof.
intros a H.
destruct (le_gt_cases a 0) as [Ha|Ha].
rewrite 2 (proj2 (log2_up_null _)) in H. generalize (lt_succ_diag_r 0); order.
order'. apply le_succ_l. order'.
assert (Ha' : 1 < S a) by (now rewrite one_succ, <- succ_lt_mono).
exists (log2_up a).
generalize (proj1 (log2_up_spec (S a) Ha')) (proj2 (log2_log2_up_spec a Ha)).
rewrite H, pred_succ, lt_succ_r. order.
Qed.
Lemma log2_up_eq_succ_iff_pow2 : forall a, 0<a ->
(log2_up (S a) == S (log2_up a) <-> exists b, a == 2^b).
Proof.
intros a Ha.
split. apply log2_up_eq_succ_is_pow2.
intros (b,Hb).
destruct (lt_ge_cases b 0) as [Hb'|Hb'].
rewrite pow_neg_r in Hb; order.
rewrite Hb, log2_up_pow2; try order'.
now rewrite log2_up_succ_pow2.
Qed.
Lemma log2_up_succ_double : forall a, 0<a ->
log2_up (2*a+1) == 2 + log2 a.
Proof.
intros a Ha.
rewrite log2_up_eqn. rewrite add_1_r, pred_succ, log2_double; now nzsimpl'.
apply le_lt_trans with (0+1). now nzsimpl'.
apply add_lt_mono_r. order_pos.
Qed.
(** [log2_up] and addition *)
Lemma log2_up_add_le : forall a b, a~=1 -> b~=1 ->
log2_up (a+b) <= log2_up a + log2_up b.
Proof.
intros a b Ha Hb.
destruct (lt_trichotomy a 1) as [Ha'|[Ha'|Ha']]; [|order|].
rewrite (log2_up_eqn0 a) by order. nzsimpl. apply log2_up_le_mono.
rewrite one_succ, lt_succ_r in Ha'.
rewrite <- (add_0_l b) at 2. now apply add_le_mono.
destruct (lt_trichotomy b 1) as [Hb'|[Hb'|Hb']]; [|order|].
rewrite (log2_up_eqn0 b) by order. nzsimpl. apply log2_up_le_mono.
rewrite one_succ, lt_succ_r in Hb'.
rewrite <- (add_0_r a) at 2. now apply add_le_mono.
clear Ha Hb.
transitivity (log2_up (a*b)).
now apply log2_up_le_mono, add_le_mul.
apply log2_up_mul_above; order'.
Qed.
(** The sum of two [log2_up] is less than twice the [log2_up] of the sum.
The large inequality is obvious thanks to monotonicity.
The strict one requires some more work. This is almost
a convexity inequality for points [2a], [2b] and their middle [a+b] :
ideally, we would have [2*log(a+b) >= log(2a)+log(2b) = 2+log a+log b].
Here, we cannot do better: consider for instance a=3 b=5, then 2+3<2*3
*)
Lemma add_log2_up_lt : forall a b, 0<a -> 0<b ->
log2_up a + log2_up b < 2 * log2_up (a+b).
Proof.
intros a b Ha Hb. nzsimpl'.
assert (H : log2_up a <= log2_up (a+b)).
apply log2_up_le_mono. rewrite <- (add_0_r a) at 1. apply add_le_mono; order.
assert (H' : log2_up b <= log2_up (a+b)).
apply log2_up_le_mono. rewrite <- (add_0_l b) at 1. apply add_le_mono; order.
le_elim H.
apply lt_le_trans with (log2_up (a+b) + log2_up b).
now apply add_lt_mono_r. now apply add_le_mono_l.
rewrite <- H at 1. apply add_lt_mono_l.
le_elim H'. trivial.
symmetry in H. apply log2_up_same in H; try order_pos.
symmetry in H'. apply log2_up_same in H'; try order_pos.
revert H H'. nzsimpl'. rewrite <- add_lt_mono_l, <- add_lt_mono_r; order.
Qed.
End NZLog2UpProp.
|
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 04/26/2016 08:42:14 AM
// Design Name:
// Module Name: ROM_test
// Project Name:
// Target Devices:
// Tool Versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module ROM_test #(parameter W=32, parameter N=0)
(
input wire [9:0] address,
output reg [W-1:0] data
);
localparam ROM_FILE32_A ="/media/francis/Acer/Proyecto de graduacion/Link to GitHub/Proyecto_De_Graduacion/TXTVerification/Hexadecimal_A.txt";
localparam ROM_FILE64_A="/media/francis/Acer/Proyecto de graduacion/Link to GitHub/Proyecto_De_Graduacion/TXTVerification/Hexadecimal_A.txt";
localparam ROM_FILE32_B= "/media/francis/Acer/Proyecto de graduacion/Link to GitHub/Proyecto_De_Graduacion/TXTVerification/Hexadecimal_B.txt";
localparam ROM_FILE64_B= "/media/francis/Acer/Proyecto de graduacion/Link to GitHub/Proyecto_De_Graduacion/TXTVerification/Hexadecimal_B.txt";
//(* rom_style="{distributed | block}" *)
reg [W-1:0] rom_test [1023:0];
generate
if(W==32)
initial
begin
if(N==0)
$readmemh(ROM_FILE32_A, rom_test, 0, 1023);
else
$readmemh(ROM_FILE32_B, rom_test, 0, 1023);
end
else
initial
begin
if(N==0)
$readmemh(ROM_FILE64_A, rom_test, 0, 1023);
else
$readmemh(ROM_FILE64_B, rom_test, 0, 1023);
end
endgenerate
always @*
begin
data = rom_test[address];
end
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2013 by Ed Lander.
// verilator lint_off WIDTH
`define checkh(gotv,expv) do if ((gotv) !== (expv)) begin $write("%%Error: %s:%0d: got='h%x exp='h%x\n", `__FILE__,`__LINE__, (gotv), (expv)); $stop; end while(0);
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
reg [7:0] p1;
reg [7:0] p2;
reg [7:0] p3;
initial begin
p1 = 8'h01;
p2 = 8'h02;
p3 = 8'h03;
end
parameter int param1 = 8'h11;
parameter int param2 = 8'h12;
parameter int param3 = 8'h13;
targetmod i_targetmod (/*AUTOINST*/
// Inputs
.clk (clk));
//Binding i_targetmod to mycheck --instantiates i_mycheck inside i_targetmod
//param1 not over-riden (as mycheck) (=> 0x31)
//param2 explicitly bound to targetmod value (=> 0x22)
//param3 explicitly bound to top value (=> 0x13)
//p1 implictly bound (.*), takes value from targetmod (=> 0x04)
//p2 explictly bound to targetmod (=> 0x05)
//p3 explictly bound to top (=> 0x03)
// Alternative unsupported form is i_targetmod
bind targetmod mycheck
#(
.param2(param2),
.param3(param3)
)
i_mycheck (.p2(p2), .p3(p3), .*);
endmodule
module targetmod (input clk);
reg [7:0] p1;
reg [7:0] p2;
reg [7:0] p3;
parameter int param1 = 8'h21;
parameter int param2 = 8'h22;
parameter int param3 = 8'h23;
initial begin
p1 = 8'h04;
p2 = 8'h05;
p3 = 8'h06;
end
endmodule
module mycheck (/*AUTOARG*/
// Inputs
clk, p1, p2, p3
);
input clk;
input [7:0] p1;
input [7:0] p2;
input [7:0] p3;
parameter int param1 = 8'h31;
parameter int param2 = 8'h32;
parameter int param3 = 8'h33;
always @ (posedge clk) begin
`checkh(param1,8'h31);
`checkh(param2,8'h22);
`checkh(param3,8'h23);
`checkh(p1,8'h04);
`checkh(p2,8'h05);
`checkh(p3,8'h06);
$write("*-* All Finished *-*\n");
$finish;
end
endmodule
|
(************************************************************************)
(* v * The Coq Proof Assistant / The Coq Development Team *)
(* <O___,, * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2015 *)
(* \VV/ **************************************************************)
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
Set Implicit Arguments.
Require Export Notations.
Notation "A -> B" := (forall (_ : A), B) : type_scope.
(** * Propositional connectives *)
(** [True] is the always true proposition *)
Inductive True : Prop :=
I : True.
(** [False] is the always false proposition *)
Inductive False : Prop :=.
(** [not A], written [~A], is the negation of [A] *)
Definition not (A:Prop) := A -> False.
Notation "~ x" := (not x) : type_scope.
Hint Unfold not: core.
(** [and A B], written [A /\ B], is the conjunction of [A] and [B]
[conj p q] is a proof of [A /\ B] as soon as
[p] is a proof of [A] and [q] a proof of [B]
[proj1] and [proj2] are first and second projections of a conjunction *)
Inductive and (A B:Prop) : Prop :=
conj : A -> B -> A /\ B
where "A /\ B" := (and A B) : type_scope.
Section Conjunction.
Variables A B : Prop.
Theorem proj1 : A /\ B -> A.
Proof.
destruct 1; trivial.
Qed.
Theorem proj2 : A /\ B -> B.
Proof.
destruct 1; trivial.
Qed.
End Conjunction.
(** [or A B], written [A \/ B], is the disjunction of [A] and [B] *)
Inductive or (A B:Prop) : Prop :=
| or_introl : A -> A \/ B
| or_intror : B -> A \/ B
where "A \/ B" := (or A B) : type_scope.
Arguments or_introl [A B] _, [A] B _.
Arguments or_intror [A B] _, A [B] _.
(** [iff A B], written [A <-> B], expresses the equivalence of [A] and [B] *)
Definition iff (A B:Prop) := (A -> B) /\ (B -> A).
Notation "A <-> B" := (iff A B) : type_scope.
Section Equivalence.
Theorem iff_refl : forall A:Prop, A <-> A.
Proof.
split; auto.
Qed.
Theorem iff_trans : forall A B C:Prop, (A <-> B) -> (B <-> C) -> (A <-> C).
Proof.
intros A B C [H1 H2] [H3 H4]; split; auto.
Qed.
Theorem iff_sym : forall A B:Prop, (A <-> B) -> (B <-> A).
Proof.
intros A B [H1 H2]; split; auto.
Qed.
End Equivalence.
Hint Unfold iff: extcore.
(** Backward direction of the equivalences above does not need assumptions *)
Theorem and_iff_compat_l : forall A B C : Prop,
(B <-> C) -> (A /\ B <-> A /\ C).
Proof.
intros ? ? ? [Hl Hr]; split; intros [? ?]; (split; [ assumption | ]);
[apply Hl | apply Hr]; assumption.
Qed.
Theorem and_iff_compat_r : forall A B C : Prop,
(B <-> C) -> (B /\ A <-> C /\ A).
Proof.
intros ? ? ? [Hl Hr]; split; intros [? ?]; (split; [ | assumption ]);
[apply Hl | apply Hr]; assumption.
Qed.
Theorem or_iff_compat_l : forall A B C : Prop,
(B <-> C) -> (A \/ B <-> A \/ C).
Proof.
intros ? ? ? [Hl Hr]; split; (intros [?|?]; [left; assumption| right]);
[apply Hl | apply Hr]; assumption.
Qed.
Theorem or_iff_compat_r : forall A B C : Prop,
(B <-> C) -> (B \/ A <-> C \/ A).
Proof.
intros ? ? ? [Hl Hr]; split; (intros [?|?]; [left| right; assumption]);
[apply Hl | apply Hr]; assumption.
Qed.
(** Some equivalences *)
Theorem neg_false : forall A : Prop, ~ A <-> (A <-> False).
Proof.
intro A; unfold not; split.
- intro H; split; [exact H | intro H1; elim H1].
- intros [H _]; exact H.
Qed.
Theorem and_cancel_l : forall A B C : Prop,
(B -> A) -> (C -> A) -> ((A /\ B <-> A /\ C) <-> (B <-> C)).
Proof.
intros A B C Hl Hr.
split; [ | apply and_iff_compat_l]; intros [HypL HypR]; split; intros.
+ apply HypL; split; [apply Hl | ]; assumption.
+ apply HypR; split; [apply Hr | ]; assumption.
Qed.
Theorem and_cancel_r : forall A B C : Prop,
(B -> A) -> (C -> A) -> ((B /\ A <-> C /\ A) <-> (B <-> C)).
Proof.
intros A B C Hl Hr.
split; [ | apply and_iff_compat_r]; intros [HypL HypR]; split; intros.
+ apply HypL; split; [ | apply Hl ]; assumption.
+ apply HypR; split; [ | apply Hr ]; assumption.
Qed.
Theorem and_comm : forall A B : Prop, A /\ B <-> B /\ A.
Proof.
intros; split; intros [? ?]; split; assumption.
Qed.
Theorem and_assoc : forall A B C : Prop, (A /\ B) /\ C <-> A /\ B /\ C.
Proof.
intros; split; [ intros [[? ?] ?]| intros [? [? ?]]]; repeat split; assumption.
Qed.
Theorem or_cancel_l : forall A B C : Prop,
(B -> ~ A) -> (C -> ~ A) -> ((A \/ B <-> A \/ C) <-> (B <-> C)).
Proof.
intros ? ? ? Fl Fr; split; [ | apply or_iff_compat_l]; intros [Hl Hr]; split; intros.
{ destruct Hl; [ right | destruct Fl | ]; assumption. }
{ destruct Hr; [ right | destruct Fr | ]; assumption. }
Qed.
Theorem or_cancel_r : forall A B C : Prop,
(B -> ~ A) -> (C -> ~ A) -> ((B \/ A <-> C \/ A) <-> (B <-> C)).
Proof.
intros ? ? ? Fl Fr; split; [ | apply or_iff_compat_r]; intros [Hl Hr]; split; intros.
{ destruct Hl; [ left | | destruct Fl ]; assumption. }
{ destruct Hr; [ left | | destruct Fr ]; assumption. }
Qed.
Theorem or_comm : forall A B : Prop, (A \/ B) <-> (B \/ A).
Proof.
intros; split; (intros [? | ?]; [ right | left ]; assumption).
Qed.
Theorem or_assoc : forall A B C : Prop, (A \/ B) \/ C <-> A \/ B \/ C.
Proof.
intros; split; [ intros [[?|?]|?]| intros [?|[?|?]]].
+ left; assumption.
+ right; left; assumption.
+ right; right; assumption.
+ left; left; assumption.
+ left; right; assumption.
+ right; assumption.
Qed.
Lemma iff_and : forall A B : Prop, (A <-> B) -> (A -> B) /\ (B -> A).
Proof.
intros A B []; split; trivial.
Qed.
Lemma iff_to_and : forall A B : Prop, (A <-> B) <-> (A -> B) /\ (B -> A).
Proof.
intros; split; intros [Hl Hr]; (split; intros; [ apply Hl | apply Hr]); assumption.
Qed.
(** [(IF_then_else P Q R)], written [IF P then Q else R] denotes
either [P] and [Q], or [~P] and [Q] *)
Definition IF_then_else (P Q R:Prop) := P /\ Q \/ ~ P /\ R.
Notation "'IF' c1 'then' c2 'else' c3" := (IF_then_else c1 c2 c3)
(at level 200, right associativity) : type_scope.
(** * First-order quantifiers *)
(** [ex P], or simply [exists x, P x], or also [exists x:A, P x],
expresses the existence of an [x] of some type [A] in [Set] which
satisfies the predicate [P]. This is existential quantification.
[ex2 P Q], or simply [exists2 x, P x & Q x], or also
[exists2 x:A, P x & Q x], expresses the existence of an [x] of
type [A] which satisfies both predicates [P] and [Q].
Universal quantification is primitively written [forall x:A, Q]. By
symmetry with existential quantification, the construction [all P]
is provided too.
*)
Inductive ex (A:Type) (P:A -> Prop) : Prop :=
ex_intro : forall x:A, P x -> ex (A:=A) P.
Inductive ex2 (A:Type) (P Q:A -> Prop) : Prop :=
ex_intro2 : forall x:A, P x -> Q x -> ex2 (A:=A) P Q.
Definition all (A:Type) (P:A -> Prop) := forall x:A, P x.
(* Rule order is important to give printing priority to fully typed exists *)
Notation "'exists' x .. y , p" := (ex (fun x => .. (ex (fun y => p)) ..))
(at level 200, x binder, right associativity,
format "'[' 'exists' '/ ' x .. y , '/ ' p ']'")
: type_scope.
Notation "'exists2' x , p & q" := (ex2 (fun x => p) (fun x => q))
(at level 200, x ident, p at level 200, right associativity) : type_scope.
Notation "'exists2' x : t , p & q" := (ex2 (fun x:t => p) (fun x:t => q))
(at level 200, x ident, t at level 200, p at level 200, right associativity,
format "'[' 'exists2' '/ ' x : t , '/ ' '[' p & '/' q ']' ']'")
: type_scope.
(** Derived rules for universal quantification *)
Section universal_quantification.
Variable A : Type.
Variable P : A -> Prop.
Theorem inst : forall x:A, all (fun x => P x) -> P x.
Proof.
unfold all; auto.
Qed.
Theorem gen : forall (B:Prop) (f:forall y:A, B -> P y), B -> all P.
Proof.
red; auto.
Qed.
End universal_quantification.
(** * Equality *)
(** [eq x y], or simply [x=y] expresses the equality of [x] and
[y]. Both [x] and [y] must belong to the same type [A].
The definition is inductive and states the reflexivity of the equality.
The others properties (symmetry, transitivity, replacement of
equals by equals) are proved below. The type of [x] and [y] can be
made explicit using the notation [x = y :> A]. This is Leibniz equality
as it expresses that [x] and [y] are equal iff every property on
[A] which is true of [x] is also true of [y] *)
Inductive eq (A:Type) (x:A) : A -> Prop :=
eq_refl : x = x :>A
where "x = y :> A" := (@eq A x y) : type_scope.
Notation "x = y" := (x = y :>_) : type_scope.
Notation "x <> y :> T" := (~ x = y :>T) : type_scope.
Notation "x <> y" := (x <> y :>_) : type_scope.
Arguments eq {A} x _.
Arguments eq_refl {A x} , [A] x.
Arguments eq_ind [A] x P _ y _.
Arguments eq_rec [A] x P _ y _.
Arguments eq_rect [A] x P _ y _.
Hint Resolve I conj or_introl or_intror : core.
Hint Resolve eq_refl: core.
Hint Resolve ex_intro ex_intro2: core.
Section Logic_lemmas.
Theorem absurd : forall A C:Prop, A -> ~ A -> C.
Proof.
unfold not; intros A C h1 h2.
destruct (h2 h1).
Qed.
Section equality.
Variables A B : Type.
Variable f : A -> B.
Variables x y z : A.
Theorem eq_sym : x = y -> y = x.
Proof.
destruct 1; trivial.
Defined.
Theorem eq_trans : x = y -> y = z -> x = z.
Proof.
destruct 2; trivial.
Defined.
Theorem f_equal : x = y -> f x = f y.
Proof.
destruct 1; trivial.
Defined.
Theorem not_eq_sym : x <> y -> y <> x.
Proof.
red; intros h1 h2; apply h1; destruct h2; trivial.
Qed.
End equality.
Definition eq_ind_r :
forall (A:Type) (x:A) (P:A -> Prop), P x -> forall y:A, y = x -> P y.
intros A x P H y H0. elim eq_sym with (1 := H0); assumption.
Defined.
Definition eq_rec_r :
forall (A:Type) (x:A) (P:A -> Set), P x -> forall y:A, y = x -> P y.
intros A x P H y H0; elim eq_sym with (1 := H0); assumption.
Defined.
Definition eq_rect_r :
forall (A:Type) (x:A) (P:A -> Type), P x -> forall y:A, y = x -> P y.
intros A x P H y H0; elim eq_sym with (1 := H0); assumption.
Defined.
End Logic_lemmas.
Module EqNotations.
Notation "'rew' H 'in' H'" := (eq_rect _ _ H' _ H)
(at level 10, H' at level 10,
format "'[' 'rew' H in '/' H' ']'").
Notation "'rew' [ P ] H 'in' H'" := (eq_rect _ P H' _ H)
(at level 10, H' at level 10,
format "'[' 'rew' [ P ] '/ ' H in '/' H' ']'").
Notation "'rew' <- H 'in' H'" := (eq_rect_r _ H' H)
(at level 10, H' at level 10,
format "'[' 'rew' <- H in '/' H' ']'").
Notation "'rew' <- [ P ] H 'in' H'" := (eq_rect_r P H' H)
(at level 10, H' at level 10,
format "'[' 'rew' <- [ P ] '/ ' H in '/' H' ']'").
Notation "'rew' -> H 'in' H'" := (eq_rect _ _ H' _ H)
(at level 10, H' at level 10, only parsing).
Notation "'rew' -> [ P ] H 'in' H'" := (eq_rect _ P H' _ H)
(at level 10, H' at level 10, only parsing).
End EqNotations.
Import EqNotations.
Lemma rew_opp_r : forall A (P:A->Type) (x y:A) (H:x=y) (a:P y), rew H in rew <- H in a = a.
Proof.
intros.
destruct H.
reflexivity.
Defined.
Lemma rew_opp_l : forall A (P:A->Type) (x y:A) (H:x=y) (a:P x), rew <- H in rew H in a = a.
Proof.
intros.
destruct H.
reflexivity.
Defined.
Theorem f_equal2 :
forall (A1 A2 B:Type) (f:A1 -> A2 -> B) (x1 y1:A1)
(x2 y2:A2), x1 = y1 -> x2 = y2 -> f x1 x2 = f y1 y2.
Proof.
destruct 1; destruct 1; reflexivity.
Qed.
Theorem f_equal3 :
forall (A1 A2 A3 B:Type) (f:A1 -> A2 -> A3 -> B) (x1 y1:A1)
(x2 y2:A2) (x3 y3:A3),
x1 = y1 -> x2 = y2 -> x3 = y3 -> f x1 x2 x3 = f y1 y2 y3.
Proof.
destruct 1; destruct 1; destruct 1; reflexivity.
Qed.
Theorem f_equal4 :
forall (A1 A2 A3 A4 B:Type) (f:A1 -> A2 -> A3 -> A4 -> B)
(x1 y1:A1) (x2 y2:A2) (x3 y3:A3) (x4 y4:A4),
x1 = y1 -> x2 = y2 -> x3 = y3 -> x4 = y4 -> f x1 x2 x3 x4 = f y1 y2 y3 y4.
Proof.
destruct 1; destruct 1; destruct 1; destruct 1; reflexivity.
Qed.
Theorem f_equal5 :
forall (A1 A2 A3 A4 A5 B:Type) (f:A1 -> A2 -> A3 -> A4 -> A5 -> B)
(x1 y1:A1) (x2 y2:A2) (x3 y3:A3) (x4 y4:A4) (x5 y5:A5),
x1 = y1 ->
x2 = y2 ->
x3 = y3 -> x4 = y4 -> x5 = y5 -> f x1 x2 x3 x4 x5 = f y1 y2 y3 y4 y5.
Proof.
destruct 1; destruct 1; destruct 1; destruct 1; destruct 1; reflexivity.
Qed.
Theorem f_equal_compose : forall A B C (a b:A) (f:A->B) (g:B->C) (e:a=b),
f_equal g (f_equal f e) = f_equal (fun a => g (f a)) e.
Proof.
destruct e. reflexivity.
Defined.
(** The goupoid structure of equality *)
Theorem eq_trans_refl_l : forall A (x y:A) (e:x=y), eq_trans eq_refl e = e.
Proof.
destruct e. reflexivity.
Defined.
Theorem eq_trans_refl_r : forall A (x y:A) (e:x=y), eq_trans e eq_refl = e.
Proof.
destruct e. reflexivity.
Defined.
Theorem eq_sym_involutive : forall A (x y:A) (e:x=y), eq_sym (eq_sym e) = e.
Proof.
destruct e; reflexivity.
Defined.
Theorem eq_trans_sym_inv_l : forall A (x y:A) (e:x=y), eq_trans (eq_sym e) e = eq_refl.
Proof.
destruct e; reflexivity.
Defined.
Theorem eq_trans_sym_inv_r : forall A (x y:A) (e:x=y), eq_trans e (eq_sym e) = eq_refl.
Proof.
destruct e; reflexivity.
Defined.
Theorem eq_trans_assoc : forall A (x y z t:A) (e:x=y) (e':y=z) (e'':z=t),
eq_trans e (eq_trans e' e'') = eq_trans (eq_trans e e') e''.
Proof.
destruct e''; reflexivity.
Defined.
(** Extra properties of equality *)
Theorem eq_id_comm_l : forall A (f:A->A) (Hf:forall a, a = f a), forall a, f_equal f (Hf a) = Hf (f a).
Proof.
intros.
unfold f_equal.
rewrite <- (eq_trans_sym_inv_l (Hf a)).
destruct (Hf a) at 1 2.
destruct (Hf a).
reflexivity.
Defined.
Theorem eq_id_comm_r : forall A (f:A->A) (Hf:forall a, f a = a), forall a, f_equal f (Hf a) = Hf (f a).
Proof.
intros.
unfold f_equal.
rewrite <- (eq_trans_sym_inv_l (Hf (f (f a)))).
set (Hfsymf := fun a => eq_sym (Hf a)).
change (eq_sym (Hf (f (f a)))) with (Hfsymf (f (f a))).
pattern (Hfsymf (f (f a))).
destruct (eq_id_comm_l f Hfsymf (f a)).
destruct (eq_id_comm_l f Hfsymf a).
unfold Hfsymf.
destruct (Hf a). simpl.
rewrite eq_trans_refl_l.
reflexivity.
Defined.
Lemma eq_trans_map_distr : forall A B x y z (f:A->B) (e:x=y) (e':y=z), f_equal f (eq_trans e e') = eq_trans (f_equal f e) (f_equal f e').
Proof.
destruct e'.
reflexivity.
Defined.
Lemma eq_sym_map_distr : forall A B (x y:A) (f:A->B) (e:x=y), eq_sym (f_equal f e) = f_equal f (eq_sym e).
Proof.
destruct e.
reflexivity.
Defined.
Lemma eq_trans_sym_distr : forall A (x y z:A) (e:x=y) (e':y=z), eq_sym (eq_trans e e') = eq_trans (eq_sym e') (eq_sym e).
Proof.
destruct e, e'.
reflexivity.
Defined.
(* Aliases *)
Notation sym_eq := eq_sym (compat "8.3").
Notation trans_eq := eq_trans (compat "8.3").
Notation sym_not_eq := not_eq_sym (compat "8.3").
Notation refl_equal := eq_refl (compat "8.3").
Notation sym_equal := eq_sym (compat "8.3").
Notation trans_equal := eq_trans (compat "8.3").
Notation sym_not_equal := not_eq_sym (compat "8.3").
Hint Immediate eq_sym not_eq_sym: core.
(** Basic definitions about relations and properties *)
Definition subrelation (A B : Type) (R R' : A->B->Prop) :=
forall x y, R x y -> R' x y.
Definition unique (A : Type) (P : A->Prop) (x:A) :=
P x /\ forall (x':A), P x' -> x=x'.
Definition uniqueness (A:Type) (P:A->Prop) := forall x y, P x -> P y -> x = y.
(** Unique existence *)
Notation "'exists' ! x .. y , p" :=
(ex (unique (fun x => .. (ex (unique (fun y => p))) ..)))
(at level 200, x binder, right associativity,
format "'[' 'exists' ! '/ ' x .. y , '/ ' p ']'")
: type_scope.
Lemma unique_existence : forall (A:Type) (P:A->Prop),
((exists x, P x) /\ uniqueness P) <-> (exists! x, P x).
Proof.
intros A P; split.
- intros ((x,Hx),Huni); exists x; red; auto.
- intros (x,(Hx,Huni)); split.
+ exists x; assumption.
+ intros x' x'' Hx' Hx''; transitivity x.
symmetry; auto.
auto.
Qed.
Lemma forall_exists_unique_domain_coincide :
forall A (P:A->Prop), (exists! x, P x) ->
forall Q:A->Prop, (forall x, P x -> Q x) <-> (exists x, P x /\ Q x).
Proof.
intros A P (x & Hp & Huniq); split.
- intro; exists x; auto.
- intros (x0 & HPx0 & HQx0) x1 HPx1.
replace x1 with x0 by (transitivity x; [symmetry|]; auto).
assumption.
Qed.
Lemma forall_exists_coincide_unique_domain :
forall A (P:A->Prop),
(forall Q:A->Prop, (forall x, P x -> Q x) <-> (exists x, P x /\ Q x))
-> (exists! x, P x).
Proof.
intros A P H.
destruct H with (Q:=P) as ((x & Hx & _),_); [trivial|].
exists x. split; [trivial|].
destruct H with (Q:=fun x'=>x=x') as (_,Huniq).
apply Huniq. exists x; auto.
Qed.
(** * Being inhabited *)
(** The predicate [inhabited] can be used in different contexts. If [A] is
thought as a type, [inhabited A] states that [A] is inhabited. If [A] is
thought as a computationally relevant proposition, then
[inhabited A] weakens [A] so as to hide its computational meaning.
The so-weakened proof remains computationally relevant but only in
a propositional context.
*)
Inductive inhabited (A:Type) : Prop := inhabits : A -> inhabited A.
Hint Resolve inhabits: core.
Lemma exists_inhabited : forall (A:Type) (P:A->Prop),
(exists x, P x) -> inhabited A.
Proof.
destruct 1; auto.
Qed.
(** Declaration of stepl and stepr for eq and iff *)
Lemma eq_stepl : forall (A : Type) (x y z : A), x = y -> x = z -> z = y.
Proof.
intros A x y z H1 H2. rewrite <- H2; exact H1.
Qed.
Declare Left Step eq_stepl.
Declare Right Step eq_trans.
Lemma iff_stepl : forall A B C : Prop, (A <-> B) -> (A <-> C) -> (C <-> B).
Proof.
intros ? ? ? [? ?] [? ?]; split; intros; auto.
Qed.
Declare Left Step iff_stepl.
Declare Right Step iff_trans.
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2012 by Wilson Snyder.
//bug456
typedef logic signed [34:0] rc_t;
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
integer cyc=0;
reg [63:0] crc;
reg [63:0] sum;
// Take CRC data and apply to testblock inputs
wire [34:0] rc = crc[34:0];
/*AUTOWIRE*/
// Beginning of automatic wires (for undeclared instantiated-module outputs)
logic o; // From test of Test.v
// End of automatics
Test test (/*AUTOINST*/
// Outputs
.o (o),
// Inputs
.rc (rc),
.clk (clk));
// Aggregate outputs into a single result vector
wire [63:0] result = {63'h0, o};
// Test loop
always @ (posedge clk) begin
`ifdef TEST_VERBOSE
$write("[%0t] cyc==%0d crc=%x result=%x\n",$time, cyc, crc, result);
`endif
cyc <= cyc + 1;
crc <= {crc[62:0], crc[63]^crc[2]^crc[0]};
sum <= result ^ {sum[62:0],sum[63]^sum[2]^sum[0]};
if (cyc==0) begin
// Setup
crc <= 64'h5aef0c8d_d70a4497;
sum <= 64'h0;
end
else if (cyc<10) begin
sum <= 64'h0;
end
else if (cyc==99) begin
$write("[%0t] cyc==%0d crc=%x sum=%x\n",$time, cyc, crc, sum);
if (crc !== 64'hc77bb9b3784ea091) $stop;
// What checksum will we end up with (above print should match)
`define EXPECTED_SUM 64'h7211d24a17b25ec9
if (sum !== `EXPECTED_SUM) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
module Test( output logic o,
input rc_t rc,
input logic clk);
localparam RATIO = 2;
rc_t rc_d[RATIO:1];
always_ff @(posedge clk) begin
integer k;
rc_d[1] <= rc;
for( k=2; k<RATIO+1; k++ ) begin
rc_d[k] <= rc_d[k-1];
end
end // always_ff @
assign o = rc_d[RATIO] < 0;
endmodule
// Local Variables:
// verilog-typedef-regexp: "_t$"
// End:
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2012 by Wilson Snyder.
//bug456
typedef logic signed [34:0] rc_t;
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
integer cyc=0;
reg [63:0] crc;
reg [63:0] sum;
// Take CRC data and apply to testblock inputs
wire [34:0] rc = crc[34:0];
/*AUTOWIRE*/
// Beginning of automatic wires (for undeclared instantiated-module outputs)
logic o; // From test of Test.v
// End of automatics
Test test (/*AUTOINST*/
// Outputs
.o (o),
// Inputs
.rc (rc),
.clk (clk));
// Aggregate outputs into a single result vector
wire [63:0] result = {63'h0, o};
// Test loop
always @ (posedge clk) begin
`ifdef TEST_VERBOSE
$write("[%0t] cyc==%0d crc=%x result=%x\n",$time, cyc, crc, result);
`endif
cyc <= cyc + 1;
crc <= {crc[62:0], crc[63]^crc[2]^crc[0]};
sum <= result ^ {sum[62:0],sum[63]^sum[2]^sum[0]};
if (cyc==0) begin
// Setup
crc <= 64'h5aef0c8d_d70a4497;
sum <= 64'h0;
end
else if (cyc<10) begin
sum <= 64'h0;
end
else if (cyc==99) begin
$write("[%0t] cyc==%0d crc=%x sum=%x\n",$time, cyc, crc, sum);
if (crc !== 64'hc77bb9b3784ea091) $stop;
// What checksum will we end up with (above print should match)
`define EXPECTED_SUM 64'h7211d24a17b25ec9
if (sum !== `EXPECTED_SUM) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
module Test( output logic o,
input rc_t rc,
input logic clk);
localparam RATIO = 2;
rc_t rc_d[RATIO:1];
always_ff @(posedge clk) begin
integer k;
rc_d[1] <= rc;
for( k=2; k<RATIO+1; k++ ) begin
rc_d[k] <= rc_d[k-1];
end
end // always_ff @
assign o = rc_d[RATIO] < 0;
endmodule
// Local Variables:
// verilog-typedef-regexp: "_t$"
// End:
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2012 by Wilson Snyder.
//bug456
typedef logic signed [34:0] rc_t;
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
integer cyc=0;
reg [63:0] crc;
reg [63:0] sum;
// Take CRC data and apply to testblock inputs
wire [34:0] rc = crc[34:0];
/*AUTOWIRE*/
// Beginning of automatic wires (for undeclared instantiated-module outputs)
logic o; // From test of Test.v
// End of automatics
Test test (/*AUTOINST*/
// Outputs
.o (o),
// Inputs
.rc (rc),
.clk (clk));
// Aggregate outputs into a single result vector
wire [63:0] result = {63'h0, o};
// Test loop
always @ (posedge clk) begin
`ifdef TEST_VERBOSE
$write("[%0t] cyc==%0d crc=%x result=%x\n",$time, cyc, crc, result);
`endif
cyc <= cyc + 1;
crc <= {crc[62:0], crc[63]^crc[2]^crc[0]};
sum <= result ^ {sum[62:0],sum[63]^sum[2]^sum[0]};
if (cyc==0) begin
// Setup
crc <= 64'h5aef0c8d_d70a4497;
sum <= 64'h0;
end
else if (cyc<10) begin
sum <= 64'h0;
end
else if (cyc==99) begin
$write("[%0t] cyc==%0d crc=%x sum=%x\n",$time, cyc, crc, sum);
if (crc !== 64'hc77bb9b3784ea091) $stop;
// What checksum will we end up with (above print should match)
`define EXPECTED_SUM 64'h7211d24a17b25ec9
if (sum !== `EXPECTED_SUM) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
module Test( output logic o,
input rc_t rc,
input logic clk);
localparam RATIO = 2;
rc_t rc_d[RATIO:1];
always_ff @(posedge clk) begin
integer k;
rc_d[1] <= rc;
for( k=2; k<RATIO+1; k++ ) begin
rc_d[k] <= rc_d[k-1];
end
end // always_ff @
assign o = rc_d[RATIO] < 0;
endmodule
// Local Variables:
// verilog-typedef-regexp: "_t$"
// End:
|
// (C) 2001-2015 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
// $File: //acds/rel/15.1/ip/avalon_st/altera_avalon_st_handshake_clock_crosser/altera_avalon_st_handshake_clock_crosser.v $
// $Revision: #1 $
// $Date: 2015/08/09 $
// $Author: swbranch $
//------------------------------------------------------------------------------
// Clock crosser module with handshaking mechanism
//------------------------------------------------------------------------------
`timescale 1ns / 1ns
module altera_avalon_st_handshake_clock_crosser
#(
parameter DATA_WIDTH = 8,
BITS_PER_SYMBOL = 8,
USE_PACKETS = 0,
// ------------------------------
// Optional signal widths
// ------------------------------
USE_CHANNEL = 0,
CHANNEL_WIDTH = 1,
USE_ERROR = 0,
ERROR_WIDTH = 1,
VALID_SYNC_DEPTH = 2,
READY_SYNC_DEPTH = 2,
USE_OUTPUT_PIPELINE = 1,
// ------------------------------
// Derived parameters
// ------------------------------
SYMBOLS_PER_BEAT = DATA_WIDTH / BITS_PER_SYMBOL,
EMPTY_WIDTH = log2ceil(SYMBOLS_PER_BEAT)
)
(
input in_clk,
input in_reset,
input out_clk,
input out_reset,
output in_ready,
input in_valid,
input [DATA_WIDTH - 1 : 0] in_data,
input [CHANNEL_WIDTH - 1 : 0] in_channel,
input [ERROR_WIDTH - 1 : 0] in_error,
input in_startofpacket,
input in_endofpacket,
input [(EMPTY_WIDTH ? (EMPTY_WIDTH - 1) : 0) : 0] in_empty,
input out_ready,
output out_valid,
output [DATA_WIDTH - 1 : 0] out_data,
output [CHANNEL_WIDTH - 1 : 0] out_channel,
output [ERROR_WIDTH - 1 : 0] out_error,
output out_startofpacket,
output out_endofpacket,
output [(EMPTY_WIDTH ? (EMPTY_WIDTH - 1) : 0) : 0] out_empty
);
// ------------------------------
// Payload-specific widths
// ------------------------------
localparam PACKET_WIDTH = (USE_PACKETS) ? 2 + EMPTY_WIDTH : 0;
localparam PCHANNEL_W = (USE_CHANNEL) ? CHANNEL_WIDTH : 0;
localparam PERROR_W = (USE_ERROR) ? ERROR_WIDTH : 0;
localparam PAYLOAD_WIDTH = DATA_WIDTH +
PACKET_WIDTH +
PCHANNEL_W +
EMPTY_WIDTH +
PERROR_W;
wire [PAYLOAD_WIDTH - 1: 0] in_payload;
wire [PAYLOAD_WIDTH - 1: 0] out_payload;
// ------------------------------
// Assign in_data and other optional sink interface
// signals to in_payload.
// ------------------------------
assign in_payload[DATA_WIDTH - 1 : 0] = in_data;
generate
// optional packet inputs
if (PACKET_WIDTH) begin
assign in_payload[
DATA_WIDTH + PACKET_WIDTH - 1 :
DATA_WIDTH
] = {in_startofpacket, in_endofpacket};
end
// optional channel input
if (USE_CHANNEL) begin
assign in_payload[
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W - 1 :
DATA_WIDTH + PACKET_WIDTH
] = in_channel;
end
// optional empty input
if (EMPTY_WIDTH) begin
assign in_payload[
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W + EMPTY_WIDTH - 1 :
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W
] = in_empty;
end
// optional error input
if (USE_ERROR) begin
assign in_payload[
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W + EMPTY_WIDTH + PERROR_W - 1 :
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W + EMPTY_WIDTH
] = in_error;
end
endgenerate
// --------------------------------------------------
// Pipe the input payload to our inner module which handles the
// actual clock crossing
// --------------------------------------------------
altera_avalon_st_clock_crosser
#(
.SYMBOLS_PER_BEAT (1),
.BITS_PER_SYMBOL (PAYLOAD_WIDTH),
.FORWARD_SYNC_DEPTH (VALID_SYNC_DEPTH),
.BACKWARD_SYNC_DEPTH (READY_SYNC_DEPTH),
.USE_OUTPUT_PIPELINE (USE_OUTPUT_PIPELINE)
) clock_xer (
.in_clk (in_clk ),
.in_reset (in_reset ),
.in_ready (in_ready ),
.in_valid (in_valid ),
.in_data (in_payload ),
.out_clk (out_clk ),
.out_reset (out_reset ),
.out_ready (out_ready ),
.out_valid (out_valid ),
.out_data (out_payload )
);
// --------------------------------------------------
// Split out_payload into the output signals.
// --------------------------------------------------
assign out_data = out_payload[DATA_WIDTH - 1 : 0];
generate
// optional packet outputs
if (USE_PACKETS) begin
assign {out_startofpacket, out_endofpacket} =
out_payload[DATA_WIDTH + PACKET_WIDTH - 1 : DATA_WIDTH];
end else begin
// avoid a "has no driver" warning.
assign {out_startofpacket, out_endofpacket} = 2'b0;
end
// optional channel output
if (USE_CHANNEL) begin
assign out_channel = out_payload[
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W - 1 :
DATA_WIDTH + PACKET_WIDTH
];
end else begin
// avoid a "has no driver" warning.
assign out_channel = 1'b0;
end
// optional empty output
if (EMPTY_WIDTH) begin
assign out_empty = out_payload[
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W + EMPTY_WIDTH - 1 :
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W
];
end else begin
// avoid a "has no driver" warning.
assign out_empty = 1'b0;
end
// optional error output
if (USE_ERROR) begin
assign out_error = out_payload[
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W + EMPTY_WIDTH + PERROR_W - 1 :
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W + EMPTY_WIDTH
];
end else begin
// avoid a "has no driver" warning.
assign out_error = 1'b0;
end
endgenerate
// --------------------------------------------------
// Calculates the log2ceil of the input value.
// --------------------------------------------------
function integer log2ceil;
input integer val;
integer i;
begin
i = 1;
log2ceil = 0;
while (i < val) begin
log2ceil = log2ceil + 1;
i = i << 1;
end
end
endfunction
endmodule
|
// (C) 2001-2015 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
// $File: //acds/rel/15.1/ip/avalon_st/altera_avalon_st_handshake_clock_crosser/altera_avalon_st_handshake_clock_crosser.v $
// $Revision: #1 $
// $Date: 2015/08/09 $
// $Author: swbranch $
//------------------------------------------------------------------------------
// Clock crosser module with handshaking mechanism
//------------------------------------------------------------------------------
`timescale 1ns / 1ns
module altera_avalon_st_handshake_clock_crosser
#(
parameter DATA_WIDTH = 8,
BITS_PER_SYMBOL = 8,
USE_PACKETS = 0,
// ------------------------------
// Optional signal widths
// ------------------------------
USE_CHANNEL = 0,
CHANNEL_WIDTH = 1,
USE_ERROR = 0,
ERROR_WIDTH = 1,
VALID_SYNC_DEPTH = 2,
READY_SYNC_DEPTH = 2,
USE_OUTPUT_PIPELINE = 1,
// ------------------------------
// Derived parameters
// ------------------------------
SYMBOLS_PER_BEAT = DATA_WIDTH / BITS_PER_SYMBOL,
EMPTY_WIDTH = log2ceil(SYMBOLS_PER_BEAT)
)
(
input in_clk,
input in_reset,
input out_clk,
input out_reset,
output in_ready,
input in_valid,
input [DATA_WIDTH - 1 : 0] in_data,
input [CHANNEL_WIDTH - 1 : 0] in_channel,
input [ERROR_WIDTH - 1 : 0] in_error,
input in_startofpacket,
input in_endofpacket,
input [(EMPTY_WIDTH ? (EMPTY_WIDTH - 1) : 0) : 0] in_empty,
input out_ready,
output out_valid,
output [DATA_WIDTH - 1 : 0] out_data,
output [CHANNEL_WIDTH - 1 : 0] out_channel,
output [ERROR_WIDTH - 1 : 0] out_error,
output out_startofpacket,
output out_endofpacket,
output [(EMPTY_WIDTH ? (EMPTY_WIDTH - 1) : 0) : 0] out_empty
);
// ------------------------------
// Payload-specific widths
// ------------------------------
localparam PACKET_WIDTH = (USE_PACKETS) ? 2 + EMPTY_WIDTH : 0;
localparam PCHANNEL_W = (USE_CHANNEL) ? CHANNEL_WIDTH : 0;
localparam PERROR_W = (USE_ERROR) ? ERROR_WIDTH : 0;
localparam PAYLOAD_WIDTH = DATA_WIDTH +
PACKET_WIDTH +
PCHANNEL_W +
EMPTY_WIDTH +
PERROR_W;
wire [PAYLOAD_WIDTH - 1: 0] in_payload;
wire [PAYLOAD_WIDTH - 1: 0] out_payload;
// ------------------------------
// Assign in_data and other optional sink interface
// signals to in_payload.
// ------------------------------
assign in_payload[DATA_WIDTH - 1 : 0] = in_data;
generate
// optional packet inputs
if (PACKET_WIDTH) begin
assign in_payload[
DATA_WIDTH + PACKET_WIDTH - 1 :
DATA_WIDTH
] = {in_startofpacket, in_endofpacket};
end
// optional channel input
if (USE_CHANNEL) begin
assign in_payload[
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W - 1 :
DATA_WIDTH + PACKET_WIDTH
] = in_channel;
end
// optional empty input
if (EMPTY_WIDTH) begin
assign in_payload[
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W + EMPTY_WIDTH - 1 :
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W
] = in_empty;
end
// optional error input
if (USE_ERROR) begin
assign in_payload[
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W + EMPTY_WIDTH + PERROR_W - 1 :
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W + EMPTY_WIDTH
] = in_error;
end
endgenerate
// --------------------------------------------------
// Pipe the input payload to our inner module which handles the
// actual clock crossing
// --------------------------------------------------
altera_avalon_st_clock_crosser
#(
.SYMBOLS_PER_BEAT (1),
.BITS_PER_SYMBOL (PAYLOAD_WIDTH),
.FORWARD_SYNC_DEPTH (VALID_SYNC_DEPTH),
.BACKWARD_SYNC_DEPTH (READY_SYNC_DEPTH),
.USE_OUTPUT_PIPELINE (USE_OUTPUT_PIPELINE)
) clock_xer (
.in_clk (in_clk ),
.in_reset (in_reset ),
.in_ready (in_ready ),
.in_valid (in_valid ),
.in_data (in_payload ),
.out_clk (out_clk ),
.out_reset (out_reset ),
.out_ready (out_ready ),
.out_valid (out_valid ),
.out_data (out_payload )
);
// --------------------------------------------------
// Split out_payload into the output signals.
// --------------------------------------------------
assign out_data = out_payload[DATA_WIDTH - 1 : 0];
generate
// optional packet outputs
if (USE_PACKETS) begin
assign {out_startofpacket, out_endofpacket} =
out_payload[DATA_WIDTH + PACKET_WIDTH - 1 : DATA_WIDTH];
end else begin
// avoid a "has no driver" warning.
assign {out_startofpacket, out_endofpacket} = 2'b0;
end
// optional channel output
if (USE_CHANNEL) begin
assign out_channel = out_payload[
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W - 1 :
DATA_WIDTH + PACKET_WIDTH
];
end else begin
// avoid a "has no driver" warning.
assign out_channel = 1'b0;
end
// optional empty output
if (EMPTY_WIDTH) begin
assign out_empty = out_payload[
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W + EMPTY_WIDTH - 1 :
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W
];
end else begin
// avoid a "has no driver" warning.
assign out_empty = 1'b0;
end
// optional error output
if (USE_ERROR) begin
assign out_error = out_payload[
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W + EMPTY_WIDTH + PERROR_W - 1 :
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W + EMPTY_WIDTH
];
end else begin
// avoid a "has no driver" warning.
assign out_error = 1'b0;
end
endgenerate
// --------------------------------------------------
// Calculates the log2ceil of the input value.
// --------------------------------------------------
function integer log2ceil;
input integer val;
integer i;
begin
i = 1;
log2ceil = 0;
while (i < val) begin
log2ceil = log2ceil + 1;
i = i << 1;
end
end
endfunction
endmodule
|
// DESCRIPTION: Verilator: Dedupe optimization test.
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty.
// Contributed 2012 by Varun Koyyalagunta, Centaur Technology.
module t(res,d,clk,en);
output res;
input d,en,clk;
wire q0,q1,q2,q3;
flop_gated_latch f0(q0,d,clk,en);
flop_gated_latch f1(q1,d,clk,en);
flop_gated_flop f2(q2,d,clk,en);
flop_gated_flop f3(q3,d,clk,en);
assign res = (q0 + q1) * (q2 - q3);
endmodule
module flop_gated_latch(q,d,clk,en);
input d, clk, en;
output q;
wire gated_clock;
clock_gate_latch clock_gate(gated_clock, clk, en);
always @(posedge gated_clock) begin
q <= d;
end
endmodule
module flop_gated_flop(q,d,clk,en);
input d, clk, en;
output q;
wire gated_clock;
clock_gate_flop clock_gate(gated_clock, clk, en);
always @(posedge gated_clock) begin
q <= d;
end
endmodule
module clock_gate_latch (gated_clk, clk, clken);
output gated_clk;
input clk, clken;
reg clken_latched /*verilator clock_enable*/;
assign gated_clk = clk & clken_latched ;
wire clkb = ~clk;
always @(clkb or clken)
if(clkb) clken_latched = clken;
endmodule
module clock_gate_flop (gated_clk, clk, clken);
output gated_clk;
input clk, clken;
reg clken_r /*verilator clock_enable*/;
assign gated_clk = clk & clken_r ;
always @(negedge clk)
clken_r <= clken;
endmodule
|
// DESCRIPTION: Verilator: Dedupe optimization test.
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty.
// Contributed 2012 by Varun Koyyalagunta, Centaur Technology.
module t(res,d,clk,en);
output res;
input d,en,clk;
wire q0,q1,q2,q3;
flop_gated_latch f0(q0,d,clk,en);
flop_gated_latch f1(q1,d,clk,en);
flop_gated_flop f2(q2,d,clk,en);
flop_gated_flop f3(q3,d,clk,en);
assign res = (q0 + q1) * (q2 - q3);
endmodule
module flop_gated_latch(q,d,clk,en);
input d, clk, en;
output q;
wire gated_clock;
clock_gate_latch clock_gate(gated_clock, clk, en);
always @(posedge gated_clock) begin
q <= d;
end
endmodule
module flop_gated_flop(q,d,clk,en);
input d, clk, en;
output q;
wire gated_clock;
clock_gate_flop clock_gate(gated_clock, clk, en);
always @(posedge gated_clock) begin
q <= d;
end
endmodule
module clock_gate_latch (gated_clk, clk, clken);
output gated_clk;
input clk, clken;
reg clken_latched /*verilator clock_enable*/;
assign gated_clk = clk & clken_latched ;
wire clkb = ~clk;
always @(clkb or clken)
if(clkb) clken_latched = clken;
endmodule
module clock_gate_flop (gated_clk, clk, clken);
output gated_clk;
input clk, clken;
reg clken_r /*verilator clock_enable*/;
assign gated_clk = clk & clken_r ;
always @(negedge clk)
clken_r <= clken;
endmodule
|
// DESCRIPTION: Verilator: Dedupe optimization test.
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty.
// Contributed 2012 by Varun Koyyalagunta, Centaur Technology.
module t(res,d,clk,en);
output res;
input d,en,clk;
wire q0,q1,q2,q3;
flop_gated_latch f0(q0,d,clk,en);
flop_gated_latch f1(q1,d,clk,en);
flop_gated_flop f2(q2,d,clk,en);
flop_gated_flop f3(q3,d,clk,en);
assign res = (q0 + q1) * (q2 - q3);
endmodule
module flop_gated_latch(q,d,clk,en);
input d, clk, en;
output q;
wire gated_clock;
clock_gate_latch clock_gate(gated_clock, clk, en);
always @(posedge gated_clock) begin
q <= d;
end
endmodule
module flop_gated_flop(q,d,clk,en);
input d, clk, en;
output q;
wire gated_clock;
clock_gate_flop clock_gate(gated_clock, clk, en);
always @(posedge gated_clock) begin
q <= d;
end
endmodule
module clock_gate_latch (gated_clk, clk, clken);
output gated_clk;
input clk, clken;
reg clken_latched /*verilator clock_enable*/;
assign gated_clk = clk & clken_latched ;
wire clkb = ~clk;
always @(clkb or clken)
if(clkb) clken_latched = clken;
endmodule
module clock_gate_flop (gated_clk, clk, clken);
output gated_clk;
input clk, clken;
reg clken_r /*verilator clock_enable*/;
assign gated_clk = clk & clken_r ;
always @(negedge clk)
clken_r <= clken;
endmodule
|
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 17:39:29 10/01/2015
// Design Name:
// Module Name: Zero_InfMult_Unit
// Project Name:
// Target Devices:
// Tool versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module Zero_InfMult_Unit
//SINGLE PRECISION PARAMETERS
# (parameter W = 32)
//DOUBLE PRECISION PARAMETERS
/* # (parameter W = 64) */
(
input wire clk,
input wire rst,
input wire load,
input wire [W-2:0] Data_A,
input wire [W-2:0] Data_B,
output wire zero_m_flag
);
//Wires/////////////////////
wire or_1, or_2;
wire [W-2:0] zero_comp;
wire zero_reg;
////////////////////////////
Comparator_Equal #(.S(W-1)) Data_A_Comp (
.Data_A(Data_A),
.Data_B(zero_comp),
.equal_sgn(or_1)
);
Comparator_Equal #(.S(W-1)) Data_B_Comp (
.Data_A(zero_comp),
.Data_B(Data_B),
.equal_sgn(or_2)
);
RegisterAdd #(.W(1)) Zero_Info_Mult ( //Data X input register
.clk(clk),
.rst(rst),
.load(load),
.D(zero_reg),
.Q(zero_m_flag)
);
assign zero_reg = or_1 || or_2;
generate
if (W == 32)
assign zero_comp = 31'd0;
else
assign zero_comp = 63'd0;
endgenerate
endmodule
|
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 17:39:29 10/01/2015
// Design Name:
// Module Name: Zero_InfMult_Unit
// Project Name:
// Target Devices:
// Tool versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module Zero_InfMult_Unit
//SINGLE PRECISION PARAMETERS
# (parameter W = 32)
//DOUBLE PRECISION PARAMETERS
/* # (parameter W = 64) */
(
input wire clk,
input wire rst,
input wire load,
input wire [W-2:0] Data_A,
input wire [W-2:0] Data_B,
output wire zero_m_flag
);
//Wires/////////////////////
wire or_1, or_2;
wire [W-2:0] zero_comp;
wire zero_reg;
////////////////////////////
Comparator_Equal #(.S(W-1)) Data_A_Comp (
.Data_A(Data_A),
.Data_B(zero_comp),
.equal_sgn(or_1)
);
Comparator_Equal #(.S(W-1)) Data_B_Comp (
.Data_A(zero_comp),
.Data_B(Data_B),
.equal_sgn(or_2)
);
RegisterAdd #(.W(1)) Zero_Info_Mult ( //Data X input register
.clk(clk),
.rst(rst),
.load(load),
.D(zero_reg),
.Q(zero_m_flag)
);
assign zero_reg = or_1 || or_2;
generate
if (W == 32)
assign zero_comp = 31'd0;
else
assign zero_comp = 63'd0;
endgenerate
endmodule
|
// DESCRIPTION: Verilator: Test of gated clock detection
//
// The code as shown generates a result by a delayed assignment from PC. The
// creation of the result is from a clock gated from the clock that sets
// PC. Howevever since they are essentially the same clock, the result should
// be delayed by one cycle.
//
// Standard Verilator treats them as different clocks, so the result stays in
// step with the PC. An event drive simulator always allows the clock to win.
//
// The problem is caused by the extra loop added by Verilator to the
// evaluation of all internally generated clocks (effectively removed by
// marking the clock enable).
//
// This test is added to facilitate experiments with solutions.
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2013 by Jeremy Bennett <[email protected]>.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
reg gated_clk_en = 1'b0 ;
reg [1:0] pc = 2'b0;
reg [1:0] res = 2'b0;
wire gated_clk = gated_clk_en & clk;
always @(posedge clk) begin
pc <= pc + 1;
gated_clk_en <= 1'b1;
end
always @(posedge gated_clk) begin
res <= pc;
end
always @(posedge clk) begin
if (pc == 2'b11) begin
// Correct behaviour is that res should be lagging pc in the count
// by one cycle
if (res == 2'b10) begin
$write("*-* All Finished *-*\n");
$finish;
end
else begin
$stop;
end
end
end
endmodule
|
// DESCRIPTION: Verilator: Test of gated clock detection
//
// The code as shown generates a result by a delayed assignment from PC. The
// creation of the result is from a clock gated from the clock that sets
// PC. Howevever since they are essentially the same clock, the result should
// be delayed by one cycle.
//
// Standard Verilator treats them as different clocks, so the result stays in
// step with the PC. An event drive simulator always allows the clock to win.
//
// The problem is caused by the extra loop added by Verilator to the
// evaluation of all internally generated clocks (effectively removed by
// marking the clock enable).
//
// This test is added to facilitate experiments with solutions.
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2013 by Jeremy Bennett <[email protected]>.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
reg gated_clk_en = 1'b0 ;
reg [1:0] pc = 2'b0;
reg [1:0] res = 2'b0;
wire gated_clk = gated_clk_en & clk;
always @(posedge clk) begin
pc <= pc + 1;
gated_clk_en <= 1'b1;
end
always @(posedge gated_clk) begin
res <= pc;
end
always @(posedge clk) begin
if (pc == 2'b11) begin
// Correct behaviour is that res should be lagging pc in the count
// by one cycle
if (res == 2'b10) begin
$write("*-* All Finished *-*\n");
$finish;
end
else begin
$stop;
end
end
end
endmodule
|
// DESCRIPTION: Verilator: Test of gated clock detection
//
// The code as shown generates a result by a delayed assignment from PC. The
// creation of the result is from a clock gated from the clock that sets
// PC. Howevever since they are essentially the same clock, the result should
// be delayed by one cycle.
//
// Standard Verilator treats them as different clocks, so the result stays in
// step with the PC. An event drive simulator always allows the clock to win.
//
// The problem is caused by the extra loop added by Verilator to the
// evaluation of all internally generated clocks (effectively removed by
// marking the clock enable).
//
// This test is added to facilitate experiments with solutions.
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2013 by Jeremy Bennett <[email protected]>.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
reg gated_clk_en = 1'b0 ;
reg [1:0] pc = 2'b0;
reg [1:0] res = 2'b0;
wire gated_clk = gated_clk_en & clk;
always @(posedge clk) begin
pc <= pc + 1;
gated_clk_en <= 1'b1;
end
always @(posedge gated_clk) begin
res <= pc;
end
always @(posedge clk) begin
if (pc == 2'b11) begin
// Correct behaviour is that res should be lagging pc in the count
// by one cycle
if (res == 2'b10) begin
$write("*-* All Finished *-*\n");
$finish;
end
else begin
$stop;
end
end
end
endmodule
|
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 03/18/2016 03:28:31 PM
// Design Name:
// Module Name: Round_Sgf_Dec
// Project Name:
// Target Devices:
// Tool Versions:
// Description:
//
// Dep encies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module Round_Sgf_Dec(
input wire clk,
input wire [1:0] Data_i,
input wire [1:0] Round_Type_i,
input wire Sign_Result_i,
output reg Round_Flag_o
);
always @*
case ({Sign_Result_i,Round_Type_i,Data_i})
//Round type=00; Towards zero / No round
//Round type=01; Towards - infinity
//Round type=10; Towards + infinity
//Op=0;Round type=00
/*5'b00000: Round_Flag_o <=0;
5'b00001: Round_Flag_o <=0;
5'b00010: Round_Flag_o <=0;
5'b00011: Round_Flag_o <=0;*/
//Op=1;Round type=00
/*5'b10000: Round_Flag_o <=0;
5'b10001: Round_Flag_o <=0;
5'b10010: Round_Flag_o <=0;
5'b10011: Round_Flag_o <=0; */
//Op=0;Round type=01
/*5'b00100: Round_Flag_o <=0;
5'b00101: Round_Flag_o <=0;
5'b00110: Round_Flag_o <=0;
5'b00111: Round_Flag_o <=0; */
//Op=1;Round type=01
//5'b10100: Round_Flag_o <=0;
5'b10101: Round_Flag_o <=1;
5'b10110: Round_Flag_o <=1;
5'b10111: Round_Flag_o <=1;
//Op=0;Round type=10
//5'b01000: Round_Flag_o <=0;
5'b01001: Round_Flag_o <=1;
5'b01010: Round_Flag_o <=1;
5'b01011: Round_Flag_o <=1;
//Op=1;Round type=10
/*5'b11000: Round_Flag_o <=0;
5'b11001: Round_Flag_o <=0;
5'b11010: Round_Flag_o <=0;
5'b11011: Round_Flag_o <=0; */
default: Round_Flag_o <=0;
endcase
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2009 by Wilson Snyder.
package defs;
function automatic integer max;
input integer a;
input integer b;
max = (a > b) ? a : b;
endfunction
function automatic integer log2;
input integer value;
value = value >> 1;
for (log2 = 0; value > 0; log2 = log2 + 1)
value = value >> 1;
endfunction
function automatic integer ceil_log2;
input integer value;
value = value - 1;
for (ceil_log2 = 0; value > 0; ceil_log2 = ceil_log2 + 1)
value = value >> 1;
endfunction
endpackage
module sub();
import defs::*;
parameter RAND_NUM_MAX = "";
localparam DATA_RANGE = RAND_NUM_MAX + 1;
localparam DATA_WIDTH = ceil_log2(DATA_RANGE);
localparam WIDTH = max(4, ceil_log2(DATA_RANGE + 1));
endmodule
module t(/*AUTOARG*/
// Inputs
clk
);
import defs::*;
parameter WHICH = 0;
parameter MAX_COUNT = 10;
localparam MAX_EXPONENT = log2(MAX_COUNT);
localparam EXPONENT_WIDTH = ceil_log2(MAX_EXPONENT + 1);
input clk;
generate
if (WHICH == 1)
begin : which_true
sub sub_true();
defparam sub_true.RAND_NUM_MAX = MAX_EXPONENT;
end
else
begin : which_false
sub sub_false();
defparam sub_false.RAND_NUM_MAX = MAX_COUNT;
end
endgenerate
endmodule
|
//-----------------------------------------------------------------------------
// Copyright (C) 2014 iZsh <izsh at fail0verflow.com>
//
// This code is licensed to you under the terms of the GNU GPL, version 2 or,
// at your option, any later version. See the LICENSE.txt file for the text of
// the license.
//-----------------------------------------------------------------------------
// testbench for lf_edge_detect
`include "lf_edge_detect.v"
`define FIN "tb_tmp/data.filtered.gold"
`define FOUT_MIN "tb_tmp/data.min"
`define FOUT_MAX "tb_tmp/data.max"
`define FOUT_STATE "tb_tmp/data.state"
`define FOUT_TOGGLE "tb_tmp/data.toggle"
`define FOUT_HIGH "tb_tmp/data.high"
`define FOUT_HIGHZ "tb_tmp/data.highz"
`define FOUT_LOWZ "tb_tmp/data.lowz"
`define FOUT_LOW "tb_tmp/data.low"
module lf_edge_detect_tb;
integer fin, fout_state, fout_toggle;
integer fout_high, fout_highz, fout_lowz, fout_low, fout_min, fout_max;
integer r;
reg clk = 0;
reg [7:0] adc_d;
wire adc_clk;
wire data_rdy;
wire edge_state;
wire edge_toggle;
wire [7:0] high_threshold;
wire [7:0] highz_threshold;
wire [7:0] lowz_threshold;
wire [7:0] low_threshold;
wire [7:0] max;
wire [7:0] min;
initial
begin
clk = 0;
fin = $fopen(`FIN, "r");
if (!fin) begin
$display("ERROR: can't open the data file");
$finish;
end
fout_min = $fopen(`FOUT_MIN, "w+");
fout_max = $fopen(`FOUT_MAX, "w+");
fout_state = $fopen(`FOUT_STATE, "w+");
fout_toggle = $fopen(`FOUT_TOGGLE, "w+");
fout_high = $fopen(`FOUT_HIGH, "w+");
fout_highz = $fopen(`FOUT_HIGHZ, "w+");
fout_lowz = $fopen(`FOUT_LOWZ, "w+");
fout_low = $fopen(`FOUT_LOW, "w+");
if (!$feof(fin))
adc_d = $fgetc(fin); // read the first value
end
always
# 1 clk = !clk;
// input
initial
begin
while (!$feof(fin)) begin
@(negedge clk) adc_d <= $fgetc(fin);
end
if ($feof(fin))
begin
# 3 $fclose(fin);
$fclose(fout_state);
$fclose(fout_toggle);
$fclose(fout_high);
$fclose(fout_highz);
$fclose(fout_lowz);
$fclose(fout_low);
$fclose(fout_min);
$fclose(fout_max);
$finish;
end
end
initial
begin
// $monitor("%d\t S: %b, E: %b", $time, edge_state, edge_toggle);
end
// output
always @(negedge clk)
if ($time > 2) begin
r = $fputc(min, fout_min);
r = $fputc(max, fout_max);
r = $fputc(edge_state, fout_state);
r = $fputc(edge_toggle, fout_toggle);
r = $fputc(high_threshold, fout_high);
r = $fputc(highz_threshold, fout_highz);
r = $fputc(lowz_threshold, fout_lowz);
r = $fputc(low_threshold, fout_low);
end
// module to test
lf_edge_detect detect(clk, adc_d, 8'd127,
max, min,
high_threshold, highz_threshold,
lowz_threshold, low_threshold,
edge_state, edge_toggle);
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2009 by Wilson Snyder.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
integer cyc=0;
genvar g;
integer i;
reg [31:0] v;
reg [31:0] gen_pre_PLUSPLUS = 32'h0;
reg [31:0] gen_pre_MINUSMINUS = 32'h0;
reg [31:0] gen_post_PLUSPLUS = 32'h0;
reg [31:0] gen_post_MINUSMINUS = 32'h0;
reg [31:0] gen_PLUSEQ = 32'h0;
reg [31:0] gen_MINUSEQ = 32'h0;
reg [31:0] gen_TIMESEQ = 32'h0;
reg [31:0] gen_DIVEQ = 32'h0;
reg [31:0] gen_MODEQ = 32'h0;
reg [31:0] gen_ANDEQ = 32'h0;
reg [31:0] gen_OREQ = 32'h0;
reg [31:0] gen_XOREQ = 32'h0;
reg [31:0] gen_SLEFTEQ = 32'h0;
reg [31:0] gen_SRIGHTEQ = 32'h0;
reg [31:0] gen_SSRIGHTEQ = 32'h0;
generate
for (g=8; g<=16; ++g) always @(posedge clk) gen_pre_PLUSPLUS[g] = 1'b1;
for (g=16; g>=8; --g) always @(posedge clk) gen_pre_MINUSMINUS[g] = 1'b1;
for (g=8; g<=16; g++) always @(posedge clk) gen_post_PLUSPLUS[g] = 1'b1;
for (g=16; g>=8; g--) always @(posedge clk) gen_post_MINUSMINUS[g] = 1'b1;
for (g=8; g<=16; g+=2) always @(posedge clk) gen_PLUSEQ[g] = 1'b1;
for (g=16; g>=8; g-=2) always @(posedge clk) gen_MINUSEQ[g] = 1'b1;
`ifndef verilator //UNSUPPORTED
for (g=8; g<=16; g*=2) always @(posedge clk) gen_TIMESEQ[g] = 1'b1;
for (g=16; g>=8; g/=2) always @(posedge clk) gen_DIVEQ[g] = 1'b1;
for (g=15; g>8; g%=8) always @(posedge clk) gen_MODEQ[g] = 1'b1;
for (g=7; g>4; g&=4) always @(posedge clk) gen_ANDEQ[g] = 1'b1;
for (g=1; g<=1; g|=2) always @(posedge clk) gen_OREQ[g] = 1'b1;
for (g=7; g==7; g^=2) always @(posedge clk) gen_XOREQ[g] = 1'b1;
for (g=8; g<=16; g<<=2) always @(posedge clk) gen_SLEFTEQ[g] = 1'b1;
for (g=16; g>=8; g>>=2) always @(posedge clk) gen_SRIGHTEQ[g] = 1'b1;
for (g=16; g>=8; g>>>=2) always @(posedge clk) gen_SSRIGHTEQ[g] = 1'b1;
`endif
endgenerate
always @ (posedge clk) begin
cyc <= cyc + 1;
if (cyc == 3) begin
`ifdef TEST_VERBOSE
$write("gen_pre_PLUSPLUS %b\n", gen_pre_PLUSPLUS);
$write("gen_pre_MINUSMINUS %b\n", gen_pre_MINUSMINUS);
$write("gen_post_PLUSPLUS %b\n", gen_post_PLUSPLUS);
$write("gen_post_MINUSMINUS %b\n", gen_post_MINUSMINUS);
$write("gen_PLUSEQ %b\n", gen_PLUSEQ);
$write("gen_MINUSEQ %b\n", gen_MINUSEQ);
$write("gen_TIMESEQ %b\n", gen_TIMESEQ);
$write("gen_DIVEQ %b\n", gen_DIVEQ);
$write("gen_MODEQ %b\n", gen_MODEQ);
$write("gen_ANDEQ %b\n", gen_ANDEQ);
$write("gen_OREQ %b\n", gen_OREQ);
$write("gen_XOREQ %b\n", gen_XOREQ);
$write("gen_SLEFTEQ %b\n", gen_SLEFTEQ);
$write("gen_SRIGHTEQ %b\n", gen_SRIGHTEQ);
$write("gen_SSRIGHTEQ %b\n", gen_SSRIGHTEQ);
`endif
if (gen_pre_PLUSPLUS !== 32'b00000000000000011111111100000000) $stop;
if (gen_pre_MINUSMINUS !== 32'b00000000000000011111111100000000) $stop;
if (gen_post_PLUSPLUS !== 32'b00000000000000011111111100000000) $stop;
if (gen_post_MINUSMINUS!== 32'b00000000000000011111111100000000) $stop;
if (gen_PLUSEQ !== 32'b00000000000000010101010100000000) $stop;
if (gen_MINUSEQ !== 32'b00000000000000010101010100000000) $stop;
`ifndef verilator //UNSUPPORTED
if (gen_TIMESEQ !== 32'b00000000000000010000000100000000) $stop;
if (gen_DIVEQ !== 32'b00000000000000010000000100000000) $stop;
if (gen_MODEQ !== 32'b00000000000000001000000000000000) $stop;
if (gen_ANDEQ !== 32'b00000000000000000000000010000000) $stop;
if (gen_OREQ !== 32'b00000000000000000000000000000010) $stop;
if (gen_XOREQ !== 32'b00000000000000000000000010000000) $stop;
if (gen_SLEFTEQ !== 32'b00000000000000000000000100000000) $stop;
if (gen_SRIGHTEQ !== 32'b00000000000000010000000000000000) $stop;
if (gen_SSRIGHTEQ !== 32'b00000000000000010000000000000000) $stop;
`endif
v=0; for (i=8; i<=16; ++i) v[i] = 1'b1; if (v !== 32'b00000000000000011111111100000000) $stop;
v=0; for (i=16; i>=8; --i) v[i] = 1'b1; if (v !== 32'b00000000000000011111111100000000) $stop;
v=0; for (i=8; i<=16; i++) v[i] = 1'b1; if (v !== 32'b00000000000000011111111100000000) $stop;
v=0; for (i=16; i>=8; i--) v[i] = 1'b1; if (v !== 32'b00000000000000011111111100000000) $stop;
v=0; for (i=8; i<=16; i+=2) v[i] = 1'b1; if (v !== 32'b00000000000000010101010100000000) $stop;
v=0; for (i=16; i>=8; i-=2) v[i] = 1'b1; if (v !== 32'b00000000000000010101010100000000) $stop;
`ifndef verilator //UNSUPPORTED
v=0; for (i=8; i<=16; i*=2) v[i] = 1'b1; if (v !== 32'b00000000000000010000000100000000) $stop;
v=0; for (i=16; i>=8; i/=2) v[i] = 1'b1; if (v !== 32'b00000000000000010000000100000000) $stop;
v=0; for (i=15; i>8; i%=8) v[i] = 1'b1; if (v !== 32'b00000000000000001000000000000000) $stop;
v=0; for (i=7; i>4; i&=4) v[i] = 1'b1; if (v !== 32'b00000000000000000000000010000000) $stop;
v=0; for (i=1; i<=1; i|=2) v[i] = 1'b1; if (v !== 32'b00000000000000000000000000000010) $stop;
v=0; for (i=7; i==7; i^=2) v[i] = 1'b1; if (v !== 32'b00000000000000000000000010000000) $stop;
v=0; for (i=8; i<=16; i<<=2) v[i] =1'b1; if (v !== 32'b00000000000000000000000100000000) $stop;
v=0; for (i=16; i>=8; i>>=2) v[i] =1'b1; if (v !== 32'b00000000000000010000000000000000) $stop;
v=0; for (i=16; i>=8; i>>>=2) v[i]=1'b1; if (v !== 32'b00000000000000010000000000000000) $stop;
`endif
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2009 by Wilson Snyder.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
integer cyc=0;
genvar g;
integer i;
reg [31:0] v;
reg [31:0] gen_pre_PLUSPLUS = 32'h0;
reg [31:0] gen_pre_MINUSMINUS = 32'h0;
reg [31:0] gen_post_PLUSPLUS = 32'h0;
reg [31:0] gen_post_MINUSMINUS = 32'h0;
reg [31:0] gen_PLUSEQ = 32'h0;
reg [31:0] gen_MINUSEQ = 32'h0;
reg [31:0] gen_TIMESEQ = 32'h0;
reg [31:0] gen_DIVEQ = 32'h0;
reg [31:0] gen_MODEQ = 32'h0;
reg [31:0] gen_ANDEQ = 32'h0;
reg [31:0] gen_OREQ = 32'h0;
reg [31:0] gen_XOREQ = 32'h0;
reg [31:0] gen_SLEFTEQ = 32'h0;
reg [31:0] gen_SRIGHTEQ = 32'h0;
reg [31:0] gen_SSRIGHTEQ = 32'h0;
generate
for (g=8; g<=16; ++g) always @(posedge clk) gen_pre_PLUSPLUS[g] = 1'b1;
for (g=16; g>=8; --g) always @(posedge clk) gen_pre_MINUSMINUS[g] = 1'b1;
for (g=8; g<=16; g++) always @(posedge clk) gen_post_PLUSPLUS[g] = 1'b1;
for (g=16; g>=8; g--) always @(posedge clk) gen_post_MINUSMINUS[g] = 1'b1;
for (g=8; g<=16; g+=2) always @(posedge clk) gen_PLUSEQ[g] = 1'b1;
for (g=16; g>=8; g-=2) always @(posedge clk) gen_MINUSEQ[g] = 1'b1;
`ifndef verilator //UNSUPPORTED
for (g=8; g<=16; g*=2) always @(posedge clk) gen_TIMESEQ[g] = 1'b1;
for (g=16; g>=8; g/=2) always @(posedge clk) gen_DIVEQ[g] = 1'b1;
for (g=15; g>8; g%=8) always @(posedge clk) gen_MODEQ[g] = 1'b1;
for (g=7; g>4; g&=4) always @(posedge clk) gen_ANDEQ[g] = 1'b1;
for (g=1; g<=1; g|=2) always @(posedge clk) gen_OREQ[g] = 1'b1;
for (g=7; g==7; g^=2) always @(posedge clk) gen_XOREQ[g] = 1'b1;
for (g=8; g<=16; g<<=2) always @(posedge clk) gen_SLEFTEQ[g] = 1'b1;
for (g=16; g>=8; g>>=2) always @(posedge clk) gen_SRIGHTEQ[g] = 1'b1;
for (g=16; g>=8; g>>>=2) always @(posedge clk) gen_SSRIGHTEQ[g] = 1'b1;
`endif
endgenerate
always @ (posedge clk) begin
cyc <= cyc + 1;
if (cyc == 3) begin
`ifdef TEST_VERBOSE
$write("gen_pre_PLUSPLUS %b\n", gen_pre_PLUSPLUS);
$write("gen_pre_MINUSMINUS %b\n", gen_pre_MINUSMINUS);
$write("gen_post_PLUSPLUS %b\n", gen_post_PLUSPLUS);
$write("gen_post_MINUSMINUS %b\n", gen_post_MINUSMINUS);
$write("gen_PLUSEQ %b\n", gen_PLUSEQ);
$write("gen_MINUSEQ %b\n", gen_MINUSEQ);
$write("gen_TIMESEQ %b\n", gen_TIMESEQ);
$write("gen_DIVEQ %b\n", gen_DIVEQ);
$write("gen_MODEQ %b\n", gen_MODEQ);
$write("gen_ANDEQ %b\n", gen_ANDEQ);
$write("gen_OREQ %b\n", gen_OREQ);
$write("gen_XOREQ %b\n", gen_XOREQ);
$write("gen_SLEFTEQ %b\n", gen_SLEFTEQ);
$write("gen_SRIGHTEQ %b\n", gen_SRIGHTEQ);
$write("gen_SSRIGHTEQ %b\n", gen_SSRIGHTEQ);
`endif
if (gen_pre_PLUSPLUS !== 32'b00000000000000011111111100000000) $stop;
if (gen_pre_MINUSMINUS !== 32'b00000000000000011111111100000000) $stop;
if (gen_post_PLUSPLUS !== 32'b00000000000000011111111100000000) $stop;
if (gen_post_MINUSMINUS!== 32'b00000000000000011111111100000000) $stop;
if (gen_PLUSEQ !== 32'b00000000000000010101010100000000) $stop;
if (gen_MINUSEQ !== 32'b00000000000000010101010100000000) $stop;
`ifndef verilator //UNSUPPORTED
if (gen_TIMESEQ !== 32'b00000000000000010000000100000000) $stop;
if (gen_DIVEQ !== 32'b00000000000000010000000100000000) $stop;
if (gen_MODEQ !== 32'b00000000000000001000000000000000) $stop;
if (gen_ANDEQ !== 32'b00000000000000000000000010000000) $stop;
if (gen_OREQ !== 32'b00000000000000000000000000000010) $stop;
if (gen_XOREQ !== 32'b00000000000000000000000010000000) $stop;
if (gen_SLEFTEQ !== 32'b00000000000000000000000100000000) $stop;
if (gen_SRIGHTEQ !== 32'b00000000000000010000000000000000) $stop;
if (gen_SSRIGHTEQ !== 32'b00000000000000010000000000000000) $stop;
`endif
v=0; for (i=8; i<=16; ++i) v[i] = 1'b1; if (v !== 32'b00000000000000011111111100000000) $stop;
v=0; for (i=16; i>=8; --i) v[i] = 1'b1; if (v !== 32'b00000000000000011111111100000000) $stop;
v=0; for (i=8; i<=16; i++) v[i] = 1'b1; if (v !== 32'b00000000000000011111111100000000) $stop;
v=0; for (i=16; i>=8; i--) v[i] = 1'b1; if (v !== 32'b00000000000000011111111100000000) $stop;
v=0; for (i=8; i<=16; i+=2) v[i] = 1'b1; if (v !== 32'b00000000000000010101010100000000) $stop;
v=0; for (i=16; i>=8; i-=2) v[i] = 1'b1; if (v !== 32'b00000000000000010101010100000000) $stop;
`ifndef verilator //UNSUPPORTED
v=0; for (i=8; i<=16; i*=2) v[i] = 1'b1; if (v !== 32'b00000000000000010000000100000000) $stop;
v=0; for (i=16; i>=8; i/=2) v[i] = 1'b1; if (v !== 32'b00000000000000010000000100000000) $stop;
v=0; for (i=15; i>8; i%=8) v[i] = 1'b1; if (v !== 32'b00000000000000001000000000000000) $stop;
v=0; for (i=7; i>4; i&=4) v[i] = 1'b1; if (v !== 32'b00000000000000000000000010000000) $stop;
v=0; for (i=1; i<=1; i|=2) v[i] = 1'b1; if (v !== 32'b00000000000000000000000000000010) $stop;
v=0; for (i=7; i==7; i^=2) v[i] = 1'b1; if (v !== 32'b00000000000000000000000010000000) $stop;
v=0; for (i=8; i<=16; i<<=2) v[i] =1'b1; if (v !== 32'b00000000000000000000000100000000) $stop;
v=0; for (i=16; i>=8; i>>=2) v[i] =1'b1; if (v !== 32'b00000000000000010000000000000000) $stop;
v=0; for (i=16; i>=8; i>>>=2) v[i]=1'b1; if (v !== 32'b00000000000000010000000000000000) $stop;
`endif
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
|
//////////////////////////////////////////////////////////////////////
//// ////
//// spi_top.v ////
//// ////
//// This file is part of the SPI IP core project ////
//// http://www.opencores.org/projects/spi/ ////
//// ////
//// Author(s): ////
//// - Simon Srot ([email protected]) ////
//// ////
//// All additional information is avaliable in the Readme.txt ////
//// file. ////
//// ////
//////////////////////////////////////////////////////////////////////
//// ////
//// Copyright (C) 2002 Authors ////
//// ////
//// This source file may be used and distributed without ////
//// restriction provided that this copyright statement is not ////
//// removed from the file and that any derivative work contains ////
//// the original copyright notice and the associated disclaimer. ////
//// ////
//// This source file is free software; you can redistribute it ////
//// and/or modify it under the terms of the GNU Lesser General ////
//// Public License as published by the Free Software Foundation; ////
//// either version 2.1 of the License, or (at your option) any ////
//// later version. ////
//// ////
//// This source is distributed in the hope that it will be ////
//// useful, but WITHOUT ANY WARRANTY; without even the implied ////
//// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR ////
//// PURPOSE. See the GNU Lesser General Public License for more ////
//// details. ////
//// ////
//// You should have received a copy of the GNU Lesser General ////
//// Public License along with this source; if not, download it ////
//// from http://www.opencores.org/lgpl.shtml ////
//// ////
//////////////////////////////////////////////////////////////////////
////
//// /* Modifications to spi_top.v */
//// /* Copyright (c) 2006 Rice University */
//// /* All Rights Reserved */
//// /* This code is covered by the Rice-WARP license */
//// /* See http://warp.rice.edu/license/ for details */
module spi_top
(
// OPB signals
opb_clk_i, opb_rst_i,
// SPI registers
reg_ctrl, reg_ss, reg_divider, reg_tx, ctrlwrite, busval, go,
// SPI signals
ss_pad_o, sclk_pad_o, mosi_pad_o
);
parameter Tp = 1;
// OPB signals
input opb_clk_i; // master clock input
input opb_rst_i; // synchronous active high reset
// SPI registers
input [13:0] reg_ctrl;
input [7:0] reg_ss;
input [3:0] reg_divider;
input [17:0] reg_tx;
input ctrlwrite;
input busval;
output go;
// SPI signals
output [8-1:0] ss_pad_o; // slave select
output sclk_pad_o; // serial clock
output mosi_pad_o; // master out slave in
// Internal signals
wire [17:0] rx; // Rx register
wire rx_negedge; // miso is sampled on negative edge
wire tx_negedge; // mosi is driven on negative edge
wire [4:0] char_len; // char len
//wire go; // go
wire lsb; // lsb first on line
wire ie; // interrupt enable
wire ass; // automatic slave select
wire spi_divider_sel; // divider register select
wire spi_ctrl_sel; // ctrl register select
wire [3:0] spi_tx_sel; // tx_l register select
wire spi_ss_sel; // ss register select
wire tip; // transfer in progress
wire pos_edge; // recognize posedge of sclk
wire neg_edge; // recognize negedge of sclk
wire last_bit; // marks last character bit
reg ctrlbitgo;
assign rx_negedge = reg_ctrl[9];
assign tx_negedge = reg_ctrl[10];
assign go = ctrlbitgo;
assign char_len = reg_ctrl[6:0];
assign lsb = reg_ctrl[11];
assign ie = reg_ctrl[12];
assign ass = reg_ctrl[13];
always @(posedge opb_clk_i or posedge opb_rst_i)
begin
if (opb_rst_i)
ctrlbitgo <= #Tp 1'b0;
else if(ctrlwrite && !tip)
ctrlbitgo <= #Tp busval;
else if(tip && last_bit && pos_edge)
ctrlbitgo <= #Tp 1'b0;
end
assign ss_pad_o = ~((reg_ss & {8{tip & ass}}) | (reg_ss & {8{!ass}}));
spi_clgen clgen (.clk_in(opb_clk_i), .rst(opb_rst_i), .go(go), .enable(tip), .last_clk(last_bit),
.divider(reg_divider), .clk_out(sclk_pad_o), .pos_edge(pos_edge),
.neg_edge(neg_edge));
spi_shift shift (.clk(opb_clk_i), .rst(opb_rst_i), .len(char_len[5-1:0]),
.lsb(lsb), .go(go), .pos_edge(pos_edge), .neg_edge(neg_edge),
.rx_negedge(rx_negedge), .tx_negedge(tx_negedge),
.tip(tip), .last(last_bit),
.p_in(reg_tx), .p_out(rx),
.s_clk(sclk_pad_o), .s_out(mosi_pad_o));
endmodule
|
//////////////////////////////////////////////////////////////////////
//// ////
//// spi_top.v ////
//// ////
//// This file is part of the SPI IP core project ////
//// http://www.opencores.org/projects/spi/ ////
//// ////
//// Author(s): ////
//// - Simon Srot ([email protected]) ////
//// ////
//// All additional information is avaliable in the Readme.txt ////
//// file. ////
//// ////
//////////////////////////////////////////////////////////////////////
//// ////
//// Copyright (C) 2002 Authors ////
//// ////
//// This source file may be used and distributed without ////
//// restriction provided that this copyright statement is not ////
//// removed from the file and that any derivative work contains ////
//// the original copyright notice and the associated disclaimer. ////
//// ////
//// This source file is free software; you can redistribute it ////
//// and/or modify it under the terms of the GNU Lesser General ////
//// Public License as published by the Free Software Foundation; ////
//// either version 2.1 of the License, or (at your option) any ////
//// later version. ////
//// ////
//// This source is distributed in the hope that it will be ////
//// useful, but WITHOUT ANY WARRANTY; without even the implied ////
//// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR ////
//// PURPOSE. See the GNU Lesser General Public License for more ////
//// details. ////
//// ////
//// You should have received a copy of the GNU Lesser General ////
//// Public License along with this source; if not, download it ////
//// from http://www.opencores.org/lgpl.shtml ////
//// ////
//////////////////////////////////////////////////////////////////////
////
//// /* Modifications to spi_top.v */
//// /* Copyright (c) 2006 Rice University */
//// /* All Rights Reserved */
//// /* This code is covered by the Rice-WARP license */
//// /* See http://warp.rice.edu/license/ for details */
module spi_top
(
// OPB signals
opb_clk_i, opb_rst_i,
// SPI registers
reg_ctrl, reg_ss, reg_divider, reg_tx, ctrlwrite, busval, go,
// SPI signals
ss_pad_o, sclk_pad_o, mosi_pad_o
);
parameter Tp = 1;
// OPB signals
input opb_clk_i; // master clock input
input opb_rst_i; // synchronous active high reset
// SPI registers
input [13:0] reg_ctrl;
input [7:0] reg_ss;
input [3:0] reg_divider;
input [17:0] reg_tx;
input ctrlwrite;
input busval;
output go;
// SPI signals
output [8-1:0] ss_pad_o; // slave select
output sclk_pad_o; // serial clock
output mosi_pad_o; // master out slave in
// Internal signals
wire [17:0] rx; // Rx register
wire rx_negedge; // miso is sampled on negative edge
wire tx_negedge; // mosi is driven on negative edge
wire [4:0] char_len; // char len
//wire go; // go
wire lsb; // lsb first on line
wire ie; // interrupt enable
wire ass; // automatic slave select
wire spi_divider_sel; // divider register select
wire spi_ctrl_sel; // ctrl register select
wire [3:0] spi_tx_sel; // tx_l register select
wire spi_ss_sel; // ss register select
wire tip; // transfer in progress
wire pos_edge; // recognize posedge of sclk
wire neg_edge; // recognize negedge of sclk
wire last_bit; // marks last character bit
reg ctrlbitgo;
assign rx_negedge = reg_ctrl[9];
assign tx_negedge = reg_ctrl[10];
assign go = ctrlbitgo;
assign char_len = reg_ctrl[6:0];
assign lsb = reg_ctrl[11];
assign ie = reg_ctrl[12];
assign ass = reg_ctrl[13];
always @(posedge opb_clk_i or posedge opb_rst_i)
begin
if (opb_rst_i)
ctrlbitgo <= #Tp 1'b0;
else if(ctrlwrite && !tip)
ctrlbitgo <= #Tp busval;
else if(tip && last_bit && pos_edge)
ctrlbitgo <= #Tp 1'b0;
end
assign ss_pad_o = ~((reg_ss & {8{tip & ass}}) | (reg_ss & {8{!ass}}));
spi_clgen clgen (.clk_in(opb_clk_i), .rst(opb_rst_i), .go(go), .enable(tip), .last_clk(last_bit),
.divider(reg_divider), .clk_out(sclk_pad_o), .pos_edge(pos_edge),
.neg_edge(neg_edge));
spi_shift shift (.clk(opb_clk_i), .rst(opb_rst_i), .len(char_len[5-1:0]),
.lsb(lsb), .go(go), .pos_edge(pos_edge), .neg_edge(neg_edge),
.rx_negedge(rx_negedge), .tx_negedge(tx_negedge),
.tip(tip), .last(last_bit),
.p_in(reg_tx), .p_out(rx),
.s_clk(sclk_pad_o), .s_out(mosi_pad_o));
endmodule
|
//////////////////////////////////////////////////////////////////////
//// ////
//// spi_top.v ////
//// ////
//// This file is part of the SPI IP core project ////
//// http://www.opencores.org/projects/spi/ ////
//// ////
//// Author(s): ////
//// - Simon Srot ([email protected]) ////
//// ////
//// All additional information is avaliable in the Readme.txt ////
//// file. ////
//// ////
//////////////////////////////////////////////////////////////////////
//// ////
//// Copyright (C) 2002 Authors ////
//// ////
//// This source file may be used and distributed without ////
//// restriction provided that this copyright statement is not ////
//// removed from the file and that any derivative work contains ////
//// the original copyright notice and the associated disclaimer. ////
//// ////
//// This source file is free software; you can redistribute it ////
//// and/or modify it under the terms of the GNU Lesser General ////
//// Public License as published by the Free Software Foundation; ////
//// either version 2.1 of the License, or (at your option) any ////
//// later version. ////
//// ////
//// This source is distributed in the hope that it will be ////
//// useful, but WITHOUT ANY WARRANTY; without even the implied ////
//// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR ////
//// PURPOSE. See the GNU Lesser General Public License for more ////
//// details. ////
//// ////
//// You should have received a copy of the GNU Lesser General ////
//// Public License along with this source; if not, download it ////
//// from http://www.opencores.org/lgpl.shtml ////
//// ////
//////////////////////////////////////////////////////////////////////
////
//// /* Modifications to spi_top.v */
//// /* Copyright (c) 2006 Rice University */
//// /* All Rights Reserved */
//// /* This code is covered by the Rice-WARP license */
//// /* See http://warp.rice.edu/license/ for details */
module spi_top
(
// OPB signals
opb_clk_i, opb_rst_i,
// SPI registers
reg_ctrl, reg_ss, reg_divider, reg_tx, ctrlwrite, busval, go,
// SPI signals
ss_pad_o, sclk_pad_o, mosi_pad_o
);
parameter Tp = 1;
// OPB signals
input opb_clk_i; // master clock input
input opb_rst_i; // synchronous active high reset
// SPI registers
input [13:0] reg_ctrl;
input [7:0] reg_ss;
input [3:0] reg_divider;
input [17:0] reg_tx;
input ctrlwrite;
input busval;
output go;
// SPI signals
output [8-1:0] ss_pad_o; // slave select
output sclk_pad_o; // serial clock
output mosi_pad_o; // master out slave in
// Internal signals
wire [17:0] rx; // Rx register
wire rx_negedge; // miso is sampled on negative edge
wire tx_negedge; // mosi is driven on negative edge
wire [4:0] char_len; // char len
//wire go; // go
wire lsb; // lsb first on line
wire ie; // interrupt enable
wire ass; // automatic slave select
wire spi_divider_sel; // divider register select
wire spi_ctrl_sel; // ctrl register select
wire [3:0] spi_tx_sel; // tx_l register select
wire spi_ss_sel; // ss register select
wire tip; // transfer in progress
wire pos_edge; // recognize posedge of sclk
wire neg_edge; // recognize negedge of sclk
wire last_bit; // marks last character bit
reg ctrlbitgo;
assign rx_negedge = reg_ctrl[9];
assign tx_negedge = reg_ctrl[10];
assign go = ctrlbitgo;
assign char_len = reg_ctrl[6:0];
assign lsb = reg_ctrl[11];
assign ie = reg_ctrl[12];
assign ass = reg_ctrl[13];
always @(posedge opb_clk_i or posedge opb_rst_i)
begin
if (opb_rst_i)
ctrlbitgo <= #Tp 1'b0;
else if(ctrlwrite && !tip)
ctrlbitgo <= #Tp busval;
else if(tip && last_bit && pos_edge)
ctrlbitgo <= #Tp 1'b0;
end
assign ss_pad_o = ~((reg_ss & {8{tip & ass}}) | (reg_ss & {8{!ass}}));
spi_clgen clgen (.clk_in(opb_clk_i), .rst(opb_rst_i), .go(go), .enable(tip), .last_clk(last_bit),
.divider(reg_divider), .clk_out(sclk_pad_o), .pos_edge(pos_edge),
.neg_edge(neg_edge));
spi_shift shift (.clk(opb_clk_i), .rst(opb_rst_i), .len(char_len[5-1:0]),
.lsb(lsb), .go(go), .pos_edge(pos_edge), .neg_edge(neg_edge),
.rx_negedge(rx_negedge), .tx_negedge(tx_negedge),
.tip(tip), .last(last_bit),
.p_in(reg_tx), .p_out(rx),
.s_clk(sclk_pad_o), .s_out(mosi_pad_o));
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2013.
// bug648
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
integer cyc=0;
reg [63:0] crc;
reg [63:0] sum;
// Take CRC data and apply to testblock inputs
wire [7:0] datai = crc[7:0];
wire enable = crc[8];
/*AUTOWIRE*/
// Beginning of automatic wires (for undeclared instantiated-module outputs)
logic [7:0] datao; // From test of Test.v
// End of automatics
Test test (/*AUTOINST*/
// Outputs
.datao (datao[7:0]),
// Inputs
.clk (clk),
.datai (datai[7:0]),
.enable (enable));
// Aggregate outputs into a single result vector
wire [63:0] result = {56'h0, datao};
// Test loop
always @ (posedge clk) begin
`ifdef TEST_VERBOSE
$write("[%0t] cyc==%0d crc=%x result=%x\n",$time, cyc, crc, result);
`endif
cyc <= cyc + 1;
crc <= {crc[62:0], crc[63]^crc[2]^crc[0]};
sum <= result ^ {sum[62:0],sum[63]^sum[2]^sum[0]};
if (cyc==0) begin
// Setup
crc <= 64'h5aef0c8d_d70a4497;
sum <= 64'h0;
end
else if (cyc<10) begin
sum <= 64'h0;
end
else if (cyc<90) begin
end
else if (cyc==99) begin
$write("[%0t] cyc==%0d crc=%x sum=%x\n",$time, cyc, crc, sum);
if (crc !== 64'hc77bb9b3784ea091) $stop;
// What checksum will we end up with (above print should match)
`define EXPECTED_SUM 64'h9d550d82d38926fa
if (sum !== `EXPECTED_SUM) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
`define FAIL 1
module Nested
(
input logic clk,
input logic x,
output logic y
);
logic t;
always_comb t = x ^ 1'b1;
always_ff @(posedge clk) begin
if (clk)
y <= t;
end
endmodule
module Test
(
input logic clk,
input logic [7:0] datai,
input logic enable,
output logic [7:0] datao
);
// verilator lint_off BLKANDNBLK
logic [7:0] datat;
// verilator lint_on BLKANDNBLK
for (genvar i = 0; i < 8; i++) begin
if (i%4 != 3) begin
`ifndef FAIL
logic t;
always_comb begin
t = datai[i] ^ 1'b1;
end
always_ff @(posedge clk) begin
if (clk)
datat[i] <= t;
end
`else
Nested nested_i
(
.clk(clk),
.x(datai[i]),
.y(datat[i]) //<== via Vcellout wire
);
`endif
always_comb begin
casez (enable)
1'b1: datao[i] = datat[i];
1'b0: datao[i] = '0;
default: datao[i] = 'x;
endcase
end
end
else begin
always_ff @(posedge clk) begin
if (clk)
datat[i] <= 0; //<== assign delayed
end
always_comb begin
casez (enable)
1'b1: datao[i] = datat[i] ^ 1'b1;
1'b0: datao[i] = '1;
default: datao[i] = 'x;
endcase
end
end
end
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2013.
// bug648
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
integer cyc=0;
reg [63:0] crc;
reg [63:0] sum;
// Take CRC data and apply to testblock inputs
wire [7:0] datai = crc[7:0];
wire enable = crc[8];
/*AUTOWIRE*/
// Beginning of automatic wires (for undeclared instantiated-module outputs)
logic [7:0] datao; // From test of Test.v
// End of automatics
Test test (/*AUTOINST*/
// Outputs
.datao (datao[7:0]),
// Inputs
.clk (clk),
.datai (datai[7:0]),
.enable (enable));
// Aggregate outputs into a single result vector
wire [63:0] result = {56'h0, datao};
// Test loop
always @ (posedge clk) begin
`ifdef TEST_VERBOSE
$write("[%0t] cyc==%0d crc=%x result=%x\n",$time, cyc, crc, result);
`endif
cyc <= cyc + 1;
crc <= {crc[62:0], crc[63]^crc[2]^crc[0]};
sum <= result ^ {sum[62:0],sum[63]^sum[2]^sum[0]};
if (cyc==0) begin
// Setup
crc <= 64'h5aef0c8d_d70a4497;
sum <= 64'h0;
end
else if (cyc<10) begin
sum <= 64'h0;
end
else if (cyc<90) begin
end
else if (cyc==99) begin
$write("[%0t] cyc==%0d crc=%x sum=%x\n",$time, cyc, crc, sum);
if (crc !== 64'hc77bb9b3784ea091) $stop;
// What checksum will we end up with (above print should match)
`define EXPECTED_SUM 64'h9d550d82d38926fa
if (sum !== `EXPECTED_SUM) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
`define FAIL 1
module Nested
(
input logic clk,
input logic x,
output logic y
);
logic t;
always_comb t = x ^ 1'b1;
always_ff @(posedge clk) begin
if (clk)
y <= t;
end
endmodule
module Test
(
input logic clk,
input logic [7:0] datai,
input logic enable,
output logic [7:0] datao
);
// verilator lint_off BLKANDNBLK
logic [7:0] datat;
// verilator lint_on BLKANDNBLK
for (genvar i = 0; i < 8; i++) begin
if (i%4 != 3) begin
`ifndef FAIL
logic t;
always_comb begin
t = datai[i] ^ 1'b1;
end
always_ff @(posedge clk) begin
if (clk)
datat[i] <= t;
end
`else
Nested nested_i
(
.clk(clk),
.x(datai[i]),
.y(datat[i]) //<== via Vcellout wire
);
`endif
always_comb begin
casez (enable)
1'b1: datao[i] = datat[i];
1'b0: datao[i] = '0;
default: datao[i] = 'x;
endcase
end
end
else begin
always_ff @(posedge clk) begin
if (clk)
datat[i] <= 0; //<== assign delayed
end
always_comb begin
casez (enable)
1'b1: datao[i] = datat[i] ^ 1'b1;
1'b0: datao[i] = '1;
default: datao[i] = 'x;
endcase
end
end
end
endmodule
|
//wishbone_arbiter.v
/*
Distributed under the MIT licesnse.
Copyright (c) 2011 Dave McCoy ([email protected])
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
`timescale 1 ns/1 ps
module arbiter_2_masters (
//control signals
input clk,
input rst,
//wishbone master ports
input i_m0_we,
input i_m0_cyc,
input i_m0_stb,
input [3:0] i_m0_sel,
output o_m0_ack,
input [31:0] i_m0_dat,
output [31:0] o_m0_dat,
input [31:0] i_m0_adr,
output o_m0_int,
input i_m1_we,
input i_m1_cyc,
input i_m1_stb,
input [3:0] i_m1_sel,
output o_m1_ack,
input [31:0] i_m1_dat,
output [31:0] o_m1_dat,
input [31:0] i_m1_adr,
output o_m1_int,
//wishbone slave signals
output o_s_we,
output o_s_stb,
output o_s_cyc,
output [3:0] o_s_sel,
output [31:0] o_s_adr,
output [31:0] o_s_dat,
input [31:0] i_s_dat,
input i_s_ack,
input i_s_int
);
localparam MASTER_COUNT = 2;
//registers/wires
//this should be parameterized
reg [7:0] master_select;
reg [7:0] priority_select;
wire o_master_we [MASTER_COUNT - 1:0];
wire o_master_stb [MASTER_COUNT - 1:0];
wire o_master_cyc [MASTER_COUNT - 1:0];
wire [3:0] o_master_sel [MASTER_COUNT - 1:0];
wire [31:0] o_master_adr [MASTER_COUNT - 1:0];
wire [31:0] o_master_dat [MASTER_COUNT - 1:0];
//master select block
localparam MASTER_NO_SEL = 8'hFF;
localparam MASTER_0 = 0;
localparam MASTER_1 = 1;
always @ (posedge clk) begin
if (rst) begin
master_select <= MASTER_NO_SEL;
end
else begin
case (master_select)
MASTER_0: begin
if (!i_m0_cyc && !i_s_ack) begin
master_select <= MASTER_NO_SEL;
end
end
MASTER_1: begin
if (!i_m1_cyc && !i_s_ack) begin
master_select <= MASTER_NO_SEL;
end
end
default: begin
//nothing selected
if (i_m0_cyc) begin
master_select <= MASTER_0;
end
else if (i_m1_cyc) begin
master_select <= MASTER_1;
end
end
endcase
if ((master_select != MASTER_NO_SEL) && (priority_select < master_select) && (!o_s_stb && !i_s_ack))begin
master_select <= MASTER_NO_SEL;
end
end
end
//priority select
always @ (posedge clk) begin
if (rst) begin
priority_select <= MASTER_NO_SEL;
end
else begin
//find the highest priority
if (i_m0_cyc) begin
priority_select <= MASTER_0;
end
else if (i_m1_cyc) begin
priority_select <= MASTER_1;
end
else begin
priority_select <= MASTER_NO_SEL;
end
end
end
//slave assignments
assign o_s_we = (master_select != MASTER_NO_SEL) ? o_master_we[master_select] : 0;
assign o_s_stb = (master_select != MASTER_NO_SEL) ? o_master_stb[master_select] : 0;
assign o_s_cyc = (master_select != MASTER_NO_SEL) ? o_master_cyc[master_select] : 0;
assign o_s_sel = (master_select != MASTER_NO_SEL) ? o_master_sel[master_select] : 0;
assign o_s_adr = (master_select != MASTER_NO_SEL) ? o_master_adr[master_select] : 0;
assign o_s_dat = (master_select != MASTER_NO_SEL) ? o_master_dat[master_select] : 0;
//write select block
assign o_master_we[MASTER_0] = i_m0_we;
assign o_master_we[MASTER_1] = i_m1_we;
//strobe select block
assign o_master_stb[MASTER_0] = i_m0_stb;
assign o_master_stb[MASTER_1] = i_m1_stb;
//cycle select block
assign o_master_cyc[MASTER_0] = i_m0_cyc;
assign o_master_cyc[MASTER_1] = i_m1_cyc;
//select select block
assign o_master_sel[MASTER_0] = i_m0_sel;
assign o_master_sel[MASTER_1] = i_m1_sel;
//address seelct block
assign o_master_adr[MASTER_0] = i_m0_adr;
assign o_master_adr[MASTER_1] = i_m1_adr;
//data select block
assign o_master_dat[MASTER_0] = i_m0_dat;
assign o_master_dat[MASTER_1] = i_m1_dat;
//assign block
assign o_m0_ack = (master_select == MASTER_0) ? i_s_ack : 0;
assign o_m0_dat = i_s_dat;
assign o_m0_int = (master_select == MASTER_0) ? i_s_int : 0;
assign o_m1_ack = (master_select == MASTER_1) ? i_s_ack : 0;
assign o_m1_dat = i_s_dat;
assign o_m1_int = (master_select == MASTER_1) ? i_s_int : 0;
endmodule
|
//wishbone_arbiter.v
/*
Distributed under the MIT licesnse.
Copyright (c) 2011 Dave McCoy ([email protected])
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
`timescale 1 ns/1 ps
module arbiter_2_masters (
//control signals
input clk,
input rst,
//wishbone master ports
input i_m0_we,
input i_m0_cyc,
input i_m0_stb,
input [3:0] i_m0_sel,
output o_m0_ack,
input [31:0] i_m0_dat,
output [31:0] o_m0_dat,
input [31:0] i_m0_adr,
output o_m0_int,
input i_m1_we,
input i_m1_cyc,
input i_m1_stb,
input [3:0] i_m1_sel,
output o_m1_ack,
input [31:0] i_m1_dat,
output [31:0] o_m1_dat,
input [31:0] i_m1_adr,
output o_m1_int,
//wishbone slave signals
output o_s_we,
output o_s_stb,
output o_s_cyc,
output [3:0] o_s_sel,
output [31:0] o_s_adr,
output [31:0] o_s_dat,
input [31:0] i_s_dat,
input i_s_ack,
input i_s_int
);
localparam MASTER_COUNT = 2;
//registers/wires
//this should be parameterized
reg [7:0] master_select;
reg [7:0] priority_select;
wire o_master_we [MASTER_COUNT - 1:0];
wire o_master_stb [MASTER_COUNT - 1:0];
wire o_master_cyc [MASTER_COUNT - 1:0];
wire [3:0] o_master_sel [MASTER_COUNT - 1:0];
wire [31:0] o_master_adr [MASTER_COUNT - 1:0];
wire [31:0] o_master_dat [MASTER_COUNT - 1:0];
//master select block
localparam MASTER_NO_SEL = 8'hFF;
localparam MASTER_0 = 0;
localparam MASTER_1 = 1;
always @ (posedge clk) begin
if (rst) begin
master_select <= MASTER_NO_SEL;
end
else begin
case (master_select)
MASTER_0: begin
if (!i_m0_cyc && !i_s_ack) begin
master_select <= MASTER_NO_SEL;
end
end
MASTER_1: begin
if (!i_m1_cyc && !i_s_ack) begin
master_select <= MASTER_NO_SEL;
end
end
default: begin
//nothing selected
if (i_m0_cyc) begin
master_select <= MASTER_0;
end
else if (i_m1_cyc) begin
master_select <= MASTER_1;
end
end
endcase
if ((master_select != MASTER_NO_SEL) && (priority_select < master_select) && (!o_s_stb && !i_s_ack))begin
master_select <= MASTER_NO_SEL;
end
end
end
//priority select
always @ (posedge clk) begin
if (rst) begin
priority_select <= MASTER_NO_SEL;
end
else begin
//find the highest priority
if (i_m0_cyc) begin
priority_select <= MASTER_0;
end
else if (i_m1_cyc) begin
priority_select <= MASTER_1;
end
else begin
priority_select <= MASTER_NO_SEL;
end
end
end
//slave assignments
assign o_s_we = (master_select != MASTER_NO_SEL) ? o_master_we[master_select] : 0;
assign o_s_stb = (master_select != MASTER_NO_SEL) ? o_master_stb[master_select] : 0;
assign o_s_cyc = (master_select != MASTER_NO_SEL) ? o_master_cyc[master_select] : 0;
assign o_s_sel = (master_select != MASTER_NO_SEL) ? o_master_sel[master_select] : 0;
assign o_s_adr = (master_select != MASTER_NO_SEL) ? o_master_adr[master_select] : 0;
assign o_s_dat = (master_select != MASTER_NO_SEL) ? o_master_dat[master_select] : 0;
//write select block
assign o_master_we[MASTER_0] = i_m0_we;
assign o_master_we[MASTER_1] = i_m1_we;
//strobe select block
assign o_master_stb[MASTER_0] = i_m0_stb;
assign o_master_stb[MASTER_1] = i_m1_stb;
//cycle select block
assign o_master_cyc[MASTER_0] = i_m0_cyc;
assign o_master_cyc[MASTER_1] = i_m1_cyc;
//select select block
assign o_master_sel[MASTER_0] = i_m0_sel;
assign o_master_sel[MASTER_1] = i_m1_sel;
//address seelct block
assign o_master_adr[MASTER_0] = i_m0_adr;
assign o_master_adr[MASTER_1] = i_m1_adr;
//data select block
assign o_master_dat[MASTER_0] = i_m0_dat;
assign o_master_dat[MASTER_1] = i_m1_dat;
//assign block
assign o_m0_ack = (master_select == MASTER_0) ? i_s_ack : 0;
assign o_m0_dat = i_s_dat;
assign o_m0_int = (master_select == MASTER_0) ? i_s_int : 0;
assign o_m1_ack = (master_select == MASTER_1) ? i_s_ack : 0;
assign o_m1_dat = i_s_dat;
assign o_m1_int = (master_select == MASTER_1) ? i_s_int : 0;
endmodule
|
/*+--------------------------------------------------------------------------
Copyright (c) 2015, Microsoft Corporation
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------*/
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: Microsoft Research Asia
// Engineer: Jiansong Zhang
//
// Create Date: 12:17:59 11/12/2009
// Design Name:
// Module Name: performance_counter
// Project Name: Sora
// Target Devices: LX50T1136-1
// Tool versions: ISE 10.02
// Description: We measure the durations in this module (1) from TX_des request sent to tx_engine to new des
// received (2) from transfer start to transfer done.
// A counter (125MHz or 250MHz depends on DMA clock) is implemeted.
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module performance_counter(
input clk,
input rst,
input transferstart_one,
input rd_dma_done_one,
input new_des_one,
output reg [23:0] round_trip_latency,
output reg [23:0] transfer_duration
);
reg [39:0] counter; /// free run 40bits counter, more than two hours per cycle on 125MHz clock
reg [23:0] snapshot_transferstart; /// record the lower 24 bit of counter when transferstart, more than 100ms per cycle on 125MHz clock
/// counter
always@(posedge clk) begin
if(rst)
counter <= 40'h00_0000_0000;
else
counter <= counter + 40'h00_0000_0001;
end
/// snapshot_transferstart
always@(posedge clk) begin
if(rst)
snapshot_transferstart <= 24'h00_0000;
else if (transferstart_one)
snapshot_transferstart <= counter[23:0];
else
snapshot_transferstart <= snapshot_transferstart;
end
/// round_trip_latency
always@(posedge clk) begin
if (rst)
round_trip_latency <= 24'h00_0000;
else if (new_des_one)
round_trip_latency <= counter[23:0] + (~snapshot_transferstart) + 24'h00_0001;
else
round_trip_latency <= round_trip_latency;
end
/// transfer_duration
always@(posedge clk) begin
if (rst)
transfer_duration <= 24'h00_0000;
else if (rd_dma_done_one)
transfer_duration <= counter[23:0] + (~snapshot_transferstart) + 24'h00_0001;
else
transfer_duration <= transfer_duration;
end
endmodule
|
/*+--------------------------------------------------------------------------
Copyright (c) 2015, Microsoft Corporation
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------*/
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: Microsoft Research Asia
// Engineer: Jiansong Zhang
//
// Create Date: 12:17:59 11/12/2009
// Design Name:
// Module Name: performance_counter
// Project Name: Sora
// Target Devices: LX50T1136-1
// Tool versions: ISE 10.02
// Description: We measure the durations in this module (1) from TX_des request sent to tx_engine to new des
// received (2) from transfer start to transfer done.
// A counter (125MHz or 250MHz depends on DMA clock) is implemeted.
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module performance_counter(
input clk,
input rst,
input transferstart_one,
input rd_dma_done_one,
input new_des_one,
output reg [23:0] round_trip_latency,
output reg [23:0] transfer_duration
);
reg [39:0] counter; /// free run 40bits counter, more than two hours per cycle on 125MHz clock
reg [23:0] snapshot_transferstart; /// record the lower 24 bit of counter when transferstart, more than 100ms per cycle on 125MHz clock
/// counter
always@(posedge clk) begin
if(rst)
counter <= 40'h00_0000_0000;
else
counter <= counter + 40'h00_0000_0001;
end
/// snapshot_transferstart
always@(posedge clk) begin
if(rst)
snapshot_transferstart <= 24'h00_0000;
else if (transferstart_one)
snapshot_transferstart <= counter[23:0];
else
snapshot_transferstart <= snapshot_transferstart;
end
/// round_trip_latency
always@(posedge clk) begin
if (rst)
round_trip_latency <= 24'h00_0000;
else if (new_des_one)
round_trip_latency <= counter[23:0] + (~snapshot_transferstart) + 24'h00_0001;
else
round_trip_latency <= round_trip_latency;
end
/// transfer_duration
always@(posedge clk) begin
if (rst)
transfer_duration <= 24'h00_0000;
else if (rd_dma_done_one)
transfer_duration <= counter[23:0] + (~snapshot_transferstart) + 24'h00_0001;
else
transfer_duration <= transfer_duration;
end
endmodule
|
/*+--------------------------------------------------------------------------
Copyright (c) 2015, Microsoft Corporation
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------*/
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: Microsoft Research Asia
// Engineer: Jiansong Zhang
//
// Create Date: 12:17:59 11/12/2009
// Design Name:
// Module Name: performance_counter
// Project Name: Sora
// Target Devices: LX50T1136-1
// Tool versions: ISE 10.02
// Description: We measure the durations in this module (1) from TX_des request sent to tx_engine to new des
// received (2) from transfer start to transfer done.
// A counter (125MHz or 250MHz depends on DMA clock) is implemeted.
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module performance_counter(
input clk,
input rst,
input transferstart_one,
input rd_dma_done_one,
input new_des_one,
output reg [23:0] round_trip_latency,
output reg [23:0] transfer_duration
);
reg [39:0] counter; /// free run 40bits counter, more than two hours per cycle on 125MHz clock
reg [23:0] snapshot_transferstart; /// record the lower 24 bit of counter when transferstart, more than 100ms per cycle on 125MHz clock
/// counter
always@(posedge clk) begin
if(rst)
counter <= 40'h00_0000_0000;
else
counter <= counter + 40'h00_0000_0001;
end
/// snapshot_transferstart
always@(posedge clk) begin
if(rst)
snapshot_transferstart <= 24'h00_0000;
else if (transferstart_one)
snapshot_transferstart <= counter[23:0];
else
snapshot_transferstart <= snapshot_transferstart;
end
/// round_trip_latency
always@(posedge clk) begin
if (rst)
round_trip_latency <= 24'h00_0000;
else if (new_des_one)
round_trip_latency <= counter[23:0] + (~snapshot_transferstart) + 24'h00_0001;
else
round_trip_latency <= round_trip_latency;
end
/// transfer_duration
always@(posedge clk) begin
if (rst)
transfer_duration <= 24'h00_0000;
else if (rd_dma_done_one)
transfer_duration <= counter[23:0] + (~snapshot_transferstart) + 24'h00_0001;
else
transfer_duration <= transfer_duration;
end
endmodule
|
/*+--------------------------------------------------------------------------
Copyright (c) 2015, Microsoft Corporation
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------*/
//////////////////////////////////////////////////////////////////////////////////
// Company: Microsoft Research Asia
// Engineer: Jiansong Zhang
//
// Create Date: 21:39:39 06/01/2009
// Design Name:
// Module Name: rx_trn_data_fsm
// Project Name: Sora
// Target Devices: Virtex5 LX50T
// Tool versions: ISE10.1.03
// Description:
// Purpose: Receive TRN Data FSM. This module interfaces to the Block Plus RX
// TRN. It presents the 64-bit data from completer and and forwards that
// data with a data_valid signal. This block also decodes packet header info
// and forwards it to the rx_trn_monitor block.
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
`timescale 1ns / 1ps
module rx_trn_data_fsm(
input wire clk,
input wire rst,
// Rx Local-Link
input wire [63:0] trn_rd,
input wire [7:0] trn_rrem_n,
input wire trn_rsof_n,
input wire trn_reof_n,
input wire trn_rsrc_rdy_n,
input wire trn_rsrc_dsc_n,
output reg trn_rdst_rdy_n,
input wire trn_rerrfwd_n,
output wire trn_rnp_ok_n,
input wire [6:0] trn_rbar_hit_n,
input wire [11:0] trn_rfc_npd_av,
input wire [7:0] trn_rfc_nph_av,
input wire [11:0] trn_rfc_pd_av,
input wire [7:0] trn_rfc_ph_av,
input wire [11:0] trn_rfc_cpld_av,
input wire [7:0] trn_rfc_cplh_av,
output wire trn_rcpl_streaming_n,
//DATA FIFO SIGNALS
output reg [63:0] data_out,
output wire [7:0] data_out_be,
output reg data_valid,
input wire data_fifo_status,
//END DATA FIFO SIGNALS
//HEADER FIELD SIGNALS
//The following are registered from the header fields of the current packet
//See the PCIe Base Specification for definitions of these headers
output reg fourdw_n_threedw, //fourdw = 1'b1; 3dw = 1'b0;
output reg payload,
output reg [2:0] tc, //traffic class
output reg td, //digest
output reg ep, //poisoned bit
output reg [1:0] attr, //attribute field
output reg [9:0] dw_length, //DWORD Length
//the following fields are dependent on the type of TLP being received
//regs with MEM prefix are valid for memory TLPS and regs with CMP prefix
//are valid for completion TLPS
output reg [15:0] MEM_req_id, //requester ID for memory TLPs
output reg [7:0] MEM_tag, //tag for non-posted memory read request
output reg [15:0] CMP_comp_id, //completer id for completion TLPs
output reg [2:0]CMP_compl_stat, //status for completion TLPs
output reg CMP_bcm, //byte count modified field for completions TLPs
output reg [11:0] CMP_byte_count, //remaining byte count for completion TLPs
output reg [63:0] MEM_addr, //address field for memory TLPs
output reg [15:0] CMP_req_id, //requester if for completions TLPs
output reg [7:0] CMP_tag, //tag field for completion TLPs
output reg [6:0] CMP_lower_addr, //lower address field for completion TLPs
//decode of the format field
output wire MRd, //Mem read
output wire MWr, //Mem write
output wire CplD, //Completion w/ data
output wire Msg, //Message TLP
output wire UR, //Unsupported request TLP i.e. IO, CPL,etc..
output reg [6:0] bar_hit, //valid when a BAR is hit
output reg header_fields_valid//valid signal to qualify the above header fields
//END HEADER FIELD SIGNALS
);
//state machine states
localparam IDLE = 3'b000;
localparam NOT_READY = 3'b001;
localparam SOF = 3'b010;
localparam HEAD2 = 3'b011;
localparam BODY = 3'b100;
localparam EOF = 3'b101;
//additional pipelines regs for RX TRN interface
reg [63:0] trn_rd_d1;
reg [7:0] trn_rrem_d1_n;
reg trn_rsof_d1_n;
reg trn_reof_d1_n;
reg trn_rsrc_rdy_d1_n;
reg trn_rsrc_dsc_d1_n;
reg trn_rerrfwd_d1_n;
reg [6:0] trn_rbar_hit_d1_n;
reg [11:0] trn_rfc_npd_av_d1;
reg [7:0] trn_rfc_nph_av_d1;
reg [11:0] trn_rfc_pd_av_d1;
reg [7:0] trn_rfc_ph_av_d1;
reg [11:0] trn_rfc_cpld_av_d1;
reg [7:0] trn_rfc_cplh_av_d1;
//second pipeline
reg [63:0] trn_rd_d2;
reg [7:0] trn_rrem_d2_n;
reg trn_rsof_d2_n;
reg trn_reof_d2_n;
reg trn_rsrc_rdy_d2_n;
reg trn_rsrc_dsc_d2_n;
reg trn_rerrfwd_d2_n;
reg [6:0] trn_rbar_hit_d2_n;
reg [11:0] trn_rfc_npd_av_d2;
reg [7:0] trn_rfc_nph_av_d2;
reg [11:0] trn_rfc_pd_av_d2;
reg [7:0] trn_rfc_ph_av_d2;
reg [11:0] trn_rfc_cpld_av_d2;
reg [7:0] trn_rfc_cplh_av_d2;
reg [4:0] rx_packet_type;
reg [2:0] trn_state;
wire [63:0] data_out_mux;
wire [7:0] data_out_be_mux;
reg data_valid_early;
reg rst_reg;
always@(posedge clk) rst_reg <= rst;
// TIE constant signals here
assign trn_rnp_ok_n = 1'b0;
assign trn_rcpl_streaming_n = 1'b0; //use completion streaming mode
//all the outputs of the endpoint should be pipelined
//to help meet required timing of an 8 lane design
always @ (posedge clk)
begin
trn_rd_d1[63:0] <= trn_rd[63:0] ;
trn_rrem_d1_n[7:0] <= trn_rrem_n[7:0] ;
trn_rsof_d1_n <= trn_rsof_n ;
trn_reof_d1_n <= trn_reof_n ;
trn_rsrc_rdy_d1_n <= trn_rsrc_rdy_n ;
trn_rsrc_dsc_d1_n <= trn_rsrc_dsc_n ;
trn_rerrfwd_d1_n <= trn_rerrfwd_n ;
trn_rbar_hit_d1_n[6:0] <= trn_rbar_hit_n[6:0] ;
trn_rfc_npd_av_d1[11:0] <= trn_rfc_npd_av[11:0] ;
trn_rfc_nph_av_d1[7:0] <= trn_rfc_nph_av[7:0] ;
trn_rfc_pd_av_d1[11:0] <= trn_rfc_pd_av[11:0] ;
trn_rfc_ph_av_d1[7:0] <= trn_rfc_ph_av[7:0] ;
trn_rfc_cpld_av_d1[11:0] <= trn_rfc_cpld_av[11:0];
trn_rfc_cplh_av_d1[7:0] <= trn_rfc_cplh_av[7:0] ;
trn_rd_d2[63:0] <= trn_rd_d1[63:0] ;
trn_rrem_d2_n[7:0] <= trn_rrem_d1_n[7:0] ;
trn_rsof_d2_n <= trn_rsof_d1_n ;
trn_reof_d2_n <= trn_reof_d1_n ;
trn_rsrc_rdy_d2_n <= trn_rsrc_rdy_d1_n ;
trn_rsrc_dsc_d2_n <= trn_rsrc_dsc_d1_n ;
trn_rerrfwd_d2_n <= trn_rerrfwd_d1_n ;
trn_rbar_hit_d2_n[6:0] <= trn_rbar_hit_d1_n[6:0] ;
trn_rfc_npd_av_d2[11:0] <= trn_rfc_npd_av_d1[11:0] ;
trn_rfc_nph_av_d2[7:0] <= trn_rfc_nph_av_d1[7:0] ;
trn_rfc_pd_av_d2[11:0] <= trn_rfc_pd_av_d1[11:0] ;
trn_rfc_ph_av_d2[7:0] <= trn_rfc_ph_av_d1[7:0] ;
trn_rfc_cpld_av_d2[11:0] <= trn_rfc_cpld_av_d1[11:0];
trn_rfc_cplh_av_d2[7:0] <= trn_rfc_cplh_av_d1[7:0] ;
end
assign rx_sof_d1 = ~trn_rsof_d1_n & ~trn_rsrc_rdy_d1_n;
// Assign packet type information about the current RX Packet
// rx_packet_type is decoded in always block directly below these assigns
assign MRd = rx_packet_type[4];
assign MWr = rx_packet_type[3];
assign CplD = rx_packet_type[2];
assign Msg = rx_packet_type[1];
assign UR = rx_packet_type[0];
//register the packet header fields and decode the packet type
//both memory and completion TLP header fields are registered for each
//received packet, however, only the fields for the incoming type will be
//valid
always@(posedge clk )
begin
if(rst_reg)begin
rx_packet_type[4:0] <= 5'b00000;
fourdw_n_threedw <= 0;
payload <= 0;
tc[2:0] <= 0; //traffic class
td <= 0; //digest
ep <= 0; //poisoned bit
attr[1:0] <= 0;
dw_length[9:0] <= 0;
MEM_req_id[15:0] <= 0;
MEM_tag[7:0] <= 0;
CMP_comp_id[15:0] <= 0;
CMP_compl_stat[2:0] <= 0;
CMP_bcm <= 0;
CMP_byte_count[11:0] <= 0;
end else begin
if(rx_sof_d1)begin
//these fields same for all TLPs
fourdw_n_threedw <= trn_rd_d1[61];
payload <= trn_rd_d1[62];
tc[2:0] <= trn_rd_d1[54:52]; //traffic class
td <= trn_rd_d1[47]; //digest
ep <= trn_rd_d1[46]; //poisoned bit
attr[1:0] <= trn_rd_d1[45:44];
dw_length[9:0] <= trn_rd_d1[41:32];
//also latch bar_hit
bar_hit[6:0] <= ~trn_rbar_hit_d1_n[6:0];
//these following fields dependent on packet type
//i.e. memory packet fields are only valid for mem packet types
//and completer packet fields are only valid for completer packet type;
//memory packet fields
MEM_req_id[15:0] <= trn_rd_d1[31:16];
MEM_tag[7:0] <= trn_rd_d1[15:8];
//first and last byte enables not needed because plus core delivers
//completer packet fields
CMP_comp_id[15:0] <= trn_rd_d1[31:16];
CMP_compl_stat[2:0] <= trn_rd_d1[15:13];
CMP_bcm <= trn_rd_d1[12];
CMP_byte_count[11:0] <= trn_rd_d1[11:0];
//add message fields here if needed
//decode the packet type and register in rx_packet_type
casex({trn_rd_d1[62],trn_rd_d1[60:56]})
6'b000000: begin //mem read
rx_packet_type[4:0] <= 5'b10000;
end
6'b100000: begin //mem write
rx_packet_type[4:0] <= 5'b01000;
end
6'b101010: begin //completer with data
rx_packet_type[4:0] <= 5'b00100;
end
6'bx10xxx: begin //message
rx_packet_type[4:0] <= 5'b00010;
end
default: begin //all other packet types are unsupported for this design
rx_packet_type[4:0] <= 5'b00001;
end
endcase
end
end
end
// Now do the same for the second header of the current packet
always@(posedge clk )begin
if(rst_reg)begin
MEM_addr[63:0] <= 0;
CMP_req_id[15:0] <= 0;
CMP_tag[7:0] <= 0;
CMP_lower_addr[6:0] <= 0;
end else begin
if(trn_state == SOF & ~trn_rsrc_rdy_d1_n)begin //packet is in process of
//reading out second header
if(fourdw_n_threedw)
MEM_addr[63:0] <= trn_rd_d1[63:0];
else
MEM_addr[63:0] <= {32'h00000000,trn_rd_d1[63:32]};
CMP_req_id[15:0] <= trn_rd_d1[63:48];
CMP_tag[7:0] <= trn_rd_d1[47:40];
CMP_lower_addr[6:0] <= trn_rd_d1[48:32];
end
end
end
// generate a valid signal for the headers field
always@(posedge clk)begin
if(rst_reg)
header_fields_valid <= 0;
else
header_fields_valid <= ~trn_rsrc_rdy_d2_n & trn_rsof_d1_n;
end
//This state machine keeps track of what state the RX TRN interface
//is currently in
always @ (posedge clk )
begin
if(rst_reg)
begin
trn_state <= IDLE;
trn_rdst_rdy_n <= 1'b0;
end
else
begin
case(trn_state)
IDLE: begin
trn_rdst_rdy_n <= 1'b0;
if(rx_sof_d1)
trn_state <= SOF;
else
trn_state <= IDLE;
end
/// Jiansong: notice, completion streaming here
NOT_READY: begin // This state is a placeholder only - it is currently not
// entered from any other state
// This state could be used for throttling the PCIe
// Endpoint Block Plus RX TRN interface, however, this
// should not be done when using completion streaming
// mode as this reference design does
trn_rdst_rdy_n <= 1'b1;
trn_state <= IDLE;
end
SOF: begin
if(~trn_reof_d1_n & ~trn_rsrc_rdy_d1_n)
trn_state <= EOF;
else if(trn_reof_d1_n & ~trn_rsrc_rdy_d1_n)
trn_state <= HEAD2;
else
trn_state <= SOF;
end
HEAD2: begin
if(~trn_reof_d1_n & ~trn_rsrc_rdy_d1_n)
trn_state <= EOF;
else if(trn_reof_d1_n & ~trn_rsrc_rdy_d1_n)
trn_state <= BODY;
else
trn_state <= HEAD2;
end
BODY: begin
if(~trn_reof_d1_n & ~trn_rsrc_rdy_d1_n)
trn_state <= EOF;
else
trn_state <= BODY;
end
EOF: begin
if(~trn_rsof_d1_n & ~trn_rsrc_rdy_d1_n)
trn_state <= SOF;
else if(trn_rsof_d1_n & trn_rsrc_rdy_d1_n)
trn_state <= IDLE;
else if(~trn_reof_d1_n & ~trn_rsrc_rdy_d1_n)
trn_state <= EOF;
else
trn_state <= IDLE;
end
default: begin
trn_state <= IDLE;
end
endcase
end
end
//data shifter logic
//need to shift the data depending if we receive a four DWORD or three DWORD
//TLP type - Note that completion packets will always be 3DW TLPs
assign data_out_mux[63:0] = (fourdw_n_threedw)
? trn_rd_d2[63:0]
: {trn_rd_d2[31:0],trn_rd_d1[63:32]};
/// Jiansong: notice, why? 64bit data? likely should be modified
//swap the byte ordering to little endian
//e.g. data_out = B7,B6,B5,B4,B3,B2,B1,B0
always@(posedge clk)
data_out[63:0] <= {data_out_mux[7:0],data_out_mux[15:8],
data_out_mux[23:16],data_out_mux[31:24],
data_out_mux[39:32],data_out_mux[47:40],
data_out_mux[55:48],data_out_mux[63:56]};
//Data byte enable logic:
//Need to add byte enable logic for incoming memory transactions if desired
//to allow memory transaction granularity smaller than DWORD.
//
//This design always requests data on 128 byte boundaries so for
//completion TLPs the byte enables would always be asserted
//
//Note that the endpoint block plus uses negative logic, however,
//I decided to use positive logic for the user application.
assign data_out_be = 8'hff;
//data_valid generation logic
//Generally, data_valid should be asserted the same amount of cycles
//that trn_rsrc_rdy_n is asserted (minus the cycles that sof and
//eof are asserted).
//There are two exceptions to this:
// - 3DW TLPs with odd number of DW without Digest
// In this case an extra cycle is required
// - eof is used to generate this extra cycle
// - 4DW TLPs with even number of DW with Digest
// In this case an extra cycle needs to be removed
// - the last cycle is removed
// Jiansong: fix Mrd data to fifo bug
always@(*)begin
case({fourdw_n_threedw, dw_length[0], td})
3'b010: data_valid_early = ~trn_rsrc_rdy_d2_n
& trn_rsof_d2_n
& ~trn_reof_d2_n
& payload;
3'b101: data_valid_early = ~trn_rsrc_rdy_d2_n
& trn_reof_d1_n
& payload;
default: data_valid_early = ~trn_rsrc_rdy_d2_n
& trn_rsof_d2_n
& trn_reof_d2_n
& payload;
endcase
end
//delay by one clock to match data_out (and presumably data_out_be)
always@(posedge clk)
if(rst_reg)
data_valid <= 1'b0;
else
data_valid <= data_valid_early;
endmodule
|
/*+--------------------------------------------------------------------------
Copyright (c) 2015, Microsoft Corporation
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------*/
//////////////////////////////////////////////////////////////////////////////////
// Company: Microsoft Research Asia
// Engineer: Jiansong Zhang
//
// Create Date: 21:39:39 06/01/2009
// Design Name:
// Module Name: rx_trn_data_fsm
// Project Name: Sora
// Target Devices: Virtex5 LX50T
// Tool versions: ISE10.1.03
// Description:
// Purpose: Receive TRN Data FSM. This module interfaces to the Block Plus RX
// TRN. It presents the 64-bit data from completer and and forwards that
// data with a data_valid signal. This block also decodes packet header info
// and forwards it to the rx_trn_monitor block.
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
`timescale 1ns / 1ps
module rx_trn_data_fsm(
input wire clk,
input wire rst,
// Rx Local-Link
input wire [63:0] trn_rd,
input wire [7:0] trn_rrem_n,
input wire trn_rsof_n,
input wire trn_reof_n,
input wire trn_rsrc_rdy_n,
input wire trn_rsrc_dsc_n,
output reg trn_rdst_rdy_n,
input wire trn_rerrfwd_n,
output wire trn_rnp_ok_n,
input wire [6:0] trn_rbar_hit_n,
input wire [11:0] trn_rfc_npd_av,
input wire [7:0] trn_rfc_nph_av,
input wire [11:0] trn_rfc_pd_av,
input wire [7:0] trn_rfc_ph_av,
input wire [11:0] trn_rfc_cpld_av,
input wire [7:0] trn_rfc_cplh_av,
output wire trn_rcpl_streaming_n,
//DATA FIFO SIGNALS
output reg [63:0] data_out,
output wire [7:0] data_out_be,
output reg data_valid,
input wire data_fifo_status,
//END DATA FIFO SIGNALS
//HEADER FIELD SIGNALS
//The following are registered from the header fields of the current packet
//See the PCIe Base Specification for definitions of these headers
output reg fourdw_n_threedw, //fourdw = 1'b1; 3dw = 1'b0;
output reg payload,
output reg [2:0] tc, //traffic class
output reg td, //digest
output reg ep, //poisoned bit
output reg [1:0] attr, //attribute field
output reg [9:0] dw_length, //DWORD Length
//the following fields are dependent on the type of TLP being received
//regs with MEM prefix are valid for memory TLPS and regs with CMP prefix
//are valid for completion TLPS
output reg [15:0] MEM_req_id, //requester ID for memory TLPs
output reg [7:0] MEM_tag, //tag for non-posted memory read request
output reg [15:0] CMP_comp_id, //completer id for completion TLPs
output reg [2:0]CMP_compl_stat, //status for completion TLPs
output reg CMP_bcm, //byte count modified field for completions TLPs
output reg [11:0] CMP_byte_count, //remaining byte count for completion TLPs
output reg [63:0] MEM_addr, //address field for memory TLPs
output reg [15:0] CMP_req_id, //requester if for completions TLPs
output reg [7:0] CMP_tag, //tag field for completion TLPs
output reg [6:0] CMP_lower_addr, //lower address field for completion TLPs
//decode of the format field
output wire MRd, //Mem read
output wire MWr, //Mem write
output wire CplD, //Completion w/ data
output wire Msg, //Message TLP
output wire UR, //Unsupported request TLP i.e. IO, CPL,etc..
output reg [6:0] bar_hit, //valid when a BAR is hit
output reg header_fields_valid//valid signal to qualify the above header fields
//END HEADER FIELD SIGNALS
);
//state machine states
localparam IDLE = 3'b000;
localparam NOT_READY = 3'b001;
localparam SOF = 3'b010;
localparam HEAD2 = 3'b011;
localparam BODY = 3'b100;
localparam EOF = 3'b101;
//additional pipelines regs for RX TRN interface
reg [63:0] trn_rd_d1;
reg [7:0] trn_rrem_d1_n;
reg trn_rsof_d1_n;
reg trn_reof_d1_n;
reg trn_rsrc_rdy_d1_n;
reg trn_rsrc_dsc_d1_n;
reg trn_rerrfwd_d1_n;
reg [6:0] trn_rbar_hit_d1_n;
reg [11:0] trn_rfc_npd_av_d1;
reg [7:0] trn_rfc_nph_av_d1;
reg [11:0] trn_rfc_pd_av_d1;
reg [7:0] trn_rfc_ph_av_d1;
reg [11:0] trn_rfc_cpld_av_d1;
reg [7:0] trn_rfc_cplh_av_d1;
//second pipeline
reg [63:0] trn_rd_d2;
reg [7:0] trn_rrem_d2_n;
reg trn_rsof_d2_n;
reg trn_reof_d2_n;
reg trn_rsrc_rdy_d2_n;
reg trn_rsrc_dsc_d2_n;
reg trn_rerrfwd_d2_n;
reg [6:0] trn_rbar_hit_d2_n;
reg [11:0] trn_rfc_npd_av_d2;
reg [7:0] trn_rfc_nph_av_d2;
reg [11:0] trn_rfc_pd_av_d2;
reg [7:0] trn_rfc_ph_av_d2;
reg [11:0] trn_rfc_cpld_av_d2;
reg [7:0] trn_rfc_cplh_av_d2;
reg [4:0] rx_packet_type;
reg [2:0] trn_state;
wire [63:0] data_out_mux;
wire [7:0] data_out_be_mux;
reg data_valid_early;
reg rst_reg;
always@(posedge clk) rst_reg <= rst;
// TIE constant signals here
assign trn_rnp_ok_n = 1'b0;
assign trn_rcpl_streaming_n = 1'b0; //use completion streaming mode
//all the outputs of the endpoint should be pipelined
//to help meet required timing of an 8 lane design
always @ (posedge clk)
begin
trn_rd_d1[63:0] <= trn_rd[63:0] ;
trn_rrem_d1_n[7:0] <= trn_rrem_n[7:0] ;
trn_rsof_d1_n <= trn_rsof_n ;
trn_reof_d1_n <= trn_reof_n ;
trn_rsrc_rdy_d1_n <= trn_rsrc_rdy_n ;
trn_rsrc_dsc_d1_n <= trn_rsrc_dsc_n ;
trn_rerrfwd_d1_n <= trn_rerrfwd_n ;
trn_rbar_hit_d1_n[6:0] <= trn_rbar_hit_n[6:0] ;
trn_rfc_npd_av_d1[11:0] <= trn_rfc_npd_av[11:0] ;
trn_rfc_nph_av_d1[7:0] <= trn_rfc_nph_av[7:0] ;
trn_rfc_pd_av_d1[11:0] <= trn_rfc_pd_av[11:0] ;
trn_rfc_ph_av_d1[7:0] <= trn_rfc_ph_av[7:0] ;
trn_rfc_cpld_av_d1[11:0] <= trn_rfc_cpld_av[11:0];
trn_rfc_cplh_av_d1[7:0] <= trn_rfc_cplh_av[7:0] ;
trn_rd_d2[63:0] <= trn_rd_d1[63:0] ;
trn_rrem_d2_n[7:0] <= trn_rrem_d1_n[7:0] ;
trn_rsof_d2_n <= trn_rsof_d1_n ;
trn_reof_d2_n <= trn_reof_d1_n ;
trn_rsrc_rdy_d2_n <= trn_rsrc_rdy_d1_n ;
trn_rsrc_dsc_d2_n <= trn_rsrc_dsc_d1_n ;
trn_rerrfwd_d2_n <= trn_rerrfwd_d1_n ;
trn_rbar_hit_d2_n[6:0] <= trn_rbar_hit_d1_n[6:0] ;
trn_rfc_npd_av_d2[11:0] <= trn_rfc_npd_av_d1[11:0] ;
trn_rfc_nph_av_d2[7:0] <= trn_rfc_nph_av_d1[7:0] ;
trn_rfc_pd_av_d2[11:0] <= trn_rfc_pd_av_d1[11:0] ;
trn_rfc_ph_av_d2[7:0] <= trn_rfc_ph_av_d1[7:0] ;
trn_rfc_cpld_av_d2[11:0] <= trn_rfc_cpld_av_d1[11:0];
trn_rfc_cplh_av_d2[7:0] <= trn_rfc_cplh_av_d1[7:0] ;
end
assign rx_sof_d1 = ~trn_rsof_d1_n & ~trn_rsrc_rdy_d1_n;
// Assign packet type information about the current RX Packet
// rx_packet_type is decoded in always block directly below these assigns
assign MRd = rx_packet_type[4];
assign MWr = rx_packet_type[3];
assign CplD = rx_packet_type[2];
assign Msg = rx_packet_type[1];
assign UR = rx_packet_type[0];
//register the packet header fields and decode the packet type
//both memory and completion TLP header fields are registered for each
//received packet, however, only the fields for the incoming type will be
//valid
always@(posedge clk )
begin
if(rst_reg)begin
rx_packet_type[4:0] <= 5'b00000;
fourdw_n_threedw <= 0;
payload <= 0;
tc[2:0] <= 0; //traffic class
td <= 0; //digest
ep <= 0; //poisoned bit
attr[1:0] <= 0;
dw_length[9:0] <= 0;
MEM_req_id[15:0] <= 0;
MEM_tag[7:0] <= 0;
CMP_comp_id[15:0] <= 0;
CMP_compl_stat[2:0] <= 0;
CMP_bcm <= 0;
CMP_byte_count[11:0] <= 0;
end else begin
if(rx_sof_d1)begin
//these fields same for all TLPs
fourdw_n_threedw <= trn_rd_d1[61];
payload <= trn_rd_d1[62];
tc[2:0] <= trn_rd_d1[54:52]; //traffic class
td <= trn_rd_d1[47]; //digest
ep <= trn_rd_d1[46]; //poisoned bit
attr[1:0] <= trn_rd_d1[45:44];
dw_length[9:0] <= trn_rd_d1[41:32];
//also latch bar_hit
bar_hit[6:0] <= ~trn_rbar_hit_d1_n[6:0];
//these following fields dependent on packet type
//i.e. memory packet fields are only valid for mem packet types
//and completer packet fields are only valid for completer packet type;
//memory packet fields
MEM_req_id[15:0] <= trn_rd_d1[31:16];
MEM_tag[7:0] <= trn_rd_d1[15:8];
//first and last byte enables not needed because plus core delivers
//completer packet fields
CMP_comp_id[15:0] <= trn_rd_d1[31:16];
CMP_compl_stat[2:0] <= trn_rd_d1[15:13];
CMP_bcm <= trn_rd_d1[12];
CMP_byte_count[11:0] <= trn_rd_d1[11:0];
//add message fields here if needed
//decode the packet type and register in rx_packet_type
casex({trn_rd_d1[62],trn_rd_d1[60:56]})
6'b000000: begin //mem read
rx_packet_type[4:0] <= 5'b10000;
end
6'b100000: begin //mem write
rx_packet_type[4:0] <= 5'b01000;
end
6'b101010: begin //completer with data
rx_packet_type[4:0] <= 5'b00100;
end
6'bx10xxx: begin //message
rx_packet_type[4:0] <= 5'b00010;
end
default: begin //all other packet types are unsupported for this design
rx_packet_type[4:0] <= 5'b00001;
end
endcase
end
end
end
// Now do the same for the second header of the current packet
always@(posedge clk )begin
if(rst_reg)begin
MEM_addr[63:0] <= 0;
CMP_req_id[15:0] <= 0;
CMP_tag[7:0] <= 0;
CMP_lower_addr[6:0] <= 0;
end else begin
if(trn_state == SOF & ~trn_rsrc_rdy_d1_n)begin //packet is in process of
//reading out second header
if(fourdw_n_threedw)
MEM_addr[63:0] <= trn_rd_d1[63:0];
else
MEM_addr[63:0] <= {32'h00000000,trn_rd_d1[63:32]};
CMP_req_id[15:0] <= trn_rd_d1[63:48];
CMP_tag[7:0] <= trn_rd_d1[47:40];
CMP_lower_addr[6:0] <= trn_rd_d1[48:32];
end
end
end
// generate a valid signal for the headers field
always@(posedge clk)begin
if(rst_reg)
header_fields_valid <= 0;
else
header_fields_valid <= ~trn_rsrc_rdy_d2_n & trn_rsof_d1_n;
end
//This state machine keeps track of what state the RX TRN interface
//is currently in
always @ (posedge clk )
begin
if(rst_reg)
begin
trn_state <= IDLE;
trn_rdst_rdy_n <= 1'b0;
end
else
begin
case(trn_state)
IDLE: begin
trn_rdst_rdy_n <= 1'b0;
if(rx_sof_d1)
trn_state <= SOF;
else
trn_state <= IDLE;
end
/// Jiansong: notice, completion streaming here
NOT_READY: begin // This state is a placeholder only - it is currently not
// entered from any other state
// This state could be used for throttling the PCIe
// Endpoint Block Plus RX TRN interface, however, this
// should not be done when using completion streaming
// mode as this reference design does
trn_rdst_rdy_n <= 1'b1;
trn_state <= IDLE;
end
SOF: begin
if(~trn_reof_d1_n & ~trn_rsrc_rdy_d1_n)
trn_state <= EOF;
else if(trn_reof_d1_n & ~trn_rsrc_rdy_d1_n)
trn_state <= HEAD2;
else
trn_state <= SOF;
end
HEAD2: begin
if(~trn_reof_d1_n & ~trn_rsrc_rdy_d1_n)
trn_state <= EOF;
else if(trn_reof_d1_n & ~trn_rsrc_rdy_d1_n)
trn_state <= BODY;
else
trn_state <= HEAD2;
end
BODY: begin
if(~trn_reof_d1_n & ~trn_rsrc_rdy_d1_n)
trn_state <= EOF;
else
trn_state <= BODY;
end
EOF: begin
if(~trn_rsof_d1_n & ~trn_rsrc_rdy_d1_n)
trn_state <= SOF;
else if(trn_rsof_d1_n & trn_rsrc_rdy_d1_n)
trn_state <= IDLE;
else if(~trn_reof_d1_n & ~trn_rsrc_rdy_d1_n)
trn_state <= EOF;
else
trn_state <= IDLE;
end
default: begin
trn_state <= IDLE;
end
endcase
end
end
//data shifter logic
//need to shift the data depending if we receive a four DWORD or three DWORD
//TLP type - Note that completion packets will always be 3DW TLPs
assign data_out_mux[63:0] = (fourdw_n_threedw)
? trn_rd_d2[63:0]
: {trn_rd_d2[31:0],trn_rd_d1[63:32]};
/// Jiansong: notice, why? 64bit data? likely should be modified
//swap the byte ordering to little endian
//e.g. data_out = B7,B6,B5,B4,B3,B2,B1,B0
always@(posedge clk)
data_out[63:0] <= {data_out_mux[7:0],data_out_mux[15:8],
data_out_mux[23:16],data_out_mux[31:24],
data_out_mux[39:32],data_out_mux[47:40],
data_out_mux[55:48],data_out_mux[63:56]};
//Data byte enable logic:
//Need to add byte enable logic for incoming memory transactions if desired
//to allow memory transaction granularity smaller than DWORD.
//
//This design always requests data on 128 byte boundaries so for
//completion TLPs the byte enables would always be asserted
//
//Note that the endpoint block plus uses negative logic, however,
//I decided to use positive logic for the user application.
assign data_out_be = 8'hff;
//data_valid generation logic
//Generally, data_valid should be asserted the same amount of cycles
//that trn_rsrc_rdy_n is asserted (minus the cycles that sof and
//eof are asserted).
//There are two exceptions to this:
// - 3DW TLPs with odd number of DW without Digest
// In this case an extra cycle is required
// - eof is used to generate this extra cycle
// - 4DW TLPs with even number of DW with Digest
// In this case an extra cycle needs to be removed
// - the last cycle is removed
// Jiansong: fix Mrd data to fifo bug
always@(*)begin
case({fourdw_n_threedw, dw_length[0], td})
3'b010: data_valid_early = ~trn_rsrc_rdy_d2_n
& trn_rsof_d2_n
& ~trn_reof_d2_n
& payload;
3'b101: data_valid_early = ~trn_rsrc_rdy_d2_n
& trn_reof_d1_n
& payload;
default: data_valid_early = ~trn_rsrc_rdy_d2_n
& trn_rsof_d2_n
& trn_reof_d2_n
& payload;
endcase
end
//delay by one clock to match data_out (and presumably data_out_be)
always@(posedge clk)
if(rst_reg)
data_valid <= 1'b0;
else
data_valid <= data_valid_early;
endmodule
|
/*+--------------------------------------------------------------------------
Copyright (c) 2015, Microsoft Corporation
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------*/
//////////////////////////////////////////////////////////////////////////////////
// Company: Microsoft Research Asia
// Engineer: Jiansong Zhang
//
// Create Date: 21:39:39 06/01/2009
// Design Name:
// Module Name: rx_trn_data_fsm
// Project Name: Sora
// Target Devices: Virtex5 LX50T
// Tool versions: ISE10.1.03
// Description:
// Purpose: Receive TRN Data FSM. This module interfaces to the Block Plus RX
// TRN. It presents the 64-bit data from completer and and forwards that
// data with a data_valid signal. This block also decodes packet header info
// and forwards it to the rx_trn_monitor block.
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
`timescale 1ns / 1ps
module rx_trn_data_fsm(
input wire clk,
input wire rst,
// Rx Local-Link
input wire [63:0] trn_rd,
input wire [7:0] trn_rrem_n,
input wire trn_rsof_n,
input wire trn_reof_n,
input wire trn_rsrc_rdy_n,
input wire trn_rsrc_dsc_n,
output reg trn_rdst_rdy_n,
input wire trn_rerrfwd_n,
output wire trn_rnp_ok_n,
input wire [6:0] trn_rbar_hit_n,
input wire [11:0] trn_rfc_npd_av,
input wire [7:0] trn_rfc_nph_av,
input wire [11:0] trn_rfc_pd_av,
input wire [7:0] trn_rfc_ph_av,
input wire [11:0] trn_rfc_cpld_av,
input wire [7:0] trn_rfc_cplh_av,
output wire trn_rcpl_streaming_n,
//DATA FIFO SIGNALS
output reg [63:0] data_out,
output wire [7:0] data_out_be,
output reg data_valid,
input wire data_fifo_status,
//END DATA FIFO SIGNALS
//HEADER FIELD SIGNALS
//The following are registered from the header fields of the current packet
//See the PCIe Base Specification for definitions of these headers
output reg fourdw_n_threedw, //fourdw = 1'b1; 3dw = 1'b0;
output reg payload,
output reg [2:0] tc, //traffic class
output reg td, //digest
output reg ep, //poisoned bit
output reg [1:0] attr, //attribute field
output reg [9:0] dw_length, //DWORD Length
//the following fields are dependent on the type of TLP being received
//regs with MEM prefix are valid for memory TLPS and regs with CMP prefix
//are valid for completion TLPS
output reg [15:0] MEM_req_id, //requester ID for memory TLPs
output reg [7:0] MEM_tag, //tag for non-posted memory read request
output reg [15:0] CMP_comp_id, //completer id for completion TLPs
output reg [2:0]CMP_compl_stat, //status for completion TLPs
output reg CMP_bcm, //byte count modified field for completions TLPs
output reg [11:0] CMP_byte_count, //remaining byte count for completion TLPs
output reg [63:0] MEM_addr, //address field for memory TLPs
output reg [15:0] CMP_req_id, //requester if for completions TLPs
output reg [7:0] CMP_tag, //tag field for completion TLPs
output reg [6:0] CMP_lower_addr, //lower address field for completion TLPs
//decode of the format field
output wire MRd, //Mem read
output wire MWr, //Mem write
output wire CplD, //Completion w/ data
output wire Msg, //Message TLP
output wire UR, //Unsupported request TLP i.e. IO, CPL,etc..
output reg [6:0] bar_hit, //valid when a BAR is hit
output reg header_fields_valid//valid signal to qualify the above header fields
//END HEADER FIELD SIGNALS
);
//state machine states
localparam IDLE = 3'b000;
localparam NOT_READY = 3'b001;
localparam SOF = 3'b010;
localparam HEAD2 = 3'b011;
localparam BODY = 3'b100;
localparam EOF = 3'b101;
//additional pipelines regs for RX TRN interface
reg [63:0] trn_rd_d1;
reg [7:0] trn_rrem_d1_n;
reg trn_rsof_d1_n;
reg trn_reof_d1_n;
reg trn_rsrc_rdy_d1_n;
reg trn_rsrc_dsc_d1_n;
reg trn_rerrfwd_d1_n;
reg [6:0] trn_rbar_hit_d1_n;
reg [11:0] trn_rfc_npd_av_d1;
reg [7:0] trn_rfc_nph_av_d1;
reg [11:0] trn_rfc_pd_av_d1;
reg [7:0] trn_rfc_ph_av_d1;
reg [11:0] trn_rfc_cpld_av_d1;
reg [7:0] trn_rfc_cplh_av_d1;
//second pipeline
reg [63:0] trn_rd_d2;
reg [7:0] trn_rrem_d2_n;
reg trn_rsof_d2_n;
reg trn_reof_d2_n;
reg trn_rsrc_rdy_d2_n;
reg trn_rsrc_dsc_d2_n;
reg trn_rerrfwd_d2_n;
reg [6:0] trn_rbar_hit_d2_n;
reg [11:0] trn_rfc_npd_av_d2;
reg [7:0] trn_rfc_nph_av_d2;
reg [11:0] trn_rfc_pd_av_d2;
reg [7:0] trn_rfc_ph_av_d2;
reg [11:0] trn_rfc_cpld_av_d2;
reg [7:0] trn_rfc_cplh_av_d2;
reg [4:0] rx_packet_type;
reg [2:0] trn_state;
wire [63:0] data_out_mux;
wire [7:0] data_out_be_mux;
reg data_valid_early;
reg rst_reg;
always@(posedge clk) rst_reg <= rst;
// TIE constant signals here
assign trn_rnp_ok_n = 1'b0;
assign trn_rcpl_streaming_n = 1'b0; //use completion streaming mode
//all the outputs of the endpoint should be pipelined
//to help meet required timing of an 8 lane design
always @ (posedge clk)
begin
trn_rd_d1[63:0] <= trn_rd[63:0] ;
trn_rrem_d1_n[7:0] <= trn_rrem_n[7:0] ;
trn_rsof_d1_n <= trn_rsof_n ;
trn_reof_d1_n <= trn_reof_n ;
trn_rsrc_rdy_d1_n <= trn_rsrc_rdy_n ;
trn_rsrc_dsc_d1_n <= trn_rsrc_dsc_n ;
trn_rerrfwd_d1_n <= trn_rerrfwd_n ;
trn_rbar_hit_d1_n[6:0] <= trn_rbar_hit_n[6:0] ;
trn_rfc_npd_av_d1[11:0] <= trn_rfc_npd_av[11:0] ;
trn_rfc_nph_av_d1[7:0] <= trn_rfc_nph_av[7:0] ;
trn_rfc_pd_av_d1[11:0] <= trn_rfc_pd_av[11:0] ;
trn_rfc_ph_av_d1[7:0] <= trn_rfc_ph_av[7:0] ;
trn_rfc_cpld_av_d1[11:0] <= trn_rfc_cpld_av[11:0];
trn_rfc_cplh_av_d1[7:0] <= trn_rfc_cplh_av[7:0] ;
trn_rd_d2[63:0] <= trn_rd_d1[63:0] ;
trn_rrem_d2_n[7:0] <= trn_rrem_d1_n[7:0] ;
trn_rsof_d2_n <= trn_rsof_d1_n ;
trn_reof_d2_n <= trn_reof_d1_n ;
trn_rsrc_rdy_d2_n <= trn_rsrc_rdy_d1_n ;
trn_rsrc_dsc_d2_n <= trn_rsrc_dsc_d1_n ;
trn_rerrfwd_d2_n <= trn_rerrfwd_d1_n ;
trn_rbar_hit_d2_n[6:0] <= trn_rbar_hit_d1_n[6:0] ;
trn_rfc_npd_av_d2[11:0] <= trn_rfc_npd_av_d1[11:0] ;
trn_rfc_nph_av_d2[7:0] <= trn_rfc_nph_av_d1[7:0] ;
trn_rfc_pd_av_d2[11:0] <= trn_rfc_pd_av_d1[11:0] ;
trn_rfc_ph_av_d2[7:0] <= trn_rfc_ph_av_d1[7:0] ;
trn_rfc_cpld_av_d2[11:0] <= trn_rfc_cpld_av_d1[11:0];
trn_rfc_cplh_av_d2[7:0] <= trn_rfc_cplh_av_d1[7:0] ;
end
assign rx_sof_d1 = ~trn_rsof_d1_n & ~trn_rsrc_rdy_d1_n;
// Assign packet type information about the current RX Packet
// rx_packet_type is decoded in always block directly below these assigns
assign MRd = rx_packet_type[4];
assign MWr = rx_packet_type[3];
assign CplD = rx_packet_type[2];
assign Msg = rx_packet_type[1];
assign UR = rx_packet_type[0];
//register the packet header fields and decode the packet type
//both memory and completion TLP header fields are registered for each
//received packet, however, only the fields for the incoming type will be
//valid
always@(posedge clk )
begin
if(rst_reg)begin
rx_packet_type[4:0] <= 5'b00000;
fourdw_n_threedw <= 0;
payload <= 0;
tc[2:0] <= 0; //traffic class
td <= 0; //digest
ep <= 0; //poisoned bit
attr[1:0] <= 0;
dw_length[9:0] <= 0;
MEM_req_id[15:0] <= 0;
MEM_tag[7:0] <= 0;
CMP_comp_id[15:0] <= 0;
CMP_compl_stat[2:0] <= 0;
CMP_bcm <= 0;
CMP_byte_count[11:0] <= 0;
end else begin
if(rx_sof_d1)begin
//these fields same for all TLPs
fourdw_n_threedw <= trn_rd_d1[61];
payload <= trn_rd_d1[62];
tc[2:0] <= trn_rd_d1[54:52]; //traffic class
td <= trn_rd_d1[47]; //digest
ep <= trn_rd_d1[46]; //poisoned bit
attr[1:0] <= trn_rd_d1[45:44];
dw_length[9:0] <= trn_rd_d1[41:32];
//also latch bar_hit
bar_hit[6:0] <= ~trn_rbar_hit_d1_n[6:0];
//these following fields dependent on packet type
//i.e. memory packet fields are only valid for mem packet types
//and completer packet fields are only valid for completer packet type;
//memory packet fields
MEM_req_id[15:0] <= trn_rd_d1[31:16];
MEM_tag[7:0] <= trn_rd_d1[15:8];
//first and last byte enables not needed because plus core delivers
//completer packet fields
CMP_comp_id[15:0] <= trn_rd_d1[31:16];
CMP_compl_stat[2:0] <= trn_rd_d1[15:13];
CMP_bcm <= trn_rd_d1[12];
CMP_byte_count[11:0] <= trn_rd_d1[11:0];
//add message fields here if needed
//decode the packet type and register in rx_packet_type
casex({trn_rd_d1[62],trn_rd_d1[60:56]})
6'b000000: begin //mem read
rx_packet_type[4:0] <= 5'b10000;
end
6'b100000: begin //mem write
rx_packet_type[4:0] <= 5'b01000;
end
6'b101010: begin //completer with data
rx_packet_type[4:0] <= 5'b00100;
end
6'bx10xxx: begin //message
rx_packet_type[4:0] <= 5'b00010;
end
default: begin //all other packet types are unsupported for this design
rx_packet_type[4:0] <= 5'b00001;
end
endcase
end
end
end
// Now do the same for the second header of the current packet
always@(posedge clk )begin
if(rst_reg)begin
MEM_addr[63:0] <= 0;
CMP_req_id[15:0] <= 0;
CMP_tag[7:0] <= 0;
CMP_lower_addr[6:0] <= 0;
end else begin
if(trn_state == SOF & ~trn_rsrc_rdy_d1_n)begin //packet is in process of
//reading out second header
if(fourdw_n_threedw)
MEM_addr[63:0] <= trn_rd_d1[63:0];
else
MEM_addr[63:0] <= {32'h00000000,trn_rd_d1[63:32]};
CMP_req_id[15:0] <= trn_rd_d1[63:48];
CMP_tag[7:0] <= trn_rd_d1[47:40];
CMP_lower_addr[6:0] <= trn_rd_d1[48:32];
end
end
end
// generate a valid signal for the headers field
always@(posedge clk)begin
if(rst_reg)
header_fields_valid <= 0;
else
header_fields_valid <= ~trn_rsrc_rdy_d2_n & trn_rsof_d1_n;
end
//This state machine keeps track of what state the RX TRN interface
//is currently in
always @ (posedge clk )
begin
if(rst_reg)
begin
trn_state <= IDLE;
trn_rdst_rdy_n <= 1'b0;
end
else
begin
case(trn_state)
IDLE: begin
trn_rdst_rdy_n <= 1'b0;
if(rx_sof_d1)
trn_state <= SOF;
else
trn_state <= IDLE;
end
/// Jiansong: notice, completion streaming here
NOT_READY: begin // This state is a placeholder only - it is currently not
// entered from any other state
// This state could be used for throttling the PCIe
// Endpoint Block Plus RX TRN interface, however, this
// should not be done when using completion streaming
// mode as this reference design does
trn_rdst_rdy_n <= 1'b1;
trn_state <= IDLE;
end
SOF: begin
if(~trn_reof_d1_n & ~trn_rsrc_rdy_d1_n)
trn_state <= EOF;
else if(trn_reof_d1_n & ~trn_rsrc_rdy_d1_n)
trn_state <= HEAD2;
else
trn_state <= SOF;
end
HEAD2: begin
if(~trn_reof_d1_n & ~trn_rsrc_rdy_d1_n)
trn_state <= EOF;
else if(trn_reof_d1_n & ~trn_rsrc_rdy_d1_n)
trn_state <= BODY;
else
trn_state <= HEAD2;
end
BODY: begin
if(~trn_reof_d1_n & ~trn_rsrc_rdy_d1_n)
trn_state <= EOF;
else
trn_state <= BODY;
end
EOF: begin
if(~trn_rsof_d1_n & ~trn_rsrc_rdy_d1_n)
trn_state <= SOF;
else if(trn_rsof_d1_n & trn_rsrc_rdy_d1_n)
trn_state <= IDLE;
else if(~trn_reof_d1_n & ~trn_rsrc_rdy_d1_n)
trn_state <= EOF;
else
trn_state <= IDLE;
end
default: begin
trn_state <= IDLE;
end
endcase
end
end
//data shifter logic
//need to shift the data depending if we receive a four DWORD or three DWORD
//TLP type - Note that completion packets will always be 3DW TLPs
assign data_out_mux[63:0] = (fourdw_n_threedw)
? trn_rd_d2[63:0]
: {trn_rd_d2[31:0],trn_rd_d1[63:32]};
/// Jiansong: notice, why? 64bit data? likely should be modified
//swap the byte ordering to little endian
//e.g. data_out = B7,B6,B5,B4,B3,B2,B1,B0
always@(posedge clk)
data_out[63:0] <= {data_out_mux[7:0],data_out_mux[15:8],
data_out_mux[23:16],data_out_mux[31:24],
data_out_mux[39:32],data_out_mux[47:40],
data_out_mux[55:48],data_out_mux[63:56]};
//Data byte enable logic:
//Need to add byte enable logic for incoming memory transactions if desired
//to allow memory transaction granularity smaller than DWORD.
//
//This design always requests data on 128 byte boundaries so for
//completion TLPs the byte enables would always be asserted
//
//Note that the endpoint block plus uses negative logic, however,
//I decided to use positive logic for the user application.
assign data_out_be = 8'hff;
//data_valid generation logic
//Generally, data_valid should be asserted the same amount of cycles
//that trn_rsrc_rdy_n is asserted (minus the cycles that sof and
//eof are asserted).
//There are two exceptions to this:
// - 3DW TLPs with odd number of DW without Digest
// In this case an extra cycle is required
// - eof is used to generate this extra cycle
// - 4DW TLPs with even number of DW with Digest
// In this case an extra cycle needs to be removed
// - the last cycle is removed
// Jiansong: fix Mrd data to fifo bug
always@(*)begin
case({fourdw_n_threedw, dw_length[0], td})
3'b010: data_valid_early = ~trn_rsrc_rdy_d2_n
& trn_rsof_d2_n
& ~trn_reof_d2_n
& payload;
3'b101: data_valid_early = ~trn_rsrc_rdy_d2_n
& trn_reof_d1_n
& payload;
default: data_valid_early = ~trn_rsrc_rdy_d2_n
& trn_rsof_d2_n
& trn_reof_d2_n
& payload;
endcase
end
//delay by one clock to match data_out (and presumably data_out_be)
always@(posedge clk)
if(rst_reg)
data_valid <= 1'b0;
else
data_valid <= data_valid_early;
endmodule
|
(** * Hoare2: Hoare Logic, Part II *)
Require Export Hoare.
(* ####################################################### *)
(** * Decorated Programs *)
(** The beauty of Hoare Logic is that it is _compositional_ --
the structure of proofs exactly follows the structure of programs.
This suggests that we can record the essential ideas of a proof
informally (leaving out some low-level calculational details) by
decorating programs with appropriate assertions around each
statement. Such a _decorated program_ carries with it
an (informal) proof of its own correctness. *)
(** For example, here is a complete decorated program: *)
(**
{{ True }} ->>
{{ m = m }}
X ::= m;;
{{ X = m }} ->>
{{ X = m /\ p = p }}
Z ::= p;
{{ X = m /\ Z = p }} ->>
{{ Z - X = p - m }}
WHILE X <> 0 DO
{{ Z - X = p - m /\ X <> 0 }} ->>
{{ (Z - 1) - (X - 1) = p - m }}
Z ::= Z - 1;;
{{ Z - (X - 1) = p - m }}
X ::= X - 1
{{ Z - X = p - m }}
END;
{{ Z - X = p - m /\ ~ (X <> 0) }} ->>
{{ Z = p - m }}
*)
(** Concretely, a decorated program consists of the program text
interleaved with assertions. To check that a decorated program
represents a valid proof, we check that each individual command is
_locally consistent_ with its accompanying assertions in the
following sense: *)
(**
- [SKIP] is locally consistent if its precondition and
postcondition are the same:
{{ P }}
SKIP
{{ P }}
*)
(**
- The sequential composition of [c1] and [c2] is locally
consistent (with respect to assertions [P] and [R]) if [c1] is
locally consistent (with respect to [P] and [Q]) and [c2] is
locally consistent (with respect to [Q] and [R]):
{{ P }}
c1;;
{{ Q }}
c2
{{ R }}
*)
(**
- An assignment is locally consistent if its precondition is
the appropriate substitution of its postcondition:
{{ P [X |-> a] }}
X ::= a
{{ P }}
*)
(**
- A conditional is locally consistent (with respect to assertions
[P] and [Q]) if the assertions at the top of its "then" and
"else" branches are exactly [P /\ b] and [P /\ ~b] and if its "then"
branch is locally consistent (with respect to [P /\ b] and [Q])
and its "else" branch is locally consistent (with respect to
[P /\ ~b] and [Q]):
{{ P }}
IFB b THEN
{{ P /\ b }}
c1
{{ Q }}
ELSE
{{ P /\ ~b }}
c2
{{ Q }}
FI
{{ Q }}
*)
(**
- A while loop with precondition [P] is locally consistent if its
postcondition is [P /\ ~b] and if the pre- and postconditions of
its body are exactly [P /\ b] and [P]:
{{ P }}
WHILE b DO
{{ P /\ b }}
c1
{{ P }}
END
{{ P /\ ~b }}
*)
(**
- A pair of assertions separated by [->>] is locally consistent if
the first implies the second (in all states):
{{ P }} ->>
{{ P' }}
This corresponds to the application of [hoare_consequence] and
is the only place in a decorated program where checking if
decorations are correct is not fully mechanical and syntactic,
but involves logical and/or arithmetic reasoning.
*)
(** We have seen above how _verifying_ the correctness of a
given proof involves checking that every single command is locally
consistent with the accompanying assertions. If we are instead
interested in _finding_ a proof for a given specification we need
to discover the right assertions. This can be done in an almost
automatic way, with the exception of finding loop invariants,
which is the subject of in the next section. In the reminder of
this section we explain in detail how to construct decorations for
several simple programs that don't involve non-trivial loop
invariants. *)
(* ####################################################### *)
(** ** Example: Swapping Using Addition and Subtraction *)
(** Here is a program that swaps the values of two variables using
addition and subtraction (instead of by assigning to a temporary
variable).
X ::= X + Y;;
Y ::= X - Y;;
X ::= X - Y
We can prove using decorations that this program is correct --
i.e., it always swaps the values of variables [X] and [Y]. *)
(**
(1) {{ X = m /\ Y = n }} ->>
(2) {{ (X + Y) - ((X + Y) - Y) = n /\ (X + Y) - Y = m }}
X ::= X + Y;;
(3) {{ X - (X - Y) = n /\ X - Y = m }}
Y ::= X - Y;;
(4) {{ X - Y = n /\ Y = m }}
X ::= X - Y
(5) {{ X = n /\ Y = m }}
The decorations were constructed as follows:
- We begin with the undecorated program (the unnumbered lines).
- We then add the specification -- i.e., the outer
precondition (1) and postcondition (5). In the precondition we
use auxiliary variables (parameters) [m] and [n] to remember
the initial values of variables [X] and respectively [Y], so
that we can refer to them in the postcondition (5).
- We work backwards mechanically starting from (5) all the way
to (2). At each step, we obtain the precondition of the
assignment from its postcondition by substituting the assigned
variable with the right-hand-side of the assignment. For
instance, we obtain (4) by substituting [X] with [X - Y]
in (5), and (3) by substituting [Y] with [X - Y] in (4).
- Finally, we verify that (1) logically implies (2) -- i.e.,
that the step from (1) to (2) is a valid use of the law of
consequence. For this we substitute [X] by [m] and [Y] by [n]
and calculate as follows:
(m + n) - ((m + n) - n) = n /\ (m + n) - n = m
(m + n) - m = n /\ m = m
n = n /\ m = m
(Note that, since we are working with natural numbers, not
fixed-size machine integers, we don't need to worry about the
possibility of arithmetic overflow anywhere in this argument.)
*)
(* ####################################################### *)
(** ** Example: Simple Conditionals *)
(** Here is a simple decorated program using conditionals:
(1) {{True}}
IFB X <= Y THEN
(2) {{True /\ X <= Y}} ->>
(3) {{(Y - X) + X = Y \/ (Y - X) + Y = X}}
Z ::= Y - X
(4) {{Z + X = Y \/ Z + Y = X}}
ELSE
(5) {{True /\ ~(X <= Y) }} ->>
(6) {{(X - Y) + X = Y \/ (X - Y) + Y = X}}
Z ::= X - Y
(7) {{Z + X = Y \/ Z + Y = X}}
FI
(8) {{Z + X = Y \/ Z + Y = X}}
These decorations were constructed as follows:
- We start with the outer precondition (1) and postcondition (8).
- We follow the format dictated by the [hoare_if] rule and copy the
postcondition (8) to (4) and (7). We conjoin the precondition (1)
with the guard of the conditional to obtain (2). We conjoin (1)
with the negated guard of the conditional to obtain (5).
- In order to use the assignment rule and obtain (3), we substitute
[Z] by [Y - X] in (4). To obtain (6) we substitute [Z] by [X - Y]
in (7).
- Finally, we verify that (2) implies (3) and (5) implies (6). Both
of these implications crucially depend on the ordering of [X] and
[Y] obtained from the guard. For instance, knowing that [X <= Y]
ensures that subtracting [X] from [Y] and then adding back [X]
produces [Y], as required by the first disjunct of (3). Similarly,
knowing that [~(X <= Y)] ensures that subtracting [Y] from [X] and
then adding back [Y] produces [X], as needed by the second
disjunct of (6). Note that [n - m + m = n] does _not_ hold for
arbitrary natural numbers [n] and [m] (for example, [3 - 5 + 5 =
5]). *)
(** **** Exercise: 2 stars (if_minus_plus_reloaded) *)
(** Fill in valid decorations for the following program:
{{ True }}
IFB X <= Y THEN
{{ }} ->>
{{ }}
Z ::= Y - X
{{ }}
ELSE
{{ }} ->>
{{ }}
Y ::= X + Z
{{ }}
FI
{{ Y = X + Z }}
*)
(** [] *)
(* ####################################################### *)
(** ** Example: Reduce to Zero (Trivial Loop) *)
(** Here is a [WHILE] loop that is so simple it needs no
invariant (i.e., the invariant [True] will do the job).
(1) {{ True }}
WHILE X <> 0 DO
(2) {{ True /\ X <> 0 }} ->>
(3) {{ True }}
X ::= X - 1
(4) {{ True }}
END
(5) {{ True /\ X = 0 }} ->>
(6) {{ X = 0 }}
The decorations can be constructed as follows:
- Start with the outer precondition (1) and postcondition (6).
- Following the format dictated by the [hoare_while] rule, we copy
(1) to (4). We conjoin (1) with the guard to obtain (2) and with
the negation of the guard to obtain (5). Note that, because the
outer postcondition (6) does not syntactically match (5), we need a
trivial use of the consequence rule from (5) to (6).
- Assertion (3) is the same as (4), because [X] does not appear in
[4], so the substitution in the assignment rule is trivial.
- Finally, the implication between (2) and (3) is also trivial.
*)
(** From this informal proof, it is easy to read off a formal proof
using the Coq versions of the Hoare rules. Note that we do _not_
unfold the definition of [hoare_triple] anywhere in this proof --
the idea is to use the Hoare rules as a "self-contained" logic for
reasoning about programs. *)
Definition reduce_to_zero' : com :=
WHILE BNot (BEq (AId X) (ANum 0)) DO
X ::= AMinus (AId X) (ANum 1)
END.
Theorem reduce_to_zero_correct' :
{{fun st => True}}
reduce_to_zero'
{{fun st => st X = 0}}.
Proof.
unfold reduce_to_zero'.
(* First we need to transform the postcondition so
that hoare_while will apply. *)
eapply hoare_consequence_post.
apply hoare_while.
Case "Loop body preserves invariant".
(* Need to massage precondition before [hoare_asgn] applies *)
eapply hoare_consequence_pre. apply hoare_asgn.
(* Proving trivial implication (2) ->> (3) *)
intros st [HT Hbp]. unfold assn_sub. apply I.
Case "Invariant and negated guard imply postcondition".
intros st [Inv GuardFalse].
unfold bassn in GuardFalse. simpl in GuardFalse.
(* SearchAbout helps to find the right lemmas *)
SearchAbout [not true].
rewrite not_true_iff_false in GuardFalse.
SearchAbout [negb false].
rewrite negb_false_iff in GuardFalse.
SearchAbout [beq_nat true].
apply beq_nat_true in GuardFalse.
apply GuardFalse. Qed.
(* ####################################################### *)
(** ** Example: Division *)
(** The following Imp program calculates the integer division and
remainder of two numbers [m] and [n] that are arbitrary constants
in the program.
X ::= m;;
Y ::= 0;;
WHILE n <= X DO
X ::= X - n;;
Y ::= Y + 1
END;
In other words, if we replace [m] and [n] by concrete numbers and
execute the program, it will terminate with the variable [X] set
to the remainder when [m] is divided by [n] and [Y] set to the
quotient. *)
(** In order to give a specification to this program we need to
remember that dividing [m] by [n] produces a reminder [X] and a
quotient [Y] so that [n * Y + X = m /\ X < n].
It turns out that we get lucky with this program and don't have to
think very hard about the loop invariant: the invariant is the
just first conjunct [n * Y + X = m], so we use that to decorate
the program.
(1) {{ True }} ->>
(2) {{ n * 0 + m = m }}
X ::= m;;
(3) {{ n * 0 + X = m }}
Y ::= 0;;
(4) {{ n * Y + X = m }}
WHILE n <= X DO
(5) {{ n * Y + X = m /\ n <= X }} ->>
(6) {{ n * (Y + 1) + (X - n) = m }}
X ::= X - n;;
(7) {{ n * (Y + 1) + X = m }}
Y ::= Y + 1
(8) {{ n * Y + X = m }}
END
(9) {{ n * Y + X = m /\ X < n }}
Assertions (4), (5), (8), and (9) are derived mechanically from
the invariant and the loop's guard. Assertions (8), (7), and (6)
are derived using the assignment rule going backwards from (8) to
(6). Assertions (4), (3), and (2) are again backwards applications
of the assignment rule.
Now that we've decorated the program it only remains to check that
the two uses of the consequence rule are correct -- i.e., that (1)
implies (2) and that (5) implies (6). This is indeed the case, so
we have a valid decorated program.
*)
(* ####################################################### *)
(** * Finding Loop Invariants *)
(** Once the outermost precondition and postcondition are chosen, the
only creative part in verifying programs with Hoare Logic is
finding the right loop invariants. The reason this is difficult
is the same as the reason that doing inductive mathematical proofs
requires creativity: strengthening the loop invariant (or the
induction hypothesis) means that you have a stronger assumption to
work with when trying to establish the postcondition of the loop
body (complete the induction step of the proof), but it also means
that the loop body postcondition itself is harder to prove!
This section is dedicated to teaching you how to approach the
challenge of finding loop invariants using a series of examples
and exercises. *)
(** ** Example: Slow Subtraction *)
(** The following program subtracts the value of [X] from the value of
[Y] by repeatedly decrementing both [X] and [Y]. We want to verify its
correctness with respect to the following specification:
{{ X = m /\ Y = n }}
WHILE X <> 0 DO
Y ::= Y - 1;;
X ::= X - 1
END
{{ Y = n - m }}
To verify this program we need to find an invariant [I] for the
loop. As a first step we can leave [I] as an unknown and build a
_skeleton_ for the proof by applying backward the rules for local
consistency. This process leads to the following skeleton:
(1) {{ X = m /\ Y = n }} ->> (a)
(2) {{ I }}
WHILE X <> 0 DO
(3) {{ I /\ X <> 0 }} ->> (c)
(4) {{ I[X |-> X-1][Y |-> Y-1] }}
Y ::= Y - 1;;
(5) {{ I[X |-> X-1] }}
X ::= X - 1
(6) {{ I }}
END
(7) {{ I /\ ~(X <> 0) }} ->> (b)
(8) {{ Y = n - m }}
By examining this skeleton, we can see that any valid [I] will
have to respect three conditions:
- (a) it must be weak enough to be implied by the loop's
precondition, i.e. (1) must imply (2);
- (b) it must be strong enough to imply the loop's postcondition,
i.e. (7) must imply (8);
- (c) it must be preserved by one iteration of the loop, i.e. (3)
must imply (4). *)
(** These conditions are actually independent of the particular
program and specification we are considering. Indeed, every loop
invariant has to satisfy them. One way to find an invariant that
simultaneously satisfies these three conditions is by using an
iterative process: start with a "candidate" invariant (e.g. a
guess or a heuristic choice) and check the three conditions above;
if any of the checks fails, try to use the information that we get
from the failure to produce another (hopefully better) candidate
invariant, and repeat the process.
For instance, in the reduce-to-zero example above, we saw that,
for a very simple loop, choosing [True] as an invariant did the
job. So let's try it again here! I.e., let's instantiate [I] with
[True] in the skeleton above see what we get...
(1) {{ X = m /\ Y = n }} ->> (a - OK)
(2) {{ True }}
WHILE X <> 0 DO
(3) {{ True /\ X <> 0 }} ->> (c - OK)
(4) {{ True }}
Y ::= Y - 1;;
(5) {{ True }}
X ::= X - 1
(6) {{ True }}
END
(7) {{ True /\ X = 0 }} ->> (b - WRONG!)
(8) {{ Y = n - m }}
While conditions (a) and (c) are trivially satisfied,
condition (b) is wrong, i.e. it is not the case that (7) [True /\
X = 0] implies (8) [Y = n - m]. In fact, the two assertions are
completely unrelated and it is easy to find a counterexample (say,
[Y = X = m = 0] and [n = 1]).
If we want (b) to hold, we need to strengthen the invariant so
that it implies the postcondition (8). One very simple way to do
this is to let the invariant _be_ the postcondition. So let's
return to our skeleton, instantiate [I] with [Y = n - m], and
check conditions (a) to (c) again.
(1) {{ X = m /\ Y = n }} ->> (a - WRONG!)
(2) {{ Y = n - m }}
WHILE X <> 0 DO
(3) {{ Y = n - m /\ X <> 0 }} ->> (c - WRONG!)
(4) {{ Y - 1 = n - m }}
Y ::= Y - 1;;
(5) {{ Y = n - m }}
X ::= X - 1
(6) {{ Y = n - m }}
END
(7) {{ Y = n - m /\ X = 0 }} ->> (b - OK)
(8) {{ Y = n - m }}
This time, condition (b) holds trivially, but (a) and (c) are
broken. Condition (a) requires that (1) [X = m /\ Y = n]
implies (2) [Y = n - m]. If we substitute [Y] by [n] we have to
show that [n = n - m] for arbitrary [m] and [n], which does not
hold (for instance, when [m = n = 1]). Condition (c) requires that
[n - m - 1 = n - m], which fails, for instance, for [n = 1] and [m =
0]. So, although [Y = n - m] holds at the end of the loop, it does
not hold from the start, and it doesn't hold on each iteration;
it is not a correct invariant.
This failure is not very surprising: the variable [Y] changes
during the loop, while [m] and [n] are constant, so the assertion
we chose didn't have much chance of being an invariant!
To do better, we need to generalize (8) to some statement that is
equivalent to (8) when [X] is [0], since this will be the case
when the loop terminates, and that "fills the gap" in some
appropriate way when [X] is nonzero. Looking at how the loop
works, we can observe that [X] and [Y] are decremented together
until [X] reaches [0]. So, if [X = 2] and [Y = 5] initially,
after one iteration of the loop we obtain [X = 1] and [Y = 4];
after two iterations [X = 0] and [Y = 3]; and then the loop stops.
Notice that the difference between [Y] and [X] stays constant
between iterations; initially, [Y = n] and [X = m], so this
difference is always [n - m]. So let's try instantiating [I] in
the skeleton above with [Y - X = n - m].
(1) {{ X = m /\ Y = n }} ->> (a - OK)
(2) {{ Y - X = n - m }}
WHILE X <> 0 DO
(3) {{ Y - X = n - m /\ X <> 0 }} ->> (c - OK)
(4) {{ (Y - 1) - (X - 1) = n - m }}
Y ::= Y - 1;;
(5) {{ Y - (X - 1) = n - m }}
X ::= X - 1
(6) {{ Y - X = n - m }}
END
(7) {{ Y - X = n - m /\ X = 0 }} ->> (b - OK)
(8) {{ Y = n - m }}
Success! Conditions (a), (b) and (c) all hold now. (To
verify (c), we need to check that, under the assumption that [X <>
0], we have [Y - X = (Y - 1) - (X - 1)]; this holds for all
natural numbers [X] and [Y].) *)
(* ####################################################### *)
(** ** Exercise: Slow Assignment *)
(** **** Exercise: 2 stars (slow_assignment) *)
(** A roundabout way of assigning a number currently stored in [X] to
the variable [Y] is to start [Y] at [0], then decrement [X] until
it hits [0], incrementing [Y] at each step. Here is a program that
implements this idea:
{{ X = m }}
Y ::= 0;;
WHILE X <> 0 DO
X ::= X - 1;;
Y ::= Y + 1
END
{{ Y = m }}
Write an informal decorated program showing that this is correct. *)
(* FILL IN HERE *)
(** [] *)
(* ####################################################### *)
(** ** Exercise: Slow Addition *)
(** **** Exercise: 3 stars, optional (add_slowly_decoration) *)
(** The following program adds the variable X into the variable Z
by repeatedly decrementing X and incrementing Z.
WHILE X <> 0 DO
Z ::= Z + 1;;
X ::= X - 1
END
Following the pattern of the [subtract_slowly] example above, pick
a precondition and postcondition that give an appropriate
specification of [add_slowly]; then (informally) decorate the
program accordingly. *)
(* FILL IN HERE *)
(** [] *)
(* ####################################################### *)
(** ** Example: Parity *)
(** Here is a cute little program for computing the parity of the
value initially stored in [X] (due to Daniel Cristofani).
{{ X = m }}
WHILE 2 <= X DO
X ::= X - 2
END
{{ X = parity m }}
The mathematical [parity] function used in the specification is
defined in Coq as follows: *)
Fixpoint parity x :=
match x with
| 0 => 0
| 1 => 1
| S (S x') => parity x'
end.
(** The postcondition does not hold at the beginning of the loop,
since [m = parity m] does not hold for an arbitrary [m], so we
cannot use that as an invariant. To find an invariant that works,
let's think a bit about what this loop does. On each iteration it
decrements [X] by [2], which preserves the parity of [X]. So the
parity of [X] does not change, i.e. it is invariant. The initial
value of [X] is [m], so the parity of [X] is always equal to the
parity of [m]. Using [parity X = parity m] as an invariant we
obtain the following decorated program:
{{ X = m }} ->> (a - OK)
{{ parity X = parity m }}
WHILE 2 <= X DO
{{ parity X = parity m /\ 2 <= X }} ->> (c - OK)
{{ parity (X-2) = parity m }}
X ::= X - 2
{{ parity X = parity m }}
END
{{ parity X = parity m /\ X < 2 }} ->> (b - OK)
{{ X = parity m }}
With this invariant, conditions (a), (b), and (c) are all
satisfied. For verifying (b), we observe that, when [X < 2], we
have [parity X = X] (we can easily see this in the definition of
[parity]). For verifying (c), we observe that, when [2 <= X], we
have [parity X = parity (X-2)]. *)
(** **** Exercise: 3 stars, optional (parity_formal) *)
(** Translate this proof to Coq. Refer to the reduce-to-zero example
for ideas. You may find the following two lemmas useful: *)
Lemma parity_ge_2 : forall x,
2 <= x ->
parity (x - 2) = parity x.
Proof.
induction x; intro. reflexivity.
destruct x. inversion H. inversion H1.
simpl. rewrite <- minus_n_O. reflexivity.
Qed.
Lemma parity_lt_2 : forall x,
~ 2 <= x ->
parity (x) = x.
Proof.
intros. induction x. reflexivity. destruct x. reflexivity.
apply ex_falso_quodlibet. apply H. omega.
Qed.
Theorem parity_correct : forall m,
{{ fun st => st X = m }}
WHILE BLe (ANum 2) (AId X) DO
X ::= AMinus (AId X) (ANum 2)
END
{{ fun st => st X = parity m }}.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(* ####################################################### *)
(** ** Example: Finding Square Roots *)
(** The following program computes the square root of [X]
by naive iteration:
{{ X=m }}
Z ::= 0;;
WHILE (Z+1)*(Z+1) <= X DO
Z ::= Z+1
END
{{ Z*Z<=m /\ m<(Z+1)*(Z+1) }}
*)
(** As above, we can try to use the postcondition as a candidate
invariant, obtaining the following decorated program:
(1) {{ X=m }} ->> (a - second conjunct of (2) WRONG!)
(2) {{ 0*0 <= m /\ m<1*1 }}
Z ::= 0;;
(3) {{ Z*Z <= m /\ m<(Z+1)*(Z+1) }}
WHILE (Z+1)*(Z+1) <= X DO
(4) {{ Z*Z<=m /\ (Z+1)*(Z+1)<=X }} ->> (c - WRONG!)
(5) {{ (Z+1)*(Z+1)<=m /\ m<(Z+2)*(Z+2) }}
Z ::= Z+1
(6) {{ Z*Z<=m /\ m<(Z+1)*(Z+1) }}
END
(7) {{ Z*Z<=m /\ m<(Z+1)*(Z+1) /\ X<(Z+1)*(Z+1) }} ->> (b - OK)
(8) {{ Z*Z<=m /\ m<(Z+1)*(Z+1) }}
This didn't work very well: both conditions (a) and (c) failed.
Looking at condition (c), we see that the second conjunct of (4)
is almost the same as the first conjunct of (5), except that (4)
mentions [X] while (5) mentions [m]. But note that [X] is never
assigned in this program, so we should have [X=m], but we didn't
propagate this information from (1) into the loop invariant.
Also, looking at the second conjunct of (8), it seems quite
hopeless as an invariant -- and we don't even need it, since we
can obtain it from the negation of the guard (third conjunct
in (7)), again under the assumption that [X=m].
So we now try [X=m /\ Z*Z <= m] as the loop invariant:
{{ X=m }} ->> (a - OK)
{{ X=m /\ 0*0 <= m }}
Z ::= 0;
{{ X=m /\ Z*Z <= m }}
WHILE (Z+1)*(Z+1) <= X DO
{{ X=m /\ Z*Z<=m /\ (Z+1)*(Z+1)<=X }} ->> (c - OK)
{{ X=m /\ (Z+1)*(Z+1)<=m }}
Z ::= Z+1
{{ X=m /\ Z*Z<=m }}
END
{{ X=m /\ Z*Z<=m /\ X<(Z+1)*(Z+1) }} ->> (b - OK)
{{ Z*Z<=m /\ m<(Z+1)*(Z+1) }}
This works, since conditions (a), (b), and (c) are now all
trivially satisfied.
Very often, if a variable is used in a loop in a read-only
fashion (i.e., it is referred to by the program or by the
specification and it is not changed by the loop) it is necessary
to add the fact that it doesn't change to the loop invariant. *)
(* ####################################################### *)
(** ** Example: Squaring *)
(** Here is a program that squares [X] by repeated addition:
{{ X = m }}
Y ::= 0;;
Z ::= 0;;
WHILE Y <> X DO
Z ::= Z + X;;
Y ::= Y + 1
END
{{ Z = m*m }}
*)
(** The first thing to note is that the loop reads [X] but doesn't
change its value. As we saw in the previous example, in such cases
it is a good idea to add [X = m] to the invariant. The other thing
we often use in the invariant is the postcondition, so let's add
that too, leading to the invariant candidate [Z = m * m /\ X = m].
{{ X = m }} ->> (a - WRONG)
{{ 0 = m*m /\ X = m }}
Y ::= 0;;
{{ 0 = m*m /\ X = m }}
Z ::= 0;;
{{ Z = m*m /\ X = m }}
WHILE Y <> X DO
{{ Z = Y*m /\ X = m /\ Y <> X }} ->> (c - WRONG)
{{ Z+X = m*m /\ X = m }}
Z ::= Z + X;;
{{ Z = m*m /\ X = m }}
Y ::= Y + 1
{{ Z = m*m /\ X = m }}
END
{{ Z = m*m /\ X = m /\ Y = X }} ->> (b - OK)
{{ Z = m*m }}
Conditions (a) and (c) fail because of the [Z = m*m] part. While
[Z] starts at [0] and works itself up to [m*m], we can't expect
[Z] to be [m*m] from the start. If we look at how [Z] progesses
in the loop, after the 1st iteration [Z = m], after the 2nd
iteration [Z = 2*m], and at the end [Z = m*m]. Since the variable
[Y] tracks how many times we go through the loop, we derive the
new invariant candidate [Z = Y*m /\ X = m].
{{ X = m }} ->> (a - OK)
{{ 0 = 0*m /\ X = m }}
Y ::= 0;;
{{ 0 = Y*m /\ X = m }}
Z ::= 0;;
{{ Z = Y*m /\ X = m }}
WHILE Y <> X DO
{{ Z = Y*m /\ X = m /\ Y <> X }} ->> (c - OK)
{{ Z+X = (Y+1)*m /\ X = m }}
Z ::= Z + X;
{{ Z = (Y+1)*m /\ X = m }}
Y ::= Y + 1
{{ Z = Y*m /\ X = m }}
END
{{ Z = Y*m /\ X = m /\ Y = X }} ->> (b - OK)
{{ Z = m*m }}
This new invariant makes the proof go through: all three
conditions are easy to check.
It is worth comparing the postcondition [Z = m*m] and the [Z =
Y*m] conjunct of the invariant. It is often the case that one has
to replace auxiliary variabes (parameters) with variables -- or
with expressions involving both variables and parameters (like
[m - Y]) -- when going from postconditions to invariants. *)
(* ####################################################### *)
(** ** Exercise: Factorial *)
(** **** Exercise: 3 stars (factorial) *)
(** Recall that [n!] denotes the factorial of [n] (i.e. [n! =
1*2*...*n]). Here is an Imp program that calculates the factorial
of the number initially stored in the variable [X] and puts it in
the variable [Y]:
{{ X = m }}
Y ::= 1 ;;
WHILE X <> 0
DO
Y ::= Y * X ;;
X ::= X - 1
END
{{ Y = m! }}
Fill in the blanks in following decorated program:
{{ X = m }} ->>
{{ }}
Y ::= 1;;
{{ }}
WHILE X <> 0
DO {{ }} ->>
{{ }}
Y ::= Y * X;;
{{ }}
X ::= X - 1
{{ }}
END
{{ }} ->>
{{ Y = m! }}
*)
(** [] *)
(* ####################################################### *)
(** ** Exercise: Min *)
(** **** Exercise: 3 stars (Min_Hoare) *)
(** Fill in valid decorations for the following program.
For the => steps in your annotations, you may rely (silently) on the
following facts about min
Lemma lemma1 : forall x y,
(x=0 \/ y=0) -> min x y = 0.
Lemma lemma2 : forall x y,
min (x-1) (y-1) = (min x y) - 1.
plus, as usual, standard high-school algebra.
{{ True }} ->>
{{ }}
X ::= a;;
{{ }}
Y ::= b;;
{{ }}
Z ::= 0;;
{{ }}
WHILE (X <> 0 /\ Y <> 0) DO
{{ }} ->>
{{ }}
X := X - 1;;
{{ }}
Y := Y - 1;;
{{ }}
Z := Z + 1
{{ }}
END
{{ }} ->>
{{ Z = min a b }}
*)
(** [] *)
(** **** Exercise: 3 stars (two_loops) *)
(** Here is a very inefficient way of adding 3 numbers:
X ::= 0;;
Y ::= 0;;
Z ::= c;;
WHILE X <> a DO
X ::= X + 1;;
Z ::= Z + 1
END;;
WHILE Y <> b DO
Y ::= Y + 1;;
Z ::= Z + 1
END
Show that it does what it should by filling in the blanks in the
following decorated program.
{{ True }} ->>
{{ }}
X ::= 0;;
{{ }}
Y ::= 0;;
{{ }}
Z ::= c;;
{{ }}
WHILE X <> a DO
{{ }} ->>
{{ }}
X ::= X + 1;;
{{ }}
Z ::= Z + 1
{{ }}
END;;
{{ }} ->>
{{ }}
WHILE Y <> b DO
{{ }} ->>
{{ }}
Y ::= Y + 1;;
{{ }}
Z ::= Z + 1
{{ }}
END
{{ }} ->>
{{ Z = a + b + c }}
*)
(** [] *)
(* ####################################################### *)
(** ** Exercise: Power Series *)
(** **** Exercise: 4 stars, optional (dpow2_down) *)
(** Here is a program that computes the series:
[1 + 2 + 2^2 + ... + 2^m = 2^(m+1) - 1]
X ::= 0;;
Y ::= 1;;
Z ::= 1;;
WHILE X <> m DO
Z ::= 2 * Z;;
Y ::= Y + Z;;
X ::= X + 1
END
Write a decorated program for this. *)
(* FILL IN HERE *)
(* ####################################################### *)
(** * Weakest Preconditions (Advanced) *)
(** Some Hoare triples are more interesting than others.
For example,
{{ False }} X ::= Y + 1 {{ X <= 5 }}
is _not_ very interesting: although it is perfectly valid, it
tells us nothing useful. Since the precondition isn't satisfied
by any state, it doesn't describe any situations where we can use
the command [X ::= Y + 1] to achieve the postcondition [X <= 5].
By contrast,
{{ Y <= 4 /\ Z = 0 }} X ::= Y + 1 {{ X <= 5 }}
is useful: it tells us that, if we can somehow create a situation
in which we know that [Y <= 4 /\ Z = 0], then running this command
will produce a state satisfying the postcondition. However, this
triple is still not as useful as it could be, because the [Z = 0]
clause in the precondition actually has nothing to do with the
postcondition [X <= 5]. The _most_ useful triple (for a given
command and postcondition) is this one:
{{ Y <= 4 }} X ::= Y + 1 {{ X <= 5 }}
In other words, [Y <= 4] is the _weakest_ valid precondition of
the command [X ::= Y + 1] for the postcondition [X <= 5]. *)
(** In general, we say that "[P] is the weakest precondition of
command [c] for postcondition [Q]" if [{{P}} c {{Q}}] and if,
whenever [P'] is an assertion such that [{{P'}} c {{Q}}], we have
[P' st] implies [P st] for all states [st]. *)
Definition is_wp P c Q :=
{{P}} c {{Q}} /\
forall P', {{P'}} c {{Q}} -> (P' ->> P).
(** That is, [P] is the weakest precondition of [c] for [Q]
if (a) [P] _is_ a precondition for [Q] and [c], and (b) [P] is the
_weakest_ (easiest to satisfy) assertion that guarantees [Q] after
executing [c]. *)
(** **** Exercise: 1 star, optional (wp) *)
(** What are the weakest preconditions of the following commands
for the following postconditions?
1) {{ ? }} SKIP {{ X = 5 }}
2) {{ ? }} X ::= Y + Z {{ X = 5 }}
3) {{ ? }} X ::= Y {{ X = Y }}
4) {{ ? }}
IFB X == 0 THEN Y ::= Z + 1 ELSE Y ::= W + 2 FI
{{ Y = 5 }}
5) {{ ? }}
X ::= 5
{{ X = 0 }}
6) {{ ? }}
WHILE True DO X ::= 0 END
{{ X = 0 }}
*)
(* FILL IN HERE *)
(** [] *)
(** **** Exercise: 3 stars, advanced, optional (is_wp_formal) *)
(** Prove formally using the definition of [hoare_triple] that [Y <= 4]
is indeed the weakest precondition of [X ::= Y + 1] with respect to
postcondition [X <= 5]. *)
Theorem is_wp_example :
is_wp (fun st => st Y <= 4)
(X ::= APlus (AId Y) (ANum 1)) (fun st => st X <= 5).
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 2 stars, advanced (hoare_asgn_weakest) *)
(** Show that the precondition in the rule [hoare_asgn] is in fact the
weakest precondition. *)
Theorem hoare_asgn_weakest : forall Q X a,
is_wp (Q [X |-> a]) (X ::= a) Q.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 2 stars, advanced, optional (hoare_havoc_weakest) *)
(** Show that your [havoc_pre] rule from the [himp_hoare] exercise
in the [Hoare] chapter returns the weakest precondition. *)
Module Himp2.
Import Himp.
Lemma hoare_havoc_weakest : forall (P Q : Assertion) (X : id),
{{ P }} HAVOC X {{ Q }} ->
P ->> havoc_pre X Q.
Proof.
(* FILL IN HERE *) Admitted.
End Himp2.
(** [] *)
(* ####################################################### *)
(** * Formal Decorated Programs (Advanced) *)
(** The informal conventions for decorated programs amount to a way of
displaying Hoare triples in which commands are annotated with
enough embedded assertions that checking the validity of the
triple is reduced to simple logical and algebraic calculations
showing that some assertions imply others. In this section, we
show that this informal presentation style can actually be made
completely formal and indeed that checking the validity of
decorated programs can mostly be automated. *)
(** ** Syntax *)
(** The first thing we need to do is to formalize a variant of the
syntax of commands with embedded assertions. We call the new
commands _decorated commands_, or [dcom]s. *)
Inductive dcom : Type :=
| DCSkip : Assertion -> dcom
| DCSeq : dcom -> dcom -> dcom
| DCAsgn : id -> aexp -> Assertion -> dcom
| DCIf : bexp -> Assertion -> dcom -> Assertion -> dcom
-> Assertion-> dcom
| DCWhile : bexp -> Assertion -> dcom -> Assertion -> dcom
| DCPre : Assertion -> dcom -> dcom
| DCPost : dcom -> Assertion -> dcom.
Tactic Notation "dcom_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "Skip" | Case_aux c "Seq" | Case_aux c "Asgn"
| Case_aux c "If" | Case_aux c "While"
| Case_aux c "Pre" | Case_aux c "Post" ].
Notation "'SKIP' {{ P }}"
:= (DCSkip P)
(at level 10) : dcom_scope.
Notation "l '::=' a {{ P }}"
:= (DCAsgn l a P)
(at level 60, a at next level) : dcom_scope.
Notation "'WHILE' b 'DO' {{ Pbody }} d 'END' {{ Ppost }}"
:= (DCWhile b Pbody d Ppost)
(at level 80, right associativity) : dcom_scope.
Notation "'IFB' b 'THEN' {{ P }} d 'ELSE' {{ P' }} d' 'FI' {{ Q }}"
:= (DCIf b P d P' d' Q)
(at level 80, right associativity) : dcom_scope.
Notation "'->>' {{ P }} d"
:= (DCPre P d)
(at level 90, right associativity) : dcom_scope.
Notation "{{ P }} d"
:= (DCPre P d)
(at level 90) : dcom_scope.
Notation "d '->>' {{ P }}"
:= (DCPost d P)
(at level 80, right associativity) : dcom_scope.
Notation " d ;; d' "
:= (DCSeq d d')
(at level 80, right associativity) : dcom_scope.
Delimit Scope dcom_scope with dcom.
(** To avoid clashing with the existing [Notation] definitions
for ordinary [com]mands, we introduce these notations in a special
scope called [dcom_scope], and we wrap examples with the
declaration [% dcom] to signal that we want the notations to be
interpreted in this scope.
Careful readers will note that we've defined two notations for the
[DCPre] constructor, one with and one without a [->>]. The
"without" version is intended to be used to supply the initial
precondition at the very top of the program. *)
Example dec_while : dcom := (
{{ fun st => True }}
WHILE (BNot (BEq (AId X) (ANum 0)))
DO
{{ fun st => True /\ st X <> 0}}
X ::= (AMinus (AId X) (ANum 1))
{{ fun _ => True }}
END
{{ fun st => True /\ st X = 0}} ->>
{{ fun st => st X = 0 }}
) % dcom.
(** It is easy to go from a [dcom] to a [com] by erasing all
annotations. *)
Fixpoint extract (d:dcom) : com :=
match d with
| DCSkip _ => SKIP
| DCSeq d1 d2 => (extract d1 ;; extract d2)
| DCAsgn X a _ => X ::= a
| DCIf b _ d1 _ d2 _ => IFB b THEN extract d1 ELSE extract d2 FI
| DCWhile b _ d _ => WHILE b DO extract d END
| DCPre _ d => extract d
| DCPost d _ => extract d
end.
(** The choice of exactly where to put assertions in the definition of
[dcom] is a bit subtle. The simplest thing to do would be to
annotate every [dcom] with a precondition and postcondition. But
this would result in very verbose programs with a lot of repeated
annotations: for example, a program like [SKIP;SKIP] would have to
be annotated as
{{P}} ({{P}} SKIP {{P}}) ;; ({{P}} SKIP {{P}}) {{P}},
with pre- and post-conditions on each [SKIP], plus identical pre-
and post-conditions on the semicolon!
Instead, the rule we've followed is this:
- The _post_-condition expected by each [dcom] [d] is embedded in [d]
- The _pre_-condition is supplied by the context. *)
(** In other words, the invariant of the representation is that a
[dcom] [d] together with a precondition [P] determines a Hoare
triple [{{P}} (extract d) {{post d}}], where [post] is defined as
follows: *)
Fixpoint post (d:dcom) : Assertion :=
match d with
| DCSkip P => P
| DCSeq d1 d2 => post d2
| DCAsgn X a Q => Q
| DCIf _ _ d1 _ d2 Q => Q
| DCWhile b Pbody c Ppost => Ppost
| DCPre _ d => post d
| DCPost c Q => Q
end.
(** Similarly, we can extract the "initial precondition" from a
decorated program. *)
Fixpoint pre (d:dcom) : Assertion :=
match d with
| DCSkip P => fun st => True
| DCSeq c1 c2 => pre c1
| DCAsgn X a Q => fun st => True
| DCIf _ _ t _ e _ => fun st => True
| DCWhile b Pbody c Ppost => fun st => True
| DCPre P c => P
| DCPost c Q => pre c
end.
(** This function is not doing anything sophisticated like calculating
a weakest precondition; it just recursively searches for an
explicit annotation at the very beginning of the program,
returning default answers for programs that lack an explicit
precondition (like a bare assignment or [SKIP]). *)
(** Using [pre] and [post], and assuming that we adopt the convention
of always supplying an explicit precondition annotation at the
very beginning of our decorated programs, we can express what it
means for a decorated program to be correct as follows: *)
Definition dec_correct (d:dcom) :=
{{pre d}} (extract d) {{post d}}.
(** To check whether this Hoare triple is _valid_, we need a way to
extract the "proof obligations" from a decorated program. These
obligations are often called _verification conditions_, because
they are the facts that must be verified to see that the
decorations are logically consistent and thus add up to a complete
proof of correctness. *)
(** ** Extracting Verification Conditions *)
(** The function [verification_conditions] takes a [dcom] [d] together
with a precondition [P] and returns a _proposition_ that, if it
can be proved, implies that the triple [{{P}} (extract d) {{post d}}]
is valid. *)
(** It does this by walking over [d] and generating a big
conjunction including all the "local checks" that we listed when
we described the informal rules for decorated programs. (Strictly
speaking, we need to massage the informal rules a little bit to
add some uses of the rule of consequence, but the correspondence
should be clear.) *)
Fixpoint verification_conditions (P : Assertion) (d:dcom) : Prop :=
match d with
| DCSkip Q =>
(P ->> Q)
| DCSeq d1 d2 =>
verification_conditions P d1
/\ verification_conditions (post d1) d2
| DCAsgn X a Q =>
(P ->> Q [X |-> a])
| DCIf b P1 d1 P2 d2 Q =>
((fun st => P st /\ bassn b st) ->> P1)
/\ ((fun st => P st /\ ~ (bassn b st)) ->> P2)
/\ (Q <<->> post d1) /\ (Q <<->> post d2)
/\ verification_conditions P1 d1
/\ verification_conditions P2 d2
| DCWhile b Pbody d Ppost =>
(* post d is the loop invariant and the initial precondition *)
(P ->> post d)
/\ (Pbody <<->> (fun st => post d st /\ bassn b st))
/\ (Ppost <<->> (fun st => post d st /\ ~(bassn b st)))
/\ verification_conditions Pbody d
| DCPre P' d =>
(P ->> P') /\ verification_conditions P' d
| DCPost d Q =>
verification_conditions P d /\ (post d ->> Q)
end.
(** And now, the key theorem, which states that
[verification_conditions] does its job correctly. Not
surprisingly, we need to use each of the Hoare Logic rules at some
point in the proof. *)
(** We have used _in_ variants of several tactics before to
apply them to values in the context rather than the goal. An
extension of this idea is the syntax [tactic in *], which applies
[tactic] in the goal and every hypothesis in the context. We most
commonly use this facility in conjunction with the [simpl] tactic,
as below. *)
Theorem verification_correct : forall d P,
verification_conditions P d -> {{P}} (extract d) {{post d}}.
Proof.
dcom_cases (induction d) Case; intros P H; simpl in *.
Case "Skip".
eapply hoare_consequence_pre.
apply hoare_skip.
assumption.
Case "Seq".
inversion H as [H1 H2]. clear H.
eapply hoare_seq.
apply IHd2. apply H2.
apply IHd1. apply H1.
Case "Asgn".
eapply hoare_consequence_pre.
apply hoare_asgn.
assumption.
Case "If".
inversion H as [HPre1 [HPre2 [[Hd11 Hd12]
[[Hd21 Hd22] [HThen HElse]]]]].
clear H.
apply IHd1 in HThen. clear IHd1.
apply IHd2 in HElse. clear IHd2.
apply hoare_if.
eapply hoare_consequence_pre; eauto.
eapply hoare_consequence_post; eauto.
eapply hoare_consequence_pre; eauto.
eapply hoare_consequence_post; eauto.
Case "While".
inversion H as [Hpre [[Hbody1 Hbody2] [[Hpost1 Hpost2] Hd]]];
subst; clear H.
eapply hoare_consequence_pre; eauto.
eapply hoare_consequence_post; eauto.
apply hoare_while.
eapply hoare_consequence_pre; eauto.
Case "Pre".
inversion H as [HP Hd]; clear H.
eapply hoare_consequence_pre. apply IHd. apply Hd. assumption.
Case "Post".
inversion H as [Hd HQ]; clear H.
eapply hoare_consequence_post. apply IHd. apply Hd. assumption.
Qed.
(** ** Examples *)
(** The propositions generated by [verification_conditions] are fairly
big, and they contain many conjuncts that are essentially trivial. *)
Eval simpl in (verification_conditions (fun st => True) dec_while).
(**
==>
(((fun _ : state => True) ->> (fun _ : state => True)) /\
((fun _ : state => True) ->> (fun _ : state => True)) /\
(fun st : state => True /\ bassn (BNot (BEq (AId X) (ANum 0))) st) =
(fun st : state => True /\ bassn (BNot (BEq (AId X) (ANum 0))) st) /\
(fun st : state => True /\ ~ bassn (BNot (BEq (AId X) (ANum 0))) st) =
(fun st : state => True /\ ~ bassn (BNot (BEq (AId X) (ANum 0))) st) /\
(fun st : state => True /\ bassn (BNot (BEq (AId X) (ANum 0))) st) ->>
(fun _ : state => True) [X |-> AMinus (AId X) (ANum 1)]) /\
(fun st : state => True /\ ~ bassn (BNot (BEq (AId X) (ANum 0))) st) ->>
(fun st : state => st X = 0)
*)
(** In principle, we could certainly work with them using just the
tactics we have so far, but we can make things much smoother with
a bit of automation. We first define a custom [verify] tactic
that applies splitting repeatedly to turn all the conjunctions
into separate subgoals and then uses [omega] and [eauto] (a handy
general-purpose automation tactic that we'll discuss in detail
later) to deal with as many of them as possible. *)
Lemma ble_nat_true_iff : forall n m : nat,
ble_nat n m = true <-> n <= m.
Proof.
intros n m. split. apply ble_nat_true.
generalize dependent m. induction n; intros m H. reflexivity.
simpl. destruct m. inversion H.
apply le_S_n in H. apply IHn. assumption.
Qed.
Lemma ble_nat_false_iff : forall n m : nat,
ble_nat n m = false <-> ~(n <= m).
Proof.
intros n m. split. apply ble_nat_false.
generalize dependent m. induction n; intros m H.
apply ex_falso_quodlibet. apply H. apply le_0_n.
simpl. destruct m. reflexivity.
apply IHn. intro Hc. apply H. apply le_n_S. assumption.
Qed.
Tactic Notation "verify" :=
apply verification_correct;
repeat split;
simpl; unfold assert_implies;
unfold bassn in *; unfold beval in *; unfold aeval in *;
unfold assn_sub; intros;
repeat rewrite update_eq;
repeat (rewrite update_neq; [| (intro X; inversion X)]);
simpl in *;
repeat match goal with [H : _ /\ _ |- _] => destruct H end;
repeat rewrite not_true_iff_false in *;
repeat rewrite not_false_iff_true in *;
repeat rewrite negb_true_iff in *;
repeat rewrite negb_false_iff in *;
repeat rewrite beq_nat_true_iff in *;
repeat rewrite beq_nat_false_iff in *;
repeat rewrite ble_nat_true_iff in *;
repeat rewrite ble_nat_false_iff in *;
try subst;
repeat
match goal with
[st : state |- _] =>
match goal with
[H : st _ = _ |- _] => rewrite -> H in *; clear H
| [H : _ = st _ |- _] => rewrite <- H in *; clear H
end
end;
try eauto; try omega.
(** What's left after [verify] does its thing is "just the interesting
parts" of checking that the decorations are correct. For very
simple examples [verify] immediately solves the goal (provided
that the annotations are correct). *)
Theorem dec_while_correct :
dec_correct dec_while.
Proof. verify. Qed.
(** Another example (formalizing a decorated program we've seen
before): *)
Example subtract_slowly_dec (m:nat) (p:nat) : dcom := (
{{ fun st => st X = m /\ st Z = p }} ->>
{{ fun st => st Z - st X = p - m }}
WHILE BNot (BEq (AId X) (ANum 0))
DO {{ fun st => st Z - st X = p - m /\ st X <> 0 }} ->>
{{ fun st => (st Z - 1) - (st X - 1) = p - m }}
Z ::= AMinus (AId Z) (ANum 1)
{{ fun st => st Z - (st X - 1) = p - m }} ;;
X ::= AMinus (AId X) (ANum 1)
{{ fun st => st Z - st X = p - m }}
END
{{ fun st => st Z - st X = p - m /\ st X = 0 }} ->>
{{ fun st => st Z = p - m }}
) % dcom.
Theorem subtract_slowly_dec_correct : forall m p,
dec_correct (subtract_slowly_dec m p).
Proof. intros m p. verify. (* this grinds for a bit! *) Qed.
(** **** Exercise: 3 stars, advanced (slow_assignment_dec) *)
(** In the [slow_assignment] exercise above, we saw a roundabout way
of assigning a number currently stored in [X] to the variable [Y]:
start [Y] at [0], then decrement [X] until it hits [0],
incrementing [Y] at each step.
Write a _formal_ version of this decorated program and prove it
correct. *)
Example slow_assignment_dec (m:nat) : dcom :=
(* FILL IN HERE *) admit.
Theorem slow_assignment_dec_correct : forall m,
dec_correct (slow_assignment_dec m).
Proof. (* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 4 stars, advanced (factorial_dec) *)
(** Remember the factorial function we worked with before: *)
Fixpoint real_fact (n:nat) : nat :=
match n with
| O => 1
| S n' => n * (real_fact n')
end.
(** Following the pattern of [subtract_slowly_dec], write a decorated
program [factorial_dec] that implements the factorial function and
prove it correct as [factorial_dec_correct]. *)
(* FILL IN HERE *)
(** [] *)
(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)
|
(** * Hoare2: Hoare Logic, Part II *)
Require Export Hoare.
(* ####################################################### *)
(** * Decorated Programs *)
(** The beauty of Hoare Logic is that it is _compositional_ --
the structure of proofs exactly follows the structure of programs.
This suggests that we can record the essential ideas of a proof
informally (leaving out some low-level calculational details) by
decorating programs with appropriate assertions around each
statement. Such a _decorated program_ carries with it
an (informal) proof of its own correctness. *)
(** For example, here is a complete decorated program: *)
(**
{{ True }} ->>
{{ m = m }}
X ::= m;;
{{ X = m }} ->>
{{ X = m /\ p = p }}
Z ::= p;
{{ X = m /\ Z = p }} ->>
{{ Z - X = p - m }}
WHILE X <> 0 DO
{{ Z - X = p - m /\ X <> 0 }} ->>
{{ (Z - 1) - (X - 1) = p - m }}
Z ::= Z - 1;;
{{ Z - (X - 1) = p - m }}
X ::= X - 1
{{ Z - X = p - m }}
END;
{{ Z - X = p - m /\ ~ (X <> 0) }} ->>
{{ Z = p - m }}
*)
(** Concretely, a decorated program consists of the program text
interleaved with assertions. To check that a decorated program
represents a valid proof, we check that each individual command is
_locally consistent_ with its accompanying assertions in the
following sense: *)
(**
- [SKIP] is locally consistent if its precondition and
postcondition are the same:
{{ P }}
SKIP
{{ P }}
*)
(**
- The sequential composition of [c1] and [c2] is locally
consistent (with respect to assertions [P] and [R]) if [c1] is
locally consistent (with respect to [P] and [Q]) and [c2] is
locally consistent (with respect to [Q] and [R]):
{{ P }}
c1;;
{{ Q }}
c2
{{ R }}
*)
(**
- An assignment is locally consistent if its precondition is
the appropriate substitution of its postcondition:
{{ P [X |-> a] }}
X ::= a
{{ P }}
*)
(**
- A conditional is locally consistent (with respect to assertions
[P] and [Q]) if the assertions at the top of its "then" and
"else" branches are exactly [P /\ b] and [P /\ ~b] and if its "then"
branch is locally consistent (with respect to [P /\ b] and [Q])
and its "else" branch is locally consistent (with respect to
[P /\ ~b] and [Q]):
{{ P }}
IFB b THEN
{{ P /\ b }}
c1
{{ Q }}
ELSE
{{ P /\ ~b }}
c2
{{ Q }}
FI
{{ Q }}
*)
(**
- A while loop with precondition [P] is locally consistent if its
postcondition is [P /\ ~b] and if the pre- and postconditions of
its body are exactly [P /\ b] and [P]:
{{ P }}
WHILE b DO
{{ P /\ b }}
c1
{{ P }}
END
{{ P /\ ~b }}
*)
(**
- A pair of assertions separated by [->>] is locally consistent if
the first implies the second (in all states):
{{ P }} ->>
{{ P' }}
This corresponds to the application of [hoare_consequence] and
is the only place in a decorated program where checking if
decorations are correct is not fully mechanical and syntactic,
but involves logical and/or arithmetic reasoning.
*)
(** We have seen above how _verifying_ the correctness of a
given proof involves checking that every single command is locally
consistent with the accompanying assertions. If we are instead
interested in _finding_ a proof for a given specification we need
to discover the right assertions. This can be done in an almost
automatic way, with the exception of finding loop invariants,
which is the subject of in the next section. In the reminder of
this section we explain in detail how to construct decorations for
several simple programs that don't involve non-trivial loop
invariants. *)
(* ####################################################### *)
(** ** Example: Swapping Using Addition and Subtraction *)
(** Here is a program that swaps the values of two variables using
addition and subtraction (instead of by assigning to a temporary
variable).
X ::= X + Y;;
Y ::= X - Y;;
X ::= X - Y
We can prove using decorations that this program is correct --
i.e., it always swaps the values of variables [X] and [Y]. *)
(**
(1) {{ X = m /\ Y = n }} ->>
(2) {{ (X + Y) - ((X + Y) - Y) = n /\ (X + Y) - Y = m }}
X ::= X + Y;;
(3) {{ X - (X - Y) = n /\ X - Y = m }}
Y ::= X - Y;;
(4) {{ X - Y = n /\ Y = m }}
X ::= X - Y
(5) {{ X = n /\ Y = m }}
The decorations were constructed as follows:
- We begin with the undecorated program (the unnumbered lines).
- We then add the specification -- i.e., the outer
precondition (1) and postcondition (5). In the precondition we
use auxiliary variables (parameters) [m] and [n] to remember
the initial values of variables [X] and respectively [Y], so
that we can refer to them in the postcondition (5).
- We work backwards mechanically starting from (5) all the way
to (2). At each step, we obtain the precondition of the
assignment from its postcondition by substituting the assigned
variable with the right-hand-side of the assignment. For
instance, we obtain (4) by substituting [X] with [X - Y]
in (5), and (3) by substituting [Y] with [X - Y] in (4).
- Finally, we verify that (1) logically implies (2) -- i.e.,
that the step from (1) to (2) is a valid use of the law of
consequence. For this we substitute [X] by [m] and [Y] by [n]
and calculate as follows:
(m + n) - ((m + n) - n) = n /\ (m + n) - n = m
(m + n) - m = n /\ m = m
n = n /\ m = m
(Note that, since we are working with natural numbers, not
fixed-size machine integers, we don't need to worry about the
possibility of arithmetic overflow anywhere in this argument.)
*)
(* ####################################################### *)
(** ** Example: Simple Conditionals *)
(** Here is a simple decorated program using conditionals:
(1) {{True}}
IFB X <= Y THEN
(2) {{True /\ X <= Y}} ->>
(3) {{(Y - X) + X = Y \/ (Y - X) + Y = X}}
Z ::= Y - X
(4) {{Z + X = Y \/ Z + Y = X}}
ELSE
(5) {{True /\ ~(X <= Y) }} ->>
(6) {{(X - Y) + X = Y \/ (X - Y) + Y = X}}
Z ::= X - Y
(7) {{Z + X = Y \/ Z + Y = X}}
FI
(8) {{Z + X = Y \/ Z + Y = X}}
These decorations were constructed as follows:
- We start with the outer precondition (1) and postcondition (8).
- We follow the format dictated by the [hoare_if] rule and copy the
postcondition (8) to (4) and (7). We conjoin the precondition (1)
with the guard of the conditional to obtain (2). We conjoin (1)
with the negated guard of the conditional to obtain (5).
- In order to use the assignment rule and obtain (3), we substitute
[Z] by [Y - X] in (4). To obtain (6) we substitute [Z] by [X - Y]
in (7).
- Finally, we verify that (2) implies (3) and (5) implies (6). Both
of these implications crucially depend on the ordering of [X] and
[Y] obtained from the guard. For instance, knowing that [X <= Y]
ensures that subtracting [X] from [Y] and then adding back [X]
produces [Y], as required by the first disjunct of (3). Similarly,
knowing that [~(X <= Y)] ensures that subtracting [Y] from [X] and
then adding back [Y] produces [X], as needed by the second
disjunct of (6). Note that [n - m + m = n] does _not_ hold for
arbitrary natural numbers [n] and [m] (for example, [3 - 5 + 5 =
5]). *)
(** **** Exercise: 2 stars (if_minus_plus_reloaded) *)
(** Fill in valid decorations for the following program:
{{ True }}
IFB X <= Y THEN
{{ }} ->>
{{ }}
Z ::= Y - X
{{ }}
ELSE
{{ }} ->>
{{ }}
Y ::= X + Z
{{ }}
FI
{{ Y = X + Z }}
*)
(** [] *)
(* ####################################################### *)
(** ** Example: Reduce to Zero (Trivial Loop) *)
(** Here is a [WHILE] loop that is so simple it needs no
invariant (i.e., the invariant [True] will do the job).
(1) {{ True }}
WHILE X <> 0 DO
(2) {{ True /\ X <> 0 }} ->>
(3) {{ True }}
X ::= X - 1
(4) {{ True }}
END
(5) {{ True /\ X = 0 }} ->>
(6) {{ X = 0 }}
The decorations can be constructed as follows:
- Start with the outer precondition (1) and postcondition (6).
- Following the format dictated by the [hoare_while] rule, we copy
(1) to (4). We conjoin (1) with the guard to obtain (2) and with
the negation of the guard to obtain (5). Note that, because the
outer postcondition (6) does not syntactically match (5), we need a
trivial use of the consequence rule from (5) to (6).
- Assertion (3) is the same as (4), because [X] does not appear in
[4], so the substitution in the assignment rule is trivial.
- Finally, the implication between (2) and (3) is also trivial.
*)
(** From this informal proof, it is easy to read off a formal proof
using the Coq versions of the Hoare rules. Note that we do _not_
unfold the definition of [hoare_triple] anywhere in this proof --
the idea is to use the Hoare rules as a "self-contained" logic for
reasoning about programs. *)
Definition reduce_to_zero' : com :=
WHILE BNot (BEq (AId X) (ANum 0)) DO
X ::= AMinus (AId X) (ANum 1)
END.
Theorem reduce_to_zero_correct' :
{{fun st => True}}
reduce_to_zero'
{{fun st => st X = 0}}.
Proof.
unfold reduce_to_zero'.
(* First we need to transform the postcondition so
that hoare_while will apply. *)
eapply hoare_consequence_post.
apply hoare_while.
Case "Loop body preserves invariant".
(* Need to massage precondition before [hoare_asgn] applies *)
eapply hoare_consequence_pre. apply hoare_asgn.
(* Proving trivial implication (2) ->> (3) *)
intros st [HT Hbp]. unfold assn_sub. apply I.
Case "Invariant and negated guard imply postcondition".
intros st [Inv GuardFalse].
unfold bassn in GuardFalse. simpl in GuardFalse.
(* SearchAbout helps to find the right lemmas *)
SearchAbout [not true].
rewrite not_true_iff_false in GuardFalse.
SearchAbout [negb false].
rewrite negb_false_iff in GuardFalse.
SearchAbout [beq_nat true].
apply beq_nat_true in GuardFalse.
apply GuardFalse. Qed.
(* ####################################################### *)
(** ** Example: Division *)
(** The following Imp program calculates the integer division and
remainder of two numbers [m] and [n] that are arbitrary constants
in the program.
X ::= m;;
Y ::= 0;;
WHILE n <= X DO
X ::= X - n;;
Y ::= Y + 1
END;
In other words, if we replace [m] and [n] by concrete numbers and
execute the program, it will terminate with the variable [X] set
to the remainder when [m] is divided by [n] and [Y] set to the
quotient. *)
(** In order to give a specification to this program we need to
remember that dividing [m] by [n] produces a reminder [X] and a
quotient [Y] so that [n * Y + X = m /\ X < n].
It turns out that we get lucky with this program and don't have to
think very hard about the loop invariant: the invariant is the
just first conjunct [n * Y + X = m], so we use that to decorate
the program.
(1) {{ True }} ->>
(2) {{ n * 0 + m = m }}
X ::= m;;
(3) {{ n * 0 + X = m }}
Y ::= 0;;
(4) {{ n * Y + X = m }}
WHILE n <= X DO
(5) {{ n * Y + X = m /\ n <= X }} ->>
(6) {{ n * (Y + 1) + (X - n) = m }}
X ::= X - n;;
(7) {{ n * (Y + 1) + X = m }}
Y ::= Y + 1
(8) {{ n * Y + X = m }}
END
(9) {{ n * Y + X = m /\ X < n }}
Assertions (4), (5), (8), and (9) are derived mechanically from
the invariant and the loop's guard. Assertions (8), (7), and (6)
are derived using the assignment rule going backwards from (8) to
(6). Assertions (4), (3), and (2) are again backwards applications
of the assignment rule.
Now that we've decorated the program it only remains to check that
the two uses of the consequence rule are correct -- i.e., that (1)
implies (2) and that (5) implies (6). This is indeed the case, so
we have a valid decorated program.
*)
(* ####################################################### *)
(** * Finding Loop Invariants *)
(** Once the outermost precondition and postcondition are chosen, the
only creative part in verifying programs with Hoare Logic is
finding the right loop invariants. The reason this is difficult
is the same as the reason that doing inductive mathematical proofs
requires creativity: strengthening the loop invariant (or the
induction hypothesis) means that you have a stronger assumption to
work with when trying to establish the postcondition of the loop
body (complete the induction step of the proof), but it also means
that the loop body postcondition itself is harder to prove!
This section is dedicated to teaching you how to approach the
challenge of finding loop invariants using a series of examples
and exercises. *)
(** ** Example: Slow Subtraction *)
(** The following program subtracts the value of [X] from the value of
[Y] by repeatedly decrementing both [X] and [Y]. We want to verify its
correctness with respect to the following specification:
{{ X = m /\ Y = n }}
WHILE X <> 0 DO
Y ::= Y - 1;;
X ::= X - 1
END
{{ Y = n - m }}
To verify this program we need to find an invariant [I] for the
loop. As a first step we can leave [I] as an unknown and build a
_skeleton_ for the proof by applying backward the rules for local
consistency. This process leads to the following skeleton:
(1) {{ X = m /\ Y = n }} ->> (a)
(2) {{ I }}
WHILE X <> 0 DO
(3) {{ I /\ X <> 0 }} ->> (c)
(4) {{ I[X |-> X-1][Y |-> Y-1] }}
Y ::= Y - 1;;
(5) {{ I[X |-> X-1] }}
X ::= X - 1
(6) {{ I }}
END
(7) {{ I /\ ~(X <> 0) }} ->> (b)
(8) {{ Y = n - m }}
By examining this skeleton, we can see that any valid [I] will
have to respect three conditions:
- (a) it must be weak enough to be implied by the loop's
precondition, i.e. (1) must imply (2);
- (b) it must be strong enough to imply the loop's postcondition,
i.e. (7) must imply (8);
- (c) it must be preserved by one iteration of the loop, i.e. (3)
must imply (4). *)
(** These conditions are actually independent of the particular
program and specification we are considering. Indeed, every loop
invariant has to satisfy them. One way to find an invariant that
simultaneously satisfies these three conditions is by using an
iterative process: start with a "candidate" invariant (e.g. a
guess or a heuristic choice) and check the three conditions above;
if any of the checks fails, try to use the information that we get
from the failure to produce another (hopefully better) candidate
invariant, and repeat the process.
For instance, in the reduce-to-zero example above, we saw that,
for a very simple loop, choosing [True] as an invariant did the
job. So let's try it again here! I.e., let's instantiate [I] with
[True] in the skeleton above see what we get...
(1) {{ X = m /\ Y = n }} ->> (a - OK)
(2) {{ True }}
WHILE X <> 0 DO
(3) {{ True /\ X <> 0 }} ->> (c - OK)
(4) {{ True }}
Y ::= Y - 1;;
(5) {{ True }}
X ::= X - 1
(6) {{ True }}
END
(7) {{ True /\ X = 0 }} ->> (b - WRONG!)
(8) {{ Y = n - m }}
While conditions (a) and (c) are trivially satisfied,
condition (b) is wrong, i.e. it is not the case that (7) [True /\
X = 0] implies (8) [Y = n - m]. In fact, the two assertions are
completely unrelated and it is easy to find a counterexample (say,
[Y = X = m = 0] and [n = 1]).
If we want (b) to hold, we need to strengthen the invariant so
that it implies the postcondition (8). One very simple way to do
this is to let the invariant _be_ the postcondition. So let's
return to our skeleton, instantiate [I] with [Y = n - m], and
check conditions (a) to (c) again.
(1) {{ X = m /\ Y = n }} ->> (a - WRONG!)
(2) {{ Y = n - m }}
WHILE X <> 0 DO
(3) {{ Y = n - m /\ X <> 0 }} ->> (c - WRONG!)
(4) {{ Y - 1 = n - m }}
Y ::= Y - 1;;
(5) {{ Y = n - m }}
X ::= X - 1
(6) {{ Y = n - m }}
END
(7) {{ Y = n - m /\ X = 0 }} ->> (b - OK)
(8) {{ Y = n - m }}
This time, condition (b) holds trivially, but (a) and (c) are
broken. Condition (a) requires that (1) [X = m /\ Y = n]
implies (2) [Y = n - m]. If we substitute [Y] by [n] we have to
show that [n = n - m] for arbitrary [m] and [n], which does not
hold (for instance, when [m = n = 1]). Condition (c) requires that
[n - m - 1 = n - m], which fails, for instance, for [n = 1] and [m =
0]. So, although [Y = n - m] holds at the end of the loop, it does
not hold from the start, and it doesn't hold on each iteration;
it is not a correct invariant.
This failure is not very surprising: the variable [Y] changes
during the loop, while [m] and [n] are constant, so the assertion
we chose didn't have much chance of being an invariant!
To do better, we need to generalize (8) to some statement that is
equivalent to (8) when [X] is [0], since this will be the case
when the loop terminates, and that "fills the gap" in some
appropriate way when [X] is nonzero. Looking at how the loop
works, we can observe that [X] and [Y] are decremented together
until [X] reaches [0]. So, if [X = 2] and [Y = 5] initially,
after one iteration of the loop we obtain [X = 1] and [Y = 4];
after two iterations [X = 0] and [Y = 3]; and then the loop stops.
Notice that the difference between [Y] and [X] stays constant
between iterations; initially, [Y = n] and [X = m], so this
difference is always [n - m]. So let's try instantiating [I] in
the skeleton above with [Y - X = n - m].
(1) {{ X = m /\ Y = n }} ->> (a - OK)
(2) {{ Y - X = n - m }}
WHILE X <> 0 DO
(3) {{ Y - X = n - m /\ X <> 0 }} ->> (c - OK)
(4) {{ (Y - 1) - (X - 1) = n - m }}
Y ::= Y - 1;;
(5) {{ Y - (X - 1) = n - m }}
X ::= X - 1
(6) {{ Y - X = n - m }}
END
(7) {{ Y - X = n - m /\ X = 0 }} ->> (b - OK)
(8) {{ Y = n - m }}
Success! Conditions (a), (b) and (c) all hold now. (To
verify (c), we need to check that, under the assumption that [X <>
0], we have [Y - X = (Y - 1) - (X - 1)]; this holds for all
natural numbers [X] and [Y].) *)
(* ####################################################### *)
(** ** Exercise: Slow Assignment *)
(** **** Exercise: 2 stars (slow_assignment) *)
(** A roundabout way of assigning a number currently stored in [X] to
the variable [Y] is to start [Y] at [0], then decrement [X] until
it hits [0], incrementing [Y] at each step. Here is a program that
implements this idea:
{{ X = m }}
Y ::= 0;;
WHILE X <> 0 DO
X ::= X - 1;;
Y ::= Y + 1
END
{{ Y = m }}
Write an informal decorated program showing that this is correct. *)
(* FILL IN HERE *)
(** [] *)
(* ####################################################### *)
(** ** Exercise: Slow Addition *)
(** **** Exercise: 3 stars, optional (add_slowly_decoration) *)
(** The following program adds the variable X into the variable Z
by repeatedly decrementing X and incrementing Z.
WHILE X <> 0 DO
Z ::= Z + 1;;
X ::= X - 1
END
Following the pattern of the [subtract_slowly] example above, pick
a precondition and postcondition that give an appropriate
specification of [add_slowly]; then (informally) decorate the
program accordingly. *)
(* FILL IN HERE *)
(** [] *)
(* ####################################################### *)
(** ** Example: Parity *)
(** Here is a cute little program for computing the parity of the
value initially stored in [X] (due to Daniel Cristofani).
{{ X = m }}
WHILE 2 <= X DO
X ::= X - 2
END
{{ X = parity m }}
The mathematical [parity] function used in the specification is
defined in Coq as follows: *)
Fixpoint parity x :=
match x with
| 0 => 0
| 1 => 1
| S (S x') => parity x'
end.
(** The postcondition does not hold at the beginning of the loop,
since [m = parity m] does not hold for an arbitrary [m], so we
cannot use that as an invariant. To find an invariant that works,
let's think a bit about what this loop does. On each iteration it
decrements [X] by [2], which preserves the parity of [X]. So the
parity of [X] does not change, i.e. it is invariant. The initial
value of [X] is [m], so the parity of [X] is always equal to the
parity of [m]. Using [parity X = parity m] as an invariant we
obtain the following decorated program:
{{ X = m }} ->> (a - OK)
{{ parity X = parity m }}
WHILE 2 <= X DO
{{ parity X = parity m /\ 2 <= X }} ->> (c - OK)
{{ parity (X-2) = parity m }}
X ::= X - 2
{{ parity X = parity m }}
END
{{ parity X = parity m /\ X < 2 }} ->> (b - OK)
{{ X = parity m }}
With this invariant, conditions (a), (b), and (c) are all
satisfied. For verifying (b), we observe that, when [X < 2], we
have [parity X = X] (we can easily see this in the definition of
[parity]). For verifying (c), we observe that, when [2 <= X], we
have [parity X = parity (X-2)]. *)
(** **** Exercise: 3 stars, optional (parity_formal) *)
(** Translate this proof to Coq. Refer to the reduce-to-zero example
for ideas. You may find the following two lemmas useful: *)
Lemma parity_ge_2 : forall x,
2 <= x ->
parity (x - 2) = parity x.
Proof.
induction x; intro. reflexivity.
destruct x. inversion H. inversion H1.
simpl. rewrite <- minus_n_O. reflexivity.
Qed.
Lemma parity_lt_2 : forall x,
~ 2 <= x ->
parity (x) = x.
Proof.
intros. induction x. reflexivity. destruct x. reflexivity.
apply ex_falso_quodlibet. apply H. omega.
Qed.
Theorem parity_correct : forall m,
{{ fun st => st X = m }}
WHILE BLe (ANum 2) (AId X) DO
X ::= AMinus (AId X) (ANum 2)
END
{{ fun st => st X = parity m }}.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(* ####################################################### *)
(** ** Example: Finding Square Roots *)
(** The following program computes the square root of [X]
by naive iteration:
{{ X=m }}
Z ::= 0;;
WHILE (Z+1)*(Z+1) <= X DO
Z ::= Z+1
END
{{ Z*Z<=m /\ m<(Z+1)*(Z+1) }}
*)
(** As above, we can try to use the postcondition as a candidate
invariant, obtaining the following decorated program:
(1) {{ X=m }} ->> (a - second conjunct of (2) WRONG!)
(2) {{ 0*0 <= m /\ m<1*1 }}
Z ::= 0;;
(3) {{ Z*Z <= m /\ m<(Z+1)*(Z+1) }}
WHILE (Z+1)*(Z+1) <= X DO
(4) {{ Z*Z<=m /\ (Z+1)*(Z+1)<=X }} ->> (c - WRONG!)
(5) {{ (Z+1)*(Z+1)<=m /\ m<(Z+2)*(Z+2) }}
Z ::= Z+1
(6) {{ Z*Z<=m /\ m<(Z+1)*(Z+1) }}
END
(7) {{ Z*Z<=m /\ m<(Z+1)*(Z+1) /\ X<(Z+1)*(Z+1) }} ->> (b - OK)
(8) {{ Z*Z<=m /\ m<(Z+1)*(Z+1) }}
This didn't work very well: both conditions (a) and (c) failed.
Looking at condition (c), we see that the second conjunct of (4)
is almost the same as the first conjunct of (5), except that (4)
mentions [X] while (5) mentions [m]. But note that [X] is never
assigned in this program, so we should have [X=m], but we didn't
propagate this information from (1) into the loop invariant.
Also, looking at the second conjunct of (8), it seems quite
hopeless as an invariant -- and we don't even need it, since we
can obtain it from the negation of the guard (third conjunct
in (7)), again under the assumption that [X=m].
So we now try [X=m /\ Z*Z <= m] as the loop invariant:
{{ X=m }} ->> (a - OK)
{{ X=m /\ 0*0 <= m }}
Z ::= 0;
{{ X=m /\ Z*Z <= m }}
WHILE (Z+1)*(Z+1) <= X DO
{{ X=m /\ Z*Z<=m /\ (Z+1)*(Z+1)<=X }} ->> (c - OK)
{{ X=m /\ (Z+1)*(Z+1)<=m }}
Z ::= Z+1
{{ X=m /\ Z*Z<=m }}
END
{{ X=m /\ Z*Z<=m /\ X<(Z+1)*(Z+1) }} ->> (b - OK)
{{ Z*Z<=m /\ m<(Z+1)*(Z+1) }}
This works, since conditions (a), (b), and (c) are now all
trivially satisfied.
Very often, if a variable is used in a loop in a read-only
fashion (i.e., it is referred to by the program or by the
specification and it is not changed by the loop) it is necessary
to add the fact that it doesn't change to the loop invariant. *)
(* ####################################################### *)
(** ** Example: Squaring *)
(** Here is a program that squares [X] by repeated addition:
{{ X = m }}
Y ::= 0;;
Z ::= 0;;
WHILE Y <> X DO
Z ::= Z + X;;
Y ::= Y + 1
END
{{ Z = m*m }}
*)
(** The first thing to note is that the loop reads [X] but doesn't
change its value. As we saw in the previous example, in such cases
it is a good idea to add [X = m] to the invariant. The other thing
we often use in the invariant is the postcondition, so let's add
that too, leading to the invariant candidate [Z = m * m /\ X = m].
{{ X = m }} ->> (a - WRONG)
{{ 0 = m*m /\ X = m }}
Y ::= 0;;
{{ 0 = m*m /\ X = m }}
Z ::= 0;;
{{ Z = m*m /\ X = m }}
WHILE Y <> X DO
{{ Z = Y*m /\ X = m /\ Y <> X }} ->> (c - WRONG)
{{ Z+X = m*m /\ X = m }}
Z ::= Z + X;;
{{ Z = m*m /\ X = m }}
Y ::= Y + 1
{{ Z = m*m /\ X = m }}
END
{{ Z = m*m /\ X = m /\ Y = X }} ->> (b - OK)
{{ Z = m*m }}
Conditions (a) and (c) fail because of the [Z = m*m] part. While
[Z] starts at [0] and works itself up to [m*m], we can't expect
[Z] to be [m*m] from the start. If we look at how [Z] progesses
in the loop, after the 1st iteration [Z = m], after the 2nd
iteration [Z = 2*m], and at the end [Z = m*m]. Since the variable
[Y] tracks how many times we go through the loop, we derive the
new invariant candidate [Z = Y*m /\ X = m].
{{ X = m }} ->> (a - OK)
{{ 0 = 0*m /\ X = m }}
Y ::= 0;;
{{ 0 = Y*m /\ X = m }}
Z ::= 0;;
{{ Z = Y*m /\ X = m }}
WHILE Y <> X DO
{{ Z = Y*m /\ X = m /\ Y <> X }} ->> (c - OK)
{{ Z+X = (Y+1)*m /\ X = m }}
Z ::= Z + X;
{{ Z = (Y+1)*m /\ X = m }}
Y ::= Y + 1
{{ Z = Y*m /\ X = m }}
END
{{ Z = Y*m /\ X = m /\ Y = X }} ->> (b - OK)
{{ Z = m*m }}
This new invariant makes the proof go through: all three
conditions are easy to check.
It is worth comparing the postcondition [Z = m*m] and the [Z =
Y*m] conjunct of the invariant. It is often the case that one has
to replace auxiliary variabes (parameters) with variables -- or
with expressions involving both variables and parameters (like
[m - Y]) -- when going from postconditions to invariants. *)
(* ####################################################### *)
(** ** Exercise: Factorial *)
(** **** Exercise: 3 stars (factorial) *)
(** Recall that [n!] denotes the factorial of [n] (i.e. [n! =
1*2*...*n]). Here is an Imp program that calculates the factorial
of the number initially stored in the variable [X] and puts it in
the variable [Y]:
{{ X = m }}
Y ::= 1 ;;
WHILE X <> 0
DO
Y ::= Y * X ;;
X ::= X - 1
END
{{ Y = m! }}
Fill in the blanks in following decorated program:
{{ X = m }} ->>
{{ }}
Y ::= 1;;
{{ }}
WHILE X <> 0
DO {{ }} ->>
{{ }}
Y ::= Y * X;;
{{ }}
X ::= X - 1
{{ }}
END
{{ }} ->>
{{ Y = m! }}
*)
(** [] *)
(* ####################################################### *)
(** ** Exercise: Min *)
(** **** Exercise: 3 stars (Min_Hoare) *)
(** Fill in valid decorations for the following program.
For the => steps in your annotations, you may rely (silently) on the
following facts about min
Lemma lemma1 : forall x y,
(x=0 \/ y=0) -> min x y = 0.
Lemma lemma2 : forall x y,
min (x-1) (y-1) = (min x y) - 1.
plus, as usual, standard high-school algebra.
{{ True }} ->>
{{ }}
X ::= a;;
{{ }}
Y ::= b;;
{{ }}
Z ::= 0;;
{{ }}
WHILE (X <> 0 /\ Y <> 0) DO
{{ }} ->>
{{ }}
X := X - 1;;
{{ }}
Y := Y - 1;;
{{ }}
Z := Z + 1
{{ }}
END
{{ }} ->>
{{ Z = min a b }}
*)
(** [] *)
(** **** Exercise: 3 stars (two_loops) *)
(** Here is a very inefficient way of adding 3 numbers:
X ::= 0;;
Y ::= 0;;
Z ::= c;;
WHILE X <> a DO
X ::= X + 1;;
Z ::= Z + 1
END;;
WHILE Y <> b DO
Y ::= Y + 1;;
Z ::= Z + 1
END
Show that it does what it should by filling in the blanks in the
following decorated program.
{{ True }} ->>
{{ }}
X ::= 0;;
{{ }}
Y ::= 0;;
{{ }}
Z ::= c;;
{{ }}
WHILE X <> a DO
{{ }} ->>
{{ }}
X ::= X + 1;;
{{ }}
Z ::= Z + 1
{{ }}
END;;
{{ }} ->>
{{ }}
WHILE Y <> b DO
{{ }} ->>
{{ }}
Y ::= Y + 1;;
{{ }}
Z ::= Z + 1
{{ }}
END
{{ }} ->>
{{ Z = a + b + c }}
*)
(** [] *)
(* ####################################################### *)
(** ** Exercise: Power Series *)
(** **** Exercise: 4 stars, optional (dpow2_down) *)
(** Here is a program that computes the series:
[1 + 2 + 2^2 + ... + 2^m = 2^(m+1) - 1]
X ::= 0;;
Y ::= 1;;
Z ::= 1;;
WHILE X <> m DO
Z ::= 2 * Z;;
Y ::= Y + Z;;
X ::= X + 1
END
Write a decorated program for this. *)
(* FILL IN HERE *)
(* ####################################################### *)
(** * Weakest Preconditions (Advanced) *)
(** Some Hoare triples are more interesting than others.
For example,
{{ False }} X ::= Y + 1 {{ X <= 5 }}
is _not_ very interesting: although it is perfectly valid, it
tells us nothing useful. Since the precondition isn't satisfied
by any state, it doesn't describe any situations where we can use
the command [X ::= Y + 1] to achieve the postcondition [X <= 5].
By contrast,
{{ Y <= 4 /\ Z = 0 }} X ::= Y + 1 {{ X <= 5 }}
is useful: it tells us that, if we can somehow create a situation
in which we know that [Y <= 4 /\ Z = 0], then running this command
will produce a state satisfying the postcondition. However, this
triple is still not as useful as it could be, because the [Z = 0]
clause in the precondition actually has nothing to do with the
postcondition [X <= 5]. The _most_ useful triple (for a given
command and postcondition) is this one:
{{ Y <= 4 }} X ::= Y + 1 {{ X <= 5 }}
In other words, [Y <= 4] is the _weakest_ valid precondition of
the command [X ::= Y + 1] for the postcondition [X <= 5]. *)
(** In general, we say that "[P] is the weakest precondition of
command [c] for postcondition [Q]" if [{{P}} c {{Q}}] and if,
whenever [P'] is an assertion such that [{{P'}} c {{Q}}], we have
[P' st] implies [P st] for all states [st]. *)
Definition is_wp P c Q :=
{{P}} c {{Q}} /\
forall P', {{P'}} c {{Q}} -> (P' ->> P).
(** That is, [P] is the weakest precondition of [c] for [Q]
if (a) [P] _is_ a precondition for [Q] and [c], and (b) [P] is the
_weakest_ (easiest to satisfy) assertion that guarantees [Q] after
executing [c]. *)
(** **** Exercise: 1 star, optional (wp) *)
(** What are the weakest preconditions of the following commands
for the following postconditions?
1) {{ ? }} SKIP {{ X = 5 }}
2) {{ ? }} X ::= Y + Z {{ X = 5 }}
3) {{ ? }} X ::= Y {{ X = Y }}
4) {{ ? }}
IFB X == 0 THEN Y ::= Z + 1 ELSE Y ::= W + 2 FI
{{ Y = 5 }}
5) {{ ? }}
X ::= 5
{{ X = 0 }}
6) {{ ? }}
WHILE True DO X ::= 0 END
{{ X = 0 }}
*)
(* FILL IN HERE *)
(** [] *)
(** **** Exercise: 3 stars, advanced, optional (is_wp_formal) *)
(** Prove formally using the definition of [hoare_triple] that [Y <= 4]
is indeed the weakest precondition of [X ::= Y + 1] with respect to
postcondition [X <= 5]. *)
Theorem is_wp_example :
is_wp (fun st => st Y <= 4)
(X ::= APlus (AId Y) (ANum 1)) (fun st => st X <= 5).
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 2 stars, advanced (hoare_asgn_weakest) *)
(** Show that the precondition in the rule [hoare_asgn] is in fact the
weakest precondition. *)
Theorem hoare_asgn_weakest : forall Q X a,
is_wp (Q [X |-> a]) (X ::= a) Q.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 2 stars, advanced, optional (hoare_havoc_weakest) *)
(** Show that your [havoc_pre] rule from the [himp_hoare] exercise
in the [Hoare] chapter returns the weakest precondition. *)
Module Himp2.
Import Himp.
Lemma hoare_havoc_weakest : forall (P Q : Assertion) (X : id),
{{ P }} HAVOC X {{ Q }} ->
P ->> havoc_pre X Q.
Proof.
(* FILL IN HERE *) Admitted.
End Himp2.
(** [] *)
(* ####################################################### *)
(** * Formal Decorated Programs (Advanced) *)
(** The informal conventions for decorated programs amount to a way of
displaying Hoare triples in which commands are annotated with
enough embedded assertions that checking the validity of the
triple is reduced to simple logical and algebraic calculations
showing that some assertions imply others. In this section, we
show that this informal presentation style can actually be made
completely formal and indeed that checking the validity of
decorated programs can mostly be automated. *)
(** ** Syntax *)
(** The first thing we need to do is to formalize a variant of the
syntax of commands with embedded assertions. We call the new
commands _decorated commands_, or [dcom]s. *)
Inductive dcom : Type :=
| DCSkip : Assertion -> dcom
| DCSeq : dcom -> dcom -> dcom
| DCAsgn : id -> aexp -> Assertion -> dcom
| DCIf : bexp -> Assertion -> dcom -> Assertion -> dcom
-> Assertion-> dcom
| DCWhile : bexp -> Assertion -> dcom -> Assertion -> dcom
| DCPre : Assertion -> dcom -> dcom
| DCPost : dcom -> Assertion -> dcom.
Tactic Notation "dcom_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "Skip" | Case_aux c "Seq" | Case_aux c "Asgn"
| Case_aux c "If" | Case_aux c "While"
| Case_aux c "Pre" | Case_aux c "Post" ].
Notation "'SKIP' {{ P }}"
:= (DCSkip P)
(at level 10) : dcom_scope.
Notation "l '::=' a {{ P }}"
:= (DCAsgn l a P)
(at level 60, a at next level) : dcom_scope.
Notation "'WHILE' b 'DO' {{ Pbody }} d 'END' {{ Ppost }}"
:= (DCWhile b Pbody d Ppost)
(at level 80, right associativity) : dcom_scope.
Notation "'IFB' b 'THEN' {{ P }} d 'ELSE' {{ P' }} d' 'FI' {{ Q }}"
:= (DCIf b P d P' d' Q)
(at level 80, right associativity) : dcom_scope.
Notation "'->>' {{ P }} d"
:= (DCPre P d)
(at level 90, right associativity) : dcom_scope.
Notation "{{ P }} d"
:= (DCPre P d)
(at level 90) : dcom_scope.
Notation "d '->>' {{ P }}"
:= (DCPost d P)
(at level 80, right associativity) : dcom_scope.
Notation " d ;; d' "
:= (DCSeq d d')
(at level 80, right associativity) : dcom_scope.
Delimit Scope dcom_scope with dcom.
(** To avoid clashing with the existing [Notation] definitions
for ordinary [com]mands, we introduce these notations in a special
scope called [dcom_scope], and we wrap examples with the
declaration [% dcom] to signal that we want the notations to be
interpreted in this scope.
Careful readers will note that we've defined two notations for the
[DCPre] constructor, one with and one without a [->>]. The
"without" version is intended to be used to supply the initial
precondition at the very top of the program. *)
Example dec_while : dcom := (
{{ fun st => True }}
WHILE (BNot (BEq (AId X) (ANum 0)))
DO
{{ fun st => True /\ st X <> 0}}
X ::= (AMinus (AId X) (ANum 1))
{{ fun _ => True }}
END
{{ fun st => True /\ st X = 0}} ->>
{{ fun st => st X = 0 }}
) % dcom.
(** It is easy to go from a [dcom] to a [com] by erasing all
annotations. *)
Fixpoint extract (d:dcom) : com :=
match d with
| DCSkip _ => SKIP
| DCSeq d1 d2 => (extract d1 ;; extract d2)
| DCAsgn X a _ => X ::= a
| DCIf b _ d1 _ d2 _ => IFB b THEN extract d1 ELSE extract d2 FI
| DCWhile b _ d _ => WHILE b DO extract d END
| DCPre _ d => extract d
| DCPost d _ => extract d
end.
(** The choice of exactly where to put assertions in the definition of
[dcom] is a bit subtle. The simplest thing to do would be to
annotate every [dcom] with a precondition and postcondition. But
this would result in very verbose programs with a lot of repeated
annotations: for example, a program like [SKIP;SKIP] would have to
be annotated as
{{P}} ({{P}} SKIP {{P}}) ;; ({{P}} SKIP {{P}}) {{P}},
with pre- and post-conditions on each [SKIP], plus identical pre-
and post-conditions on the semicolon!
Instead, the rule we've followed is this:
- The _post_-condition expected by each [dcom] [d] is embedded in [d]
- The _pre_-condition is supplied by the context. *)
(** In other words, the invariant of the representation is that a
[dcom] [d] together with a precondition [P] determines a Hoare
triple [{{P}} (extract d) {{post d}}], where [post] is defined as
follows: *)
Fixpoint post (d:dcom) : Assertion :=
match d with
| DCSkip P => P
| DCSeq d1 d2 => post d2
| DCAsgn X a Q => Q
| DCIf _ _ d1 _ d2 Q => Q
| DCWhile b Pbody c Ppost => Ppost
| DCPre _ d => post d
| DCPost c Q => Q
end.
(** Similarly, we can extract the "initial precondition" from a
decorated program. *)
Fixpoint pre (d:dcom) : Assertion :=
match d with
| DCSkip P => fun st => True
| DCSeq c1 c2 => pre c1
| DCAsgn X a Q => fun st => True
| DCIf _ _ t _ e _ => fun st => True
| DCWhile b Pbody c Ppost => fun st => True
| DCPre P c => P
| DCPost c Q => pre c
end.
(** This function is not doing anything sophisticated like calculating
a weakest precondition; it just recursively searches for an
explicit annotation at the very beginning of the program,
returning default answers for programs that lack an explicit
precondition (like a bare assignment or [SKIP]). *)
(** Using [pre] and [post], and assuming that we adopt the convention
of always supplying an explicit precondition annotation at the
very beginning of our decorated programs, we can express what it
means for a decorated program to be correct as follows: *)
Definition dec_correct (d:dcom) :=
{{pre d}} (extract d) {{post d}}.
(** To check whether this Hoare triple is _valid_, we need a way to
extract the "proof obligations" from a decorated program. These
obligations are often called _verification conditions_, because
they are the facts that must be verified to see that the
decorations are logically consistent and thus add up to a complete
proof of correctness. *)
(** ** Extracting Verification Conditions *)
(** The function [verification_conditions] takes a [dcom] [d] together
with a precondition [P] and returns a _proposition_ that, if it
can be proved, implies that the triple [{{P}} (extract d) {{post d}}]
is valid. *)
(** It does this by walking over [d] and generating a big
conjunction including all the "local checks" that we listed when
we described the informal rules for decorated programs. (Strictly
speaking, we need to massage the informal rules a little bit to
add some uses of the rule of consequence, but the correspondence
should be clear.) *)
Fixpoint verification_conditions (P : Assertion) (d:dcom) : Prop :=
match d with
| DCSkip Q =>
(P ->> Q)
| DCSeq d1 d2 =>
verification_conditions P d1
/\ verification_conditions (post d1) d2
| DCAsgn X a Q =>
(P ->> Q [X |-> a])
| DCIf b P1 d1 P2 d2 Q =>
((fun st => P st /\ bassn b st) ->> P1)
/\ ((fun st => P st /\ ~ (bassn b st)) ->> P2)
/\ (Q <<->> post d1) /\ (Q <<->> post d2)
/\ verification_conditions P1 d1
/\ verification_conditions P2 d2
| DCWhile b Pbody d Ppost =>
(* post d is the loop invariant and the initial precondition *)
(P ->> post d)
/\ (Pbody <<->> (fun st => post d st /\ bassn b st))
/\ (Ppost <<->> (fun st => post d st /\ ~(bassn b st)))
/\ verification_conditions Pbody d
| DCPre P' d =>
(P ->> P') /\ verification_conditions P' d
| DCPost d Q =>
verification_conditions P d /\ (post d ->> Q)
end.
(** And now, the key theorem, which states that
[verification_conditions] does its job correctly. Not
surprisingly, we need to use each of the Hoare Logic rules at some
point in the proof. *)
(** We have used _in_ variants of several tactics before to
apply them to values in the context rather than the goal. An
extension of this idea is the syntax [tactic in *], which applies
[tactic] in the goal and every hypothesis in the context. We most
commonly use this facility in conjunction with the [simpl] tactic,
as below. *)
Theorem verification_correct : forall d P,
verification_conditions P d -> {{P}} (extract d) {{post d}}.
Proof.
dcom_cases (induction d) Case; intros P H; simpl in *.
Case "Skip".
eapply hoare_consequence_pre.
apply hoare_skip.
assumption.
Case "Seq".
inversion H as [H1 H2]. clear H.
eapply hoare_seq.
apply IHd2. apply H2.
apply IHd1. apply H1.
Case "Asgn".
eapply hoare_consequence_pre.
apply hoare_asgn.
assumption.
Case "If".
inversion H as [HPre1 [HPre2 [[Hd11 Hd12]
[[Hd21 Hd22] [HThen HElse]]]]].
clear H.
apply IHd1 in HThen. clear IHd1.
apply IHd2 in HElse. clear IHd2.
apply hoare_if.
eapply hoare_consequence_pre; eauto.
eapply hoare_consequence_post; eauto.
eapply hoare_consequence_pre; eauto.
eapply hoare_consequence_post; eauto.
Case "While".
inversion H as [Hpre [[Hbody1 Hbody2] [[Hpost1 Hpost2] Hd]]];
subst; clear H.
eapply hoare_consequence_pre; eauto.
eapply hoare_consequence_post; eauto.
apply hoare_while.
eapply hoare_consequence_pre; eauto.
Case "Pre".
inversion H as [HP Hd]; clear H.
eapply hoare_consequence_pre. apply IHd. apply Hd. assumption.
Case "Post".
inversion H as [Hd HQ]; clear H.
eapply hoare_consequence_post. apply IHd. apply Hd. assumption.
Qed.
(** ** Examples *)
(** The propositions generated by [verification_conditions] are fairly
big, and they contain many conjuncts that are essentially trivial. *)
Eval simpl in (verification_conditions (fun st => True) dec_while).
(**
==>
(((fun _ : state => True) ->> (fun _ : state => True)) /\
((fun _ : state => True) ->> (fun _ : state => True)) /\
(fun st : state => True /\ bassn (BNot (BEq (AId X) (ANum 0))) st) =
(fun st : state => True /\ bassn (BNot (BEq (AId X) (ANum 0))) st) /\
(fun st : state => True /\ ~ bassn (BNot (BEq (AId X) (ANum 0))) st) =
(fun st : state => True /\ ~ bassn (BNot (BEq (AId X) (ANum 0))) st) /\
(fun st : state => True /\ bassn (BNot (BEq (AId X) (ANum 0))) st) ->>
(fun _ : state => True) [X |-> AMinus (AId X) (ANum 1)]) /\
(fun st : state => True /\ ~ bassn (BNot (BEq (AId X) (ANum 0))) st) ->>
(fun st : state => st X = 0)
*)
(** In principle, we could certainly work with them using just the
tactics we have so far, but we can make things much smoother with
a bit of automation. We first define a custom [verify] tactic
that applies splitting repeatedly to turn all the conjunctions
into separate subgoals and then uses [omega] and [eauto] (a handy
general-purpose automation tactic that we'll discuss in detail
later) to deal with as many of them as possible. *)
Lemma ble_nat_true_iff : forall n m : nat,
ble_nat n m = true <-> n <= m.
Proof.
intros n m. split. apply ble_nat_true.
generalize dependent m. induction n; intros m H. reflexivity.
simpl. destruct m. inversion H.
apply le_S_n in H. apply IHn. assumption.
Qed.
Lemma ble_nat_false_iff : forall n m : nat,
ble_nat n m = false <-> ~(n <= m).
Proof.
intros n m. split. apply ble_nat_false.
generalize dependent m. induction n; intros m H.
apply ex_falso_quodlibet. apply H. apply le_0_n.
simpl. destruct m. reflexivity.
apply IHn. intro Hc. apply H. apply le_n_S. assumption.
Qed.
Tactic Notation "verify" :=
apply verification_correct;
repeat split;
simpl; unfold assert_implies;
unfold bassn in *; unfold beval in *; unfold aeval in *;
unfold assn_sub; intros;
repeat rewrite update_eq;
repeat (rewrite update_neq; [| (intro X; inversion X)]);
simpl in *;
repeat match goal with [H : _ /\ _ |- _] => destruct H end;
repeat rewrite not_true_iff_false in *;
repeat rewrite not_false_iff_true in *;
repeat rewrite negb_true_iff in *;
repeat rewrite negb_false_iff in *;
repeat rewrite beq_nat_true_iff in *;
repeat rewrite beq_nat_false_iff in *;
repeat rewrite ble_nat_true_iff in *;
repeat rewrite ble_nat_false_iff in *;
try subst;
repeat
match goal with
[st : state |- _] =>
match goal with
[H : st _ = _ |- _] => rewrite -> H in *; clear H
| [H : _ = st _ |- _] => rewrite <- H in *; clear H
end
end;
try eauto; try omega.
(** What's left after [verify] does its thing is "just the interesting
parts" of checking that the decorations are correct. For very
simple examples [verify] immediately solves the goal (provided
that the annotations are correct). *)
Theorem dec_while_correct :
dec_correct dec_while.
Proof. verify. Qed.
(** Another example (formalizing a decorated program we've seen
before): *)
Example subtract_slowly_dec (m:nat) (p:nat) : dcom := (
{{ fun st => st X = m /\ st Z = p }} ->>
{{ fun st => st Z - st X = p - m }}
WHILE BNot (BEq (AId X) (ANum 0))
DO {{ fun st => st Z - st X = p - m /\ st X <> 0 }} ->>
{{ fun st => (st Z - 1) - (st X - 1) = p - m }}
Z ::= AMinus (AId Z) (ANum 1)
{{ fun st => st Z - (st X - 1) = p - m }} ;;
X ::= AMinus (AId X) (ANum 1)
{{ fun st => st Z - st X = p - m }}
END
{{ fun st => st Z - st X = p - m /\ st X = 0 }} ->>
{{ fun st => st Z = p - m }}
) % dcom.
Theorem subtract_slowly_dec_correct : forall m p,
dec_correct (subtract_slowly_dec m p).
Proof. intros m p. verify. (* this grinds for a bit! *) Qed.
(** **** Exercise: 3 stars, advanced (slow_assignment_dec) *)
(** In the [slow_assignment] exercise above, we saw a roundabout way
of assigning a number currently stored in [X] to the variable [Y]:
start [Y] at [0], then decrement [X] until it hits [0],
incrementing [Y] at each step.
Write a _formal_ version of this decorated program and prove it
correct. *)
Example slow_assignment_dec (m:nat) : dcom :=
(* FILL IN HERE *) admit.
Theorem slow_assignment_dec_correct : forall m,
dec_correct (slow_assignment_dec m).
Proof. (* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 4 stars, advanced (factorial_dec) *)
(** Remember the factorial function we worked with before: *)
Fixpoint real_fact (n:nat) : nat :=
match n with
| O => 1
| S n' => n * (real_fact n')
end.
(** Following the pattern of [subtract_slowly_dec], write a decorated
program [factorial_dec] that implements the factorial function and
prove it correct as [factorial_dec_correct]. *)
(* FILL IN HERE *)
(** [] *)
(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)
|
//Legal Notice: (C)2016 Altera Corporation. All rights reserved. Your
//use of Altera Corporation's design tools, logic functions and other
//software and tools, and its AMPP partner logic functions, and any
//output files any of the foregoing (including device programming or
//simulation files), and any associated documentation or information are
//expressly subject to the terms and conditions of the Altera Program
//License Subscription Agreement or other applicable license agreement,
//including, without limitation, that your use is for the sole purpose
//of programming logic devices manufactured by Altera and sold by Altera
//or its authorized distributors. Please refer to the applicable
//agreement for further details.
// synthesis translate_off
`timescale 1ns / 1ps
// synthesis translate_on
// turn off superfluous verilog processor warnings
// altera message_level Level1
// altera message_off 10034 10035 10036 10037 10230 10240 10030
module niosii_onchip_memory2_0 (
// inputs:
address,
byteenable,
chipselect,
clk,
clken,
reset,
reset_req,
write,
writedata,
// outputs:
readdata
)
;
parameter INIT_FILE = "niosii_onchip_memory2_0.hex";
output [ 31: 0] readdata;
input [ 13: 0] address;
input [ 3: 0] byteenable;
input chipselect;
input clk;
input clken;
input reset;
input reset_req;
input write;
input [ 31: 0] writedata;
wire clocken0;
wire [ 31: 0] readdata;
wire wren;
assign wren = chipselect & write;
assign clocken0 = clken & ~reset_req;
altsyncram the_altsyncram
(
.address_a (address),
.byteena_a (byteenable),
.clock0 (clk),
.clocken0 (clocken0),
.data_a (writedata),
.q_a (readdata),
.wren_a (wren)
);
defparam the_altsyncram.byte_size = 8,
the_altsyncram.init_file = INIT_FILE,
the_altsyncram.lpm_type = "altsyncram",
the_altsyncram.maximum_depth = 12000,
the_altsyncram.numwords_a = 12000,
the_altsyncram.operation_mode = "SINGLE_PORT",
the_altsyncram.outdata_reg_a = "UNREGISTERED",
the_altsyncram.ram_block_type = "AUTO",
the_altsyncram.read_during_write_mode_mixed_ports = "DONT_CARE",
the_altsyncram.width_a = 32,
the_altsyncram.width_byteena_a = 4,
the_altsyncram.widthad_a = 14;
//s1, which is an e_avalon_slave
//s2, which is an e_avalon_slave
endmodule
|
//Legal Notice: (C)2016 Altera Corporation. All rights reserved. Your
//use of Altera Corporation's design tools, logic functions and other
//software and tools, and its AMPP partner logic functions, and any
//output files any of the foregoing (including device programming or
//simulation files), and any associated documentation or information are
//expressly subject to the terms and conditions of the Altera Program
//License Subscription Agreement or other applicable license agreement,
//including, without limitation, that your use is for the sole purpose
//of programming logic devices manufactured by Altera and sold by Altera
//or its authorized distributors. Please refer to the applicable
//agreement for further details.
// synthesis translate_off
`timescale 1ns / 1ps
// synthesis translate_on
// turn off superfluous verilog processor warnings
// altera message_level Level1
// altera message_off 10034 10035 10036 10037 10230 10240 10030
module niosii_onchip_memory2_0 (
// inputs:
address,
byteenable,
chipselect,
clk,
clken,
reset,
reset_req,
write,
writedata,
// outputs:
readdata
)
;
parameter INIT_FILE = "niosii_onchip_memory2_0.hex";
output [ 31: 0] readdata;
input [ 13: 0] address;
input [ 3: 0] byteenable;
input chipselect;
input clk;
input clken;
input reset;
input reset_req;
input write;
input [ 31: 0] writedata;
wire clocken0;
wire [ 31: 0] readdata;
wire wren;
assign wren = chipselect & write;
assign clocken0 = clken & ~reset_req;
altsyncram the_altsyncram
(
.address_a (address),
.byteena_a (byteenable),
.clock0 (clk),
.clocken0 (clocken0),
.data_a (writedata),
.q_a (readdata),
.wren_a (wren)
);
defparam the_altsyncram.byte_size = 8,
the_altsyncram.init_file = INIT_FILE,
the_altsyncram.lpm_type = "altsyncram",
the_altsyncram.maximum_depth = 12000,
the_altsyncram.numwords_a = 12000,
the_altsyncram.operation_mode = "SINGLE_PORT",
the_altsyncram.outdata_reg_a = "UNREGISTERED",
the_altsyncram.ram_block_type = "AUTO",
the_altsyncram.read_during_write_mode_mixed_ports = "DONT_CARE",
the_altsyncram.width_a = 32,
the_altsyncram.width_byteena_a = 4,
the_altsyncram.widthad_a = 14;
//s1, which is an e_avalon_slave
//s2, which is an e_avalon_slave
endmodule
|
module ghrd_10m50da_top (
//Clock and Reset
input wire clk_50,
input wire fpga_reset_n,
//QSPI
// output wire qspi_clk,
// inout wire[3:0] qspi_io,
// output wire qspi_csn,
//16550 UART
input wire uart_rx,
output wire uart_tx,
output wire [4:0] user_led
);
//Heart-beat counter
reg [25:0] heart_beat_cnt;
// SoC sub-system module
ghrd_10m50da ghrd_10m50da_inst (
.clk_clk (clk_50),
.reset_reset_n (fpga_reset_n),
// .ext_flash_flash_dataout_conduit_dataout (qspi_io),
// .ext_flash_flash_dclk_out_conduit_dclk_out (qspi_clk),
// .ext_flash_flash_ncs_conduit_ncs (qspi_csn),
//16550 UART
.a_16550_uart_0_rs_232_serial_sin (uart_rx), // a_16550_uart_0_rs_232_serial.sin
.a_16550_uart_0_rs_232_serial_sout (uart_tx), // .sout
.a_16550_uart_0_rs_232_serial_sout_oe () // .sout_oe
);
//Heart beat by 50MHz clock
always @(posedge clk_50 or negedge fpga_reset_n)
if (!fpga_reset_n)
heart_beat_cnt <= 26'h0; //0x3FFFFFF
else
heart_beat_cnt <= heart_beat_cnt + 1'b1;
assign user_led = {4'hf,heart_beat_cnt[25]};
endmodule
|
//-----------------------------------------------------------------------------
// The way that we connect things in low-frequency read mode. In this case
// we are generating the unmodulated low frequency carrier.
// The A/D samples at that same rate and the result is serialized.
//
// Jonathan Westhues, April 2006
// iZsh <izsh at fail0verflow.com>, June 2014
//-----------------------------------------------------------------------------
module lo_read(
input pck0, input [7:0] pck_cnt, input pck_divclk,
output pwr_lo, output pwr_hi,
output pwr_oe1, output pwr_oe2, output pwr_oe3, output pwr_oe4,
input [7:0] adc_d, output adc_clk,
output ssp_frame, output ssp_din, output ssp_clk,
output dbg,
input lf_field
);
reg [7:0] to_arm_shiftreg;
// this task also runs at pck0 frequency (24Mhz) and is used to serialize
// the ADC output which is then clocked into the ARM SSP.
// because pck_divclk always transitions when pck_cnt = 0 we use the
// pck_div counter to sync our other signals off it
// we read the ADC value when pck_cnt=7 and shift it out on counts 8..15
always @(posedge pck0)
begin
if((pck_cnt == 8'd7) && !pck_divclk)
to_arm_shiftreg <= adc_d;
else begin
to_arm_shiftreg[7:1] <= to_arm_shiftreg[6:0];
// simulation showed a glitch occuring due to the LSB of the shifter
// not being set as we shift bits out
// this ensures the ssp_din remains low after a transfer and suppresses
// the glitch that would occur when the last data shifted out ended in
// a 1 bit and the next data shifted out started with a 0 bit
to_arm_shiftreg[0] <= 1'b0;
end
end
// ADC samples on falling edge of adc_clk, data available on the rising edge
// example of ssp transfer of binary value 1100101
// start of transfer is indicated by the rise of the ssp_frame signal
// ssp_din changes on the rising edge of the ssp_clk clock and is clocked into
// the ARM by the falling edge of ssp_clk
// _______________________________
// ssp_frame__| |__
// _______ ___ ___
// ssp_din __| |_______| |___| |______
// _ _ _ _ _ _ _ _ _ _
// ssp_clk |_| |_| |_| |_| |_| |_| |_| |_| |_| |_
// serialized SSP data is gated by ant_lo to suppress unwanted signal
assign ssp_din = to_arm_shiftreg[7] && !pck_divclk;
// SSP clock always runs at 24Mhz
assign ssp_clk = pck0;
// SSP frame is gated by ant_lo and goes high when pck_divider=8..15
assign ssp_frame = (pck_cnt[7:3] == 5'd1) && !pck_divclk;
// unused signals tied low
assign pwr_hi = 1'b0;
assign pwr_oe1 = 1'b0;
assign pwr_oe2 = 1'b0;
assign pwr_oe3 = 1'b0;
assign pwr_oe4 = 1'b0;
// this is the antenna driver signal
assign pwr_lo = lf_field & pck_divclk;
// ADC clock out of phase with antenna driver
assign adc_clk = ~pck_divclk;
// ADC clock also routed to debug pin
assign dbg = adc_clk;
endmodule
|
//-----------------------------------------------------------------------------
// The way that we connect things in low-frequency read mode. In this case
// we are generating the unmodulated low frequency carrier.
// The A/D samples at that same rate and the result is serialized.
//
// Jonathan Westhues, April 2006
// iZsh <izsh at fail0verflow.com>, June 2014
//-----------------------------------------------------------------------------
module lo_read(
input pck0, input [7:0] pck_cnt, input pck_divclk,
output pwr_lo, output pwr_hi,
output pwr_oe1, output pwr_oe2, output pwr_oe3, output pwr_oe4,
input [7:0] adc_d, output adc_clk,
output ssp_frame, output ssp_din, output ssp_clk,
output dbg,
input lf_field
);
reg [7:0] to_arm_shiftreg;
// this task also runs at pck0 frequency (24Mhz) and is used to serialize
// the ADC output which is then clocked into the ARM SSP.
// because pck_divclk always transitions when pck_cnt = 0 we use the
// pck_div counter to sync our other signals off it
// we read the ADC value when pck_cnt=7 and shift it out on counts 8..15
always @(posedge pck0)
begin
if((pck_cnt == 8'd7) && !pck_divclk)
to_arm_shiftreg <= adc_d;
else begin
to_arm_shiftreg[7:1] <= to_arm_shiftreg[6:0];
// simulation showed a glitch occuring due to the LSB of the shifter
// not being set as we shift bits out
// this ensures the ssp_din remains low after a transfer and suppresses
// the glitch that would occur when the last data shifted out ended in
// a 1 bit and the next data shifted out started with a 0 bit
to_arm_shiftreg[0] <= 1'b0;
end
end
// ADC samples on falling edge of adc_clk, data available on the rising edge
// example of ssp transfer of binary value 1100101
// start of transfer is indicated by the rise of the ssp_frame signal
// ssp_din changes on the rising edge of the ssp_clk clock and is clocked into
// the ARM by the falling edge of ssp_clk
// _______________________________
// ssp_frame__| |__
// _______ ___ ___
// ssp_din __| |_______| |___| |______
// _ _ _ _ _ _ _ _ _ _
// ssp_clk |_| |_| |_| |_| |_| |_| |_| |_| |_| |_
// serialized SSP data is gated by ant_lo to suppress unwanted signal
assign ssp_din = to_arm_shiftreg[7] && !pck_divclk;
// SSP clock always runs at 24Mhz
assign ssp_clk = pck0;
// SSP frame is gated by ant_lo and goes high when pck_divider=8..15
assign ssp_frame = (pck_cnt[7:3] == 5'd1) && !pck_divclk;
// unused signals tied low
assign pwr_hi = 1'b0;
assign pwr_oe1 = 1'b0;
assign pwr_oe2 = 1'b0;
assign pwr_oe3 = 1'b0;
assign pwr_oe4 = 1'b0;
// this is the antenna driver signal
assign pwr_lo = lf_field & pck_divclk;
// ADC clock out of phase with antenna driver
assign adc_clk = ~pck_divclk;
// ADC clock also routed to debug pin
assign dbg = adc_clk;
endmodule
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.