-------------------------------------------------------------------------------
--
-- Copyright 2022
-- ASTRON (Netherlands Institute for Radio Astronomy) <http://www.astron.nl/>
-- P.O.Box 2, 7990 AA Dwingeloo, The Netherlands
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
--     http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-------------------------------------------------------------------------------
-- Author: Job van Wee
-- Purpose: Create address by counting input valids
--
-- Description:
--  The counter starts on the first valid = '1' clockcylce, the counter stops 
--  when valid = '0'.
--
-- Remark:
--  Use VHDL coding template from:
--  https://support.astron.nl/confluence/display/SBe/VHDL+design+patterns+for+RTL+coding
--  The maximum value of the address is determend by g_tech_ddr.

LIBRARY IEEE, technology_lib, tech_ddr_lib, common_lib, dp_lib;
USE IEEE.std_logic_1164.ALL;
USE IEEE.numeric_std.ALL;
USE technology_lib.technology_pkg.ALL;
USE tech_ddr_lib.tech_ddr_pkg.ALL;
USE common_lib.common_pkg.ALL;
USE common_lib.common_mem_pkg.ALL;
USE dp_lib.dp_stream_pkg.ALL;


ENTITY ddrctrl_address_counter IS
  GENERIC (
    g_tech_ddr        : t_c_tech_ddr;
    g_sim_model       : BOOLEAN := TRUE
  );
  PORT (
    clk               : IN  STD_LOGIC;
    rst               : IN  STD_LOGIC;
    in_sosi           : IN  t_dp_sosi;
    out_mosi          : OUT t_mem_ctlr_mosi
  );
END ddrctrl_address_counter;


ARCHITECTURE rtl OF ddrctrl_address_counter IS

  CONSTANT c_data_w   : NATURAL := func_tech_ddr_ctlr_data_w( g_tech_ddr ); --576
  CONSTANT c_adr_w    : NATURAL := sel_a_b(g_sim_model, 4, func_tech_ddr_ctlr_address_w( g_tech_ddr )); --27;
  CONSTANT c_max_adr  : NATURAL := 2**(c_adr_w) - 1;

  SIGNAL   s_adr      : NATURAL range 0 to 2**(c_adr_w)-1 := 0;

BEGIN

  out_mosi.wrdata(c_data_w - 1 DOWNTO 0) <= in_sosi.data(c_data_w - 1 DOWNTO 0);
  out_mosi.wr                            <= in_sosi.valid;
  out_mosi.address(c_adr_w -1 DOWNTO 0)  <= TO_UVEC(s_adr, c_adr_w);

  p_clk : PROCESS(clk)
  BEGIN
    IF rising_edge(clk) THEN
      IF rst = '1' THEN
        s_adr <= 0;
      ELSIF in_sosi.valid = '1' THEN
        IF (s_adr = c_max_adr) THEN
          s_adr <= 0;
        ELSE
          s_adr <= s_adr + 1;
        END IF;
      END IF;
    END IF;
  END PROCESS;

END rtl;