Files
mlkem-sync/sync_rtl/comp_decomp/comp_decomp_sync.v

106 lines
3.6 KiB
Verilog

// comp_decomp_sync.v - ML-KEM coefficient compression/decompression
//
// Streaming valid/ready interface. Compression is intentionally iterative to
// avoid inferring a long combinational divider for /Q.
// mode=0: compress — round((2^d * x) / Q) mod 2^d
// mode=1: decompress — round((Q * x) / 2^d)
// Uses round-half-up (round(2.5)=3, round(3.5)=4).
// Integer arithmetic:
// compress: (x * 2^d + Q/2) / Q, lower d bits as result
// decompress: (x * Q + 2^(d-1)) / 2^d, result (always < Q)
`include "sync_rtl/common/defines.vh"
(* use_dsp = "no" *)
module comp_decomp_sync (
input clk,
input rst_n,
input [11:0] coeff_in,
input [4:0] d,
input mode, // 0=compress, 1=decompress
input valid_i,
output ready_o,
output [11:0] coeff_out,
output valid_o,
input ready_i
);
localparam [11:0] Q_VAL = 12'(`Q);
localparam [4:0] COMP_MSB = 5'd22; // max ((Q-1)<<11)+Q/2 is 23 bits
reg busy_r;
reg [4:0] bit_idx_r;
reg [4:0] d_r;
reg [23:0] dividend_r;
reg [23:0] quotient_r;
reg [12:0] rem_r;
reg [11:0] data_r;
reg valid_r;
wire fire_i = valid_i && ready_o;
// Accept a new command only when the iterative divider and output slot are
// both free. Current users tie ready_i high and issue one coefficient at a
// time, but this keeps the module from accepting work it cannot retain.
assign ready_o = !busy_r && (!valid_r || ready_i);
assign coeff_out = data_r;
assign valid_o = valid_r;
wire [23:0] comp_dividend = ({12'd0, coeff_in} << d) + 24'd1664;
wire [23:0] decomp_product =
{12'd0, coeff_in} +
({12'd0, coeff_in} << 8) +
({12'd0, coeff_in} << 10) +
({12'd0, coeff_in} << 11);
wire [23:0] decomp_rounded = decomp_product + (24'd1 << (d - 1'b1));
wire [11:0] decomp_result = decomp_rounded >> d;
wire [12:0] rem_shift = {rem_r[11:0], dividend_r[bit_idx_r]};
wire rem_ge_q = rem_shift >= {1'b0, Q_VAL};
wire [12:0] rem_sub_q = rem_shift - {1'b0, Q_VAL};
wire [12:0] rem_next = rem_ge_q ? rem_sub_q : rem_shift;
wire [23:0] quot_next = quotient_r | (rem_ge_q ? (24'd1 << bit_idx_r) : 24'd0);
wire [11:0] comp_mask = (12'd1 << d_r) - 12'd1;
always @(posedge clk or negedge rst_n) begin
if (!rst_n) begin
busy_r <= 1'b0;
bit_idx_r <= 5'd0;
d_r <= 5'd0;
dividend_r <= 24'd0;
quotient_r <= 24'd0;
rem_r <= 13'd0;
data_r <= 12'd0;
valid_r <= 1'b0;
end else begin
if (valid_r && ready_i)
valid_r <= 1'b0;
if (busy_r) begin
rem_r <= rem_next;
quotient_r <= quot_next;
if (bit_idx_r == 5'd0) begin
busy_r <= 1'b0;
data_r <= quot_next[11:0] & comp_mask;
valid_r <= 1'b1;
end else begin
bit_idx_r <= bit_idx_r - 5'd1;
end
end else if (fire_i) begin
if (mode) begin
data_r <= decomp_result;
valid_r <= 1'b1;
end else begin
busy_r <= 1'b1;
bit_idx_r <= COMP_MSB;
d_r <= d;
dividend_r <= comp_dividend;
quotient_r <= 24'd0;
rem_r <= 13'd0;
end
end
end
end
endmodule