/*
 * 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 <init.h>
#include <init/ps1/types.h>
#include <drv/ps1/bios.h>
#include <drv/ps1/cpu.h>
#include <drv/ps1/rcnt.h>
#include <drv/ps1/time.h>
#include <time.h>

int init_time(void)
{
    struct timespec ts;
    const union drv_ps1_rcnt_cfg cfg =
    {
        .bits =
        {
            .reset = 1,
            .repeat = 1,
            .irq_tgt = 1,
            .clocksrc = 3
        }
    };

    if (clock_getres(CLOCK_REALTIME, &ts))
        return -1;

    const uint16_t target = (DRV_PS1_CPU_F / 8) / (ts.tv_nsec / 1000);

    return drv_ps1_rcnt_init(DRV_PS1_RCNT2, target, &cfg, drv_ps1_time_tick);
}
