`timescale 1ns / 1ns

// ------------------------------------
// Interlock monitoring
//
// All intlk_foo registers are built with
//   bit 0:  Internal PLL lock fault
//   bit 1:  EPICS timeout
//   bit 2:  fault reported from rectl chassis
//   bit 3:  link failure on fiber from resctl chassis
//   bit 4:  SSA TTL status line
//   bit 5:  Quench detect
//
// Inputs wired through newad
//
// Single-clock-domain logic,
// all inputs _must_ be qualified in that domain.

module interlock_mon
(
   input clk,

   // Interlock controls
   input [5:0] byp,   // external
   input [5:0] reset, // external single-cycle

   // Interlock inputs
   input pll_ok,
   input epics_timeout,
   input resctl_permit,
   input resctl_link_fault,
   input ssa_fault,
   input rfs_quench,

   // Interlock outputs
   output [5:0] intlk_fault, // Current fault when '1'
   output [5:0] intlk_latch, // Latched fault when '1'
   output [5:0] intlk_firstf, // First fault indication
   output       intlk_trig   // Single-cycle start-of-fault indicator
);
   localparam PLL_NLOCK    = 0;
   localparam EPICS_TOUT   = 1;
   localparam RESCTL_FAULT = 2;
   localparam RESCTL_LINK  = 3;
   localparam SSA_FAULT    = 4;
   localparam RFS_QUENCH   = 5;

   wire [5:0] intlk_fault_l, intlk_fault_masked;
   reg  [5:0] intlk_mask;
   reg  [5:0] intlk_latch_l=0, intlk_firstf_l=0;

   assign intlk_fault_l[PLL_NLOCK]    = ~pll_ok;
   assign intlk_fault_l[EPICS_TOUT]   = epics_timeout;
   assign intlk_fault_l[RESCTL_FAULT] = ~resctl_permit;
   assign intlk_fault_l[RESCTL_LINK]  = resctl_link_fault;
   assign intlk_fault_l[SSA_FAULT]    = ssa_fault;
   assign intlk_fault_l[RFS_QUENCH]   = rfs_quench;

   assign intlk_fault_masked = intlk_fault_l & intlk_mask;

   always @(byp) begin
      intlk_mask = ~byp;
      intlk_mask[PLL_NLOCK] = 1; // can't mask clock fault
   end

   always @(posedge clk) begin
      intlk_latch_l <= (intlk_latch_l & ~reset) | intlk_fault_masked;

      // Latch faults as we first go from non-fault to fault
      if (intlk_latch_l==0 && intlk_fault_masked!=0)
         intlk_firstf_l <= intlk_fault_masked;
      else
         intlk_firstf_l <= intlk_firstf_l & ~reset;
   end

   // Create single-cycle event when interlocks fire
   reg intlk_summary=0, intlk_trig_l=0;
   wire intlk_latch_any = |intlk_latch_l;
   always @(posedge clk) begin
      intlk_summary <= intlk_latch_any;
      intlk_trig_l <= intlk_latch_any & ~intlk_summary;  // rising edge detect
   end

   assign intlk_fault = intlk_fault_l;
   assign intlk_latch = intlk_latch_l;
   assign intlk_firstf = intlk_firstf_l;
   assign intlk_trig = intlk_trig_l;

endmodule
