/*
 * newlib system calls that are not about files: heap, debug output,
 * time, process. Files and directories are in fs.c.
 */
#include <errno.h>
#include <reent.h>
#include <stddef.h>
#include <stdint.h>
#include <sys/time.h>
#include <sys/times.h>
#include <time.h>

#include <xbox360/xboxkrnl.h>
/* xam.h is not included: its socket types clash with newlib. */
extern void XamLoaderTerminateTitle(void) __attribute__((noreturn));

#include "xex_runtime.h"

/* VOID XNotifyQueueUI(DWORD Type, DWORD UserIndex, ULONGLONG Areas,
 * PCWSTR Text, PVOID Context): Areas is one register in the console ABI,
 * so it is passed as a 32-bit value (see extra_imports.S). */
extern void XNotifyQueueUI(uint32_t type, uint32_t user, uint32_t areas,
                           const uint16_t *text, void *context);

/* ------------------------------------------------------------------------ */
/* Heap: a .bss arena (the loader commits it with the image).               */

#ifndef XEX_HEAP_SIZE
#define XEX_HEAP_SIZE (96 * 1024 * 1024)
#endif
static char heap[XEX_HEAP_SIZE] __attribute__((aligned(64)));
static size_t heap_used;

void *_sbrk_r(struct _reent *r, ptrdiff_t incr)
{
    if (incr < 0 || heap_used + (size_t)incr > XEX_HEAP_SIZE) {
        r->_errno = ENOMEM;
        return (void *)-1;
    }
    void *p = heap + heap_used;
    heap_used += (size_t)incr;
    return p;
}

/* ------------------------------------------------------------------------ */
/* Debug output and notifications                                           */

void xex_debug_write(const void *buf, size_t len)
{
    char tmp[257];
    size_t done = 0;
    while (done < len) {
        size_t n = len - done > 256 ? 256 : len - done;
        for (size_t i = 0; i < n; i++) tmp[i] = ((const char *)buf)[done + i];
        tmp[n] = 0;
        DbgPrint("%s", tmp);
        done += n;
    }
}

void xex_notify(const char *text)
{
    uint16_t wide[128];
    size_t n = 0;
    for (; text[n] && n < 127; n++) wide[n] = (uint8_t)text[n];
    wide[n] = 0;
    XNotifyQueueUI(14 /* XNOTIFYUI_TYPE_PREFERRED_REVIEW */, 0, 2 /* high priority */, wide, NULL);
}

/* ------------------------------------------------------------------------ */
/* Time                                                                     */

uint64_t xex_timebase(void)
{
    uint64_t tb;
    __asm__ volatile("mftb %0" : "=r"(tb));   /* 64-bit register */
    return tb;
}

uint64_t xex_timebase_freq(void)
{
    static uint64_t freq;
    if (!freq) freq = KeQueryPerformanceFrequency();
    return freq ? freq : 49875000ull;
}

void xex_sleep_ms(unsigned ms)
{
    LARGE_INTEGER interval;
    interval.QuadPart = -(LONGLONG)ms * 10000;   /* relative, 100 ns units */
    KeDelayExecutionThread(1 /* UserMode */, FALSE, &interval);
}

int _gettimeofday_r(struct _reent *r, struct timeval *tv, void *tz)
{
    (void)r; (void)tz;
    LARGE_INTEGER now;
    KeQuerySystemTime(&now);   /* 100 ns since 1601-01-01 */
    long long us = (now.QuadPart - 116444736000000000LL) / 10;
    tv->tv_sec = (time_t)(us / 1000000);
    tv->tv_usec = (suseconds_t)(us % 1000000);
    return 0;
}

clock_t _times_r(struct _reent *r, struct tms *buf)
{
    (void)r;
    clock_t t = (clock_t)(xex_timebase() / (xex_timebase_freq() / CLOCKS_PER_SEC));
    if (buf) {
        buf->tms_utime = t;
        buf->tms_stime = 0;
        buf->tms_cutime = 0;
        buf->tms_cstime = 0;
    }
    return t;
}

int usleep(useconds_t us)
{
    xex_sleep_ms((unsigned)((us + 999) / 1000));
    return 0;
}

/* ------------------------------------------------------------------------ */
/* Process                                                                  */

int _kill_r(struct _reent *r, int pid, int sig)
{
    (void)pid; (void)sig;
    r->_errno = EINVAL;
    return -1;
}

int _getpid_r(struct _reent *r)
{
    (void)r;
    return 1;
}

void _exit(int status)
{
    (void)status;
    XamLoaderTerminateTitle();
}
