#include "common-app.h"

void
init (void)
{
  REGS->mailboxes.mboxout = 0;

  /* Enable scrubber */
  SUPERVISOR->scrub_cfg = HYDRA_SUPERVISOR_REGS_SCRUB_CFG_IRAM_EN
    | HYDRA_SUPERVISOR_REGS_SCRUB_CFG_DRAM_EN;
}

void
main (void)
{
  unsigned mbi = REGS->mailboxes.mboxin;  /* written by mgmt */
  unsigned mbo = REGS->mailboxes.mboxout; /* written by app */
  unsigned rwslot = (mbi >> 8) & 0xff; /* Remote slots (read from). */
  unsigned rrslot = mbo & 0xff;
  unsigned lwslot = (mbo >> 8) & 0xff; /* Local slots (write to).  */
  unsigned lrslot = mbi & 0xff;
  unsigned lnslot = (lwslot + 1) & 3;
  volatile uint32_t *src;
  volatile uint32_t *dst;
  unsigned i;

  /* Watchdog */
  SUPERVISOR->wd_key = WD_KEY;

  /* Maybe nothing to read. */
  if (rrslot == rwslot) {
    REGS->mailboxes.mboxout = (mbo & 0xffff) | (1 << 28);
    return;
  }

  if (lnslot == lrslot) {
    /* No free slot, skip. */
    REGS->mailboxes.mboxout = (mbo & 0xffff) | (2 << 28);
    return;
  }

  src = &REGS->sh_mem[rrslot << 5];
  dst = &REGS->sh_mem[128 + (lwslot << 5)];

  *dst = *src ^ 0x0f;

  for (i = 1; i < 124 / 4; i++)
    dst[i] = src[i] + 0x02020202;

  REGS->mailboxes.mboxout = (mbo + 0x101) & 0xffff0303;
}
