/*
 * wnix, a Unix-like operating system for WebAssembly applications.
 * Copyright (C) 2025  Xavier Del Campo Romero
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

#include <drv/ps1/sio.h>
#include <drv/ps1/sio/ops.h>
#include <drv/ps1/sio/regs.h>
#include <drv/ps1/sio/routines.h>
#include <drv/ps1/sio/types.h>
#include <drv/ps1/bios.h>
#include <drv/ps1/cpu.h>
#include <drv/ps1/irq.h>
#include <drv/event.h>

int irq_sio_overrun;

static int read_rx(struct sio_fifo *const f)
{
    const unsigned char v = *SIO_RX_DATA->values;
    size_t n = f->pend + 1;

    if (n >= sizeof f->buf)
        n = 0;

    if (n == f->proc)
    {
        irq_sio_overrun = 1;
        return -1;
    }

    f->buf[f->pend = n] = v;
    return 0;
}

volatile unsigned sio_read;
volatile int sw_overrun;

int drv_ps1_sio_irq(void)
{
    SIO_CTRL->bits.rts = 0;

    while (SIO_STAT->bits.rx_fifo_not_empty)
    {
        if (read_rx(&drv_ps1_sio.rx))
        {
            sw_overrun = 1;
            break;
        }

        sio_read++;
    }

    SIO_CTRL->bits.rts = 1;
    I_STAT->bits.sio = 0;
    SIO_CTRL->bits.ack = 1;
    return 0;
}
