/*
 * ESP32-C3 USB Serial JTAG emulation
 *
 * Copyright (c) 2023 Espressif Systems (Shanghai) Co. Ltd.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 or
 * (at your option) any later version.
 */
#include "qemu/osdep.h"
#include "qemu/log.h"
#include "qemu/module.h"
#include "qemu/error-report.h"
#include "hw/hw.h"
#include "hw/sysbus.h"
#include "hw/misc/esp32c3_jtag.h"


/* USB Serial JTAG Console Tap - The firmware routes ESP-IDF console output (incl. panic dumps) through this peripheral. EP1 is the byte FIFO; EP1_CONF bit1 (SERIAL_IN_EP_DATA_FREE) must read set so the driver believes the TX FIFO can always accept a byte. */
#define ESP32C3_JTAG_EP1_REG       0x00
#define ESP32C3_JTAG_EP1_CONF_REG  0x04
#define ESP32C3_JTAG_IN_EP_DATA_FREE (1u << 1)

static uint64_t esp32c3_jtag_read(void *opaque, hwaddr addr, unsigned int size)
{
    ESP32C3UsbJtagState *s = ESP32C3_JTAG(opaque);
    (void) s;
    if (addr == ESP32C3_JTAG_EP1_CONF_REG) {
        return ESP32C3_JTAG_IN_EP_DATA_FREE;
    }
    return 0;
}

static void esp32c3_jtag_write(void *opaque, hwaddr addr, uint64_t value, unsigned int size)
{
    ESP32C3UsbJtagState *s = ESP32C3_JTAG(opaque);
    (void) s;
    if (addr == ESP32C3_JTAG_EP1_REG) {
        fputc((int)(value & 0xff), stderr);
    }
}

static const MemoryRegionOps esp32c3_jtag_ops = {
    .read =  esp32c3_jtag_read,
    .write = esp32c3_jtag_write,
    .endianness = DEVICE_LITTLE_ENDIAN,
};

static void esp32c3_jtag_reset_hold(Object *obj, ResetType type)
{
    (void) obj;
    (void) type;
}

static void esp32c3_jtag_realize(DeviceState *dev, Error **errp)
{
    (void) dev;
    (void) errp;
}

static void esp32c3_jtag_init(Object *obj)
{
    ESP32C3UsbJtagState *s = ESP32C3_JTAG(obj);
    SysBusDevice *sbd = SYS_BUS_DEVICE(obj);

    memory_region_init_io(&s->iomem, obj, &esp32c3_jtag_ops, s,
                          TYPE_ESP32C3_JTAG, ESP32C3_JTAG_REGS_SIZE);
    sysbus_init_mmio(sbd, &s->iomem);
}

static void esp32c3_jtag_class_init(ObjectClass *klass, void *data)
{
    DeviceClass *dc = DEVICE_CLASS(klass);
    ResettableClass *rc = RESETTABLE_CLASS(klass);

    rc->phases.hold = esp32c3_jtag_reset_hold;
    dc->realize = esp32c3_jtag_realize;
}

static const TypeInfo esp32c3_jtag_info = {
    .name = TYPE_ESP32C3_JTAG,
    .parent = TYPE_SYS_BUS_DEVICE,
    .instance_size = sizeof(ESP32C3UsbJtagState),
    .instance_init = esp32c3_jtag_init,
    .class_init = esp32c3_jtag_class_init
};

static void esp32c3_jtag_types(void)
{
    type_register_static(&esp32c3_jtag_info);
}

type_init(esp32c3_jtag_types)
