/*
 * 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/time.h>
#include <drv/ps1/time/types.h>
#include <drv/ps1/irq.h>
#include <time.h>

int drv_ps1_time_tick(void)
{
    int ret = 0;
    struct timespec ts;
    volatile struct timespec *const t = &drv_ps1_time;

    if (clock_getres(CLOCK_REALTIME, &ts))
        ret = -1;
    else if (t->tv_nsec >= 1000000000 - ts.tv_nsec)
    {
        t->tv_sec++;
        t->tv_nsec = 0;
    }
    else
        t->tv_nsec += ts.tv_nsec;

    I_STAT->bits.tmr2 = 0;
    return ret;
}
