/*
 * QEMU PowerPC CHRP (Genesi/bPlan Pegasos II) hardware System Emulator
 *
 * Copyright (c) 2018-2020 BALATON Zoltan
 *
 * This work is licensed under the GNU GPL license version 2 or later.
 *
 */

#include "qemu/osdep.h"
#include "qemu-common.h"
#include "qemu/units.h"
#include "qapi/error.h"
#include "hw/hw.h"
#include "hw/ppc/ppc.h"
#include "hw/sysbus.h"
#include "hw/pci/pci_host.h"
#include "hw/irq.h"
#include "hw/isa/vt82c686.h"
#include "hw/isa/superio.h"
#include "hw/ide/pci.h"
#include "hw/i2c/pm_smbus.h"
#include "hw/i2c/smbus_eeprom.h"
#include "hw/dma/i8257.h"
#include "hw/timer/i8254.h"
#include "hw/rtc/mc146818rtc.h"
#include "net/net.h"
#include "sysemu/reset.h"
#include "hw/boards.h"
#include "hw/loader.h"
#include "hw/fw-path-provider.h"
#include "elf.h"
#include "qemu/log.h"
#include "qemu/error-report.h"
#include "sysemu/kvm.h"
#include "kvm_ppc.h"
#include "hw/intc/i8259.h"
#include "exec/address-spaces.h"
#include "trace.h"

/* ------------------------------------------------------------------------- */
/* Marvell Discovery II MV64361 System Controller */

/* mv64361.h */

#include "mv643xx.h"

static void mv64361_pcibridge_class_init(ObjectClass *klass, void *data)
{
    DeviceClass *dc = DEVICE_CLASS(klass);
    PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);

    k->vendor_id = PCI_VENDOR_ID_MARVELL;
    k->device_id = 0x6460;
    k->class_id = PCI_CLASS_BRIDGE_HOST;
    /*
     * PCI-facing part of the host bridge,
     * not usable without the host-facing part
     */
    dc->user_creatable = false;
}

static const TypeInfo mv64361_pcibridge_info = {
    .name          = "mv64361-pcibridge",
    .parent        = TYPE_PCI_DEVICE,
    .instance_size = sizeof(PCIDevice),
    .class_init    = mv64361_pcibridge_class_init,
    .interfaces = (InterfaceInfo[]) {
        { INTERFACE_CONVENTIONAL_PCI_DEVICE },
        { },
    },
};

#define TYPE_MV64361_PCI "mv64361-pcihost"
#define MV64361_PCI(obj) OBJECT_CHECK(MV64361PCIState, (obj), TYPE_MV64361_PCI)

typedef struct MV64361PCIState {
    PCIHostState parent_obj;

    uint8_t index;
    MemoryRegion io;
    MemoryRegion mem;
    qemu_irq irq[4];

    uint32_t io_base;
    uint32_t io_size;
    uint32_t mem_base[4];
    uint32_t mem_size[4];
    uint64_t remap[5];
} MV64361PCIState;

static int mv64361_pcihost_map_irq(PCIDevice *pci_dev, int n)
{
    return (n + PCI_SLOT(pci_dev->devfn) - 1) % 4;
}

static void mv64361_pcihost_set_irq(void *opaque, int n, int level)
{
    MV64361PCIState *s = opaque;

    qemu_set_irq(s->irq[n], level);
}

static void mv64361_pcihost_realize(DeviceState *dev, Error **errp)
{
    MV64361PCIState *s = MV64361_PCI(dev);
    PCIHostState *h = PCI_HOST_BRIDGE(dev);
    char *name;

    name = g_strdup_printf("pci%d-io", s->index);
    memory_region_init(&s->io, OBJECT(dev), name, 0x10000);
    g_free(name);
    name = g_strdup_printf("pci%d-mem", s->index);
    memory_region_init(&s->mem, OBJECT(dev), name, 1ULL << 32);
    g_free(name);
    name = g_strdup_printf("pci.%d", s->index);
    h->bus = pci_register_root_bus(dev, name, mv64361_pcihost_set_irq,
                                   mv64361_pcihost_map_irq, dev,
                                   &s->mem, &s->io, 0, 4, TYPE_PCI_BUS);
    g_free(name);
    pci_create_simple(h->bus, 0, "mv64361-pcibridge");
}

static Property mv64361_pcihost_props[] = {
    DEFINE_PROP_UINT8("index", MV64361PCIState, index, 0),
    DEFINE_PROP_END_OF_LIST()
};

static void mv64361_pcihost_class_init(ObjectClass *klass, void *data)
{
    DeviceClass *dc = DEVICE_CLASS(klass);

    dc->realize = mv64361_pcihost_realize;
    device_class_set_props(dc, mv64361_pcihost_props);
    set_bit(DEVICE_CATEGORY_BRIDGE, dc->categories);
}

static const TypeInfo mv64361_pcihost_info = {
       .name          = TYPE_MV64361_PCI,
       .parent        = TYPE_PCI_HOST_BRIDGE,
       .instance_size = sizeof(MV64361PCIState),
       .class_init    = mv64361_pcihost_class_init,
};

static void mv64361_pci_register_types(void)
{
   type_register_static(&mv64361_pcihost_info);
   type_register_static(&mv64361_pcibridge_info);
}

type_init(mv64361_pci_register_types)

#define TYPE_MV64361 "mv64361"
#define MV64361(obj) OBJECT_CHECK(MV64361State, (obj), TYPE_MV64361)

typedef struct MV64361State {
    SysBusDevice parent_obj;

    MemoryRegion regs;
    MV64361PCIState pci[2];
    MemoryRegion cpu_win[19];
    qemu_irq cpu_irq;

    /* registers state */
    uint32_t cpu_conf;
    uint32_t regs_base;
    uint32_t base_addr_enable;
    uint64_t main_int_cr;
    uint64_t cpu0_int_mask;
    uint32_t gpp_io;
    uint32_t gpp_level;
    uint32_t gpp_value;
    uint32_t gpp_int_cr;
    uint32_t gpp_int_mask;
    bool gpp_int_level;
} MV64361State;

/* mv64361.c */

enum mv64361_irq_cause {
    MV64361_IRQ_DEVERR = 1,
    MV64361_IRQ_DMAERR,
    MV64361_IRQ_CPUERR,
    MV64361_IRQ_IDMA0,
    MV64361_IRQ_IDMA1,
    MV64361_IRQ_IDMA2,
    MV64361_IRQ_IDMA3,
    MV64361_IRQ_TIMER0,
    MV64361_IRQ_TIMER1,
    MV64361_IRQ_TIMER2,
    MV64361_IRQ_TIMER3,
    MV64361_IRQ_PCI0,
    MV64361_IRQ_SRAMERR,
    MV64361_IRQ_GBEERR,
    MV64361_IRQ_CERR,
    MV64361_IRQ_PCI1,
    MV64361_IRQ_DRAMERR,
    MV64361_IRQ_WDNMI,
    MV64361_IRQ_WDE,
    MV64361_IRQ_PCI0IN,
    MV64361_IRQ_PCI0OUT,
    MV64361_IRQ_PCI1IN,
    MV64361_IRQ_PCI1OUT,
    MV64361_IRQ_P1_GPP0_7,
    MV64361_IRQ_P1_GPP8_15,
    MV64361_IRQ_P1_GPP16_23,
    MV64361_IRQ_P1_GPP24_31,
    MV64361_IRQ_P1_CPU_DB,
    /* 29-31: reserved */
    MV64361_IRQ_GBE0 = 32,
    MV64361_IRQ_GBE1,
    MV64361_IRQ_GBE2,
    /* 35: reserved */
    MV64361_IRQ_SDMA0 = 36,
    MV64361_IRQ_TWSI,
    MV64361_IRQ_SDMA1,
    MV64361_IRQ_BRG,
    MV64361_IRQ_MPSC0,
    MV64361_IRQ_MPSC1,
    MV64361_IRQ_G0RX,
    MV64361_IRQ_G0TX,
    MV64361_IRQ_G0MISC,
    MV64361_IRQ_G1RX,
    MV64361_IRQ_G1TX,
    MV64361_IRQ_G1MISC,
    MV64361_IRQ_G2RX,
    MV64361_IRQ_G2TX,
    MV64361_IRQ_G2MISC,
    /* 51-55: reserved */
    MV64361_IRQ_P0_GPP0_7 = 56,
    MV64361_IRQ_P0_GPP8_15,
    MV64361_IRQ_P0_GPP16_23,
    MV64361_IRQ_P0_GPP24_31,
    MV64361_IRQ_P0_CPU_DB,
    /* 61-63: reserved */
};

static void unmap_region(MemoryRegion *mr)
{
    if (memory_region_is_mapped(mr)) {
        memory_region_del_subregion(get_system_memory(), mr);
        object_unparent(OBJECT(mr));
    }
}

static void map_pci_region(MemoryRegion *mr, MemoryRegion *parent,
                           struct Object *owner, const char *name,
                           hwaddr poffs, uint64_t size, hwaddr moffs)
{
    memory_region_init_alias(mr, owner, name, parent, poffs, size);
    memory_region_add_subregion(get_system_memory(), moffs, mr);
    printf("Mapping %s 0x%"HWADDR_PRIx"+0x%"PRIx64" @ 0x%"HWADDR_PRIx"\n", name, poffs, size, moffs);
}

static void setup_mem_windows(MV64361State *s, uint32_t val)
{
    MV64361PCIState *p;
    MemoryRegion *mr;
    uint32_t mask;
    int i;

    val &= 0x1fffff;
    for (mask = 1, i = 0; i < 21; i++, mask <<= 1) {
        if ((val & mask) != (s->base_addr_enable & mask)) {
            printf("%s: Should %s region %d\n", __func__, (!(val & mask) ? "enable" : "disable"), i);
            switch (i) {
            /*
             * 0-3 are SDRAM chip selects but we map all RAM directly
             * 4-7 are device chip selects (not sure what those are)
             * 8 is Boot device (ROM) chip select but we map that directly too
             */
            case 9:
                p = &s->pci[0];
                mr = &s->cpu_win[i];
                unmap_region(mr);
                if (!(val & mask)) {
                    map_pci_region(mr, &p->io, OBJECT(s), "pci0-io-win",
                                   p->remap[4], (p->io_size + 1) << 16,
                                   (p->io_base & 0xfffff) << 16);
                }
                break;
            case 10:
                p = &s->pci[0];
                mr = &s->cpu_win[i];
                unmap_region(mr);
                if (!(val & mask)) {
                    map_pci_region(mr, &p->mem, OBJECT(s), "pci0-mem0-win",
                                   p->remap[0], (p->mem_size[0] + 1) << 16,
                                   (p->mem_base[0] & 0xfffff) << 16);
                }
                break;
            case 11:
                p = &s->pci[0];
                mr = &s->cpu_win[i];
                unmap_region(mr);
                if (!(val & mask)) {
                    map_pci_region(mr, &p->mem, OBJECT(s), "pci0-mem1-win",
                                   p->remap[1], (p->mem_size[1] + 1) << 16,
                                   (p->mem_base[1] & 0xfffff) << 16);
                }
                break;
            case 12:
                p = &s->pci[0];
                mr = &s->cpu_win[i];
                unmap_region(mr);
                if (!(val & mask)) {
                    map_pci_region(mr, &p->mem, OBJECT(s), "pci0-mem2-win",
                                   p->remap[2], (p->mem_size[2] + 1) << 16,
                                   (p->mem_base[2] & 0xfffff) << 16);
                }
                break;
            case 13:
                p = &s->pci[0];
                mr = &s->cpu_win[i];
                unmap_region(mr);
                if (!(val & mask)) {
                    map_pci_region(mr, &p->mem, OBJECT(s), "pci0-mem3-win",
                                   p->remap[3], (p->mem_size[3] + 1) << 16,
                                   (p->mem_base[3] & 0xfffff) << 16);
                }
                break;
            case 14:
                p = &s->pci[1];
                mr = &s->cpu_win[i];
                unmap_region(mr);
                if (!(val & mask)) {
                    map_pci_region(mr, &p->io, OBJECT(s), "pci1-io-win",
                                   p->remap[4], (p->io_size + 1) << 16,
                                   (p->io_base & 0xfffff) << 16);
                }
                break;
            case 15:
                p = &s->pci[1];
                mr = &s->cpu_win[i];
                unmap_region(mr);
                if (!(val & mask)) {
                    map_pci_region(mr, &p->mem, OBJECT(s), "pci1-mem0-win",
                                   p->remap[0], (p->mem_size[0] + 1) << 16,
                                   (p->mem_base[0] & 0xfffff) << 16);
                }
                break;
            case 16:
                p = &s->pci[1];
                mr = &s->cpu_win[i];
                unmap_region(mr);
                if (!(val & mask)) {
                    map_pci_region(mr, &p->mem, OBJECT(s), "pci1-mem1-win",
                                   p->remap[1], (p->mem_size[1] + 1) << 16,
                                   (p->mem_base[1] & 0xfffff) << 16);
                }
                break;
            case 17:
                p = &s->pci[1];
                mr = &s->cpu_win[i];
                unmap_region(mr);
                if (!(val & mask)) {
                    map_pci_region(mr, &p->mem, OBJECT(s), "pci1-mem2-win",
                                   p->remap[2], (p->mem_size[2] + 1) << 16,
                                   (p->mem_base[2] & 0xfffff) << 16);
                }
                break;
            case 18:
                p = &s->pci[1];
                mr = &s->cpu_win[i];
                unmap_region(mr);
                if (!(val & mask)) {
                    map_pci_region(mr, &p->mem, OBJECT(s), "pci1-mem3-win",
                                   p->remap[3], (p->mem_size[3] + 1) << 16,
                                   (p->mem_base[3] & 0xfffff) << 16);
                }
                break;
            /* 19 is integrated SRAM */
            case 20:
                mr = &s->regs;
                unmap_region(mr);
                if (!(val & mask)) {
                    memory_region_add_subregion(get_system_memory(),
                        (s->regs_base & 0xfffff) << 16, mr);
                }
                break;
            }
        }
    }
}

static void mv64361_update_irq(void *opaque, int n, int level)
{
    MV64361State *s = opaque;
    uint64_t val = s->main_int_cr;

    if (level) {
        val |= BIT_ULL(n);
    } else {
        val &= ~BIT_ULL(n);
    }
    if ((s->main_int_cr & s->cpu0_int_mask) != (val & s->cpu0_int_mask)) {
        qemu_set_irq(s->cpu_irq, level);
    }
    s->main_int_cr = val;
}

static uint64_t mv64361_read(void *opaque, hwaddr addr, unsigned int size)
{
    MV64361State *s = MV64361(opaque);
    uint32_t ret = 0;

    switch (addr) {
    case MV64340_CPU_CONFIG:
        ret = s->cpu_conf;
        break;
    case MV64340_PCI_0_IO_BASE_ADDR:
        ret = s->pci[0].io_base;
        break;
    case MV64340_PCI_0_IO_SIZE:
        ret = s->pci[0].io_size;
        break;
    case MV64340_PCI_0_IO_ADDR_REMAP:
        ret = s->pci[0].remap[4] >> 16;
        break;
    case MV64340_PCI_0_MEMORY0_BASE_ADDR:
        ret = s->pci[0].mem_base[0];
        break;
    case MV64340_PCI_0_MEMORY0_SIZE:
        ret = s->pci[0].mem_size[0];
        break;
    case MV64340_PCI_0_MEMORY0_LOW_ADDR_REMAP:
        ret = (s->pci[0].remap[0] & 0xffff0000) >> 16;
        break;
    case MV64340_PCI_0_MEMORY0_HIGH_ADDR_REMAP:
        ret = s->pci[0].remap[0] >> 32;
        break;
    case MV64340_PCI_0_MEMORY1_BASE_ADDR:
        ret = s->pci[0].mem_base[1];
        break;
    case MV64340_PCI_0_MEMORY1_SIZE:
        ret = s->pci[0].mem_size[1];
        break;
    case MV64340_PCI_0_MEMORY1_LOW_ADDR_REMAP:
        ret = (s->pci[0].remap[1] & 0xffff0000) >> 16;
        break;
    case MV64340_PCI_0_MEMORY1_HIGH_ADDR_REMAP:
        ret = s->pci[0].remap[1] >> 32;
        break;
    case MV64340_PCI_0_MEMORY2_BASE_ADDR:
        ret = s->pci[0].mem_base[2];
        break;
    case MV64340_PCI_0_MEMORY2_SIZE:
        ret = s->pci[0].mem_size[2];
        break;
    case MV64340_PCI_0_MEMORY2_LOW_ADDR_REMAP:
        ret = (s->pci[0].remap[2] & 0xffff0000) >> 16;
        break;
    case MV64340_PCI_0_MEMORY2_HIGH_ADDR_REMAP:
        ret = s->pci[0].remap[2] >> 32;
        break;
    case MV64340_PCI_0_MEMORY3_BASE_ADDR:
        ret = s->pci[0].mem_base[3];
        break;
    case MV64340_PCI_0_MEMORY3_SIZE:
        ret = s->pci[0].mem_size[3];
        break;
    case MV64340_PCI_0_MEMORY3_LOW_ADDR_REMAP:
        ret = (s->pci[0].remap[3] & 0xffff0000) >> 16;
        break;
    case MV64340_PCI_0_MEMORY3_HIGH_ADDR_REMAP:
        ret = s->pci[0].remap[3] >> 32;
        break;
    case MV64340_PCI_1_IO_BASE_ADDR:
        ret = s->pci[1].io_base;
        break;
    case MV64340_PCI_1_IO_SIZE:
        ret = s->pci[1].io_size;
        break;
    case MV64340_PCI_1_IO_ADDR_REMAP:
        ret = s->pci[1].remap[4] >> 16;
        break;
    case MV64340_PCI_1_MEMORY0_BASE_ADDR:
        ret = s->pci[1].mem_base[0];
        break;
    case MV64340_PCI_1_MEMORY0_SIZE:
        ret = s->pci[1].mem_size[0];
        break;
    case MV64340_PCI_1_MEMORY0_LOW_ADDR_REMAP:
        ret = (s->pci[1].remap[0] & 0xffff0000) >> 16;
        break;
    case MV64340_PCI_1_MEMORY0_HIGH_ADDR_REMAP:
        ret = s->pci[1].remap[0] >> 32;
        break;
    case MV64340_PCI_1_MEMORY1_BASE_ADDR:
        ret = s->pci[1].mem_base[1];
        break;
    case MV64340_PCI_1_MEMORY1_SIZE:
        ret = s->pci[1].mem_size[1];
        break;
    case MV64340_PCI_1_MEMORY1_LOW_ADDR_REMAP:
        ret = (s->pci[1].remap[1] & 0xffff0000) >> 16;
        break;
    case MV64340_PCI_1_MEMORY1_HIGH_ADDR_REMAP:
        ret = s->pci[1].remap[1] >> 32;
        break;
    case MV64340_PCI_1_MEMORY2_BASE_ADDR:
        ret = s->pci[1].mem_base[2];
        break;
    case MV64340_PCI_1_MEMORY2_SIZE:
        ret = s->pci[1].mem_size[2];
        break;
    case MV64340_PCI_1_MEMORY2_LOW_ADDR_REMAP:
        ret = (s->pci[1].remap[2] & 0xffff0000) >> 16;
        break;
    case MV64340_PCI_1_MEMORY2_HIGH_ADDR_REMAP:
        ret = s->pci[1].remap[2] >> 32;
        break;
    case MV64340_PCI_1_MEMORY3_BASE_ADDR:
        ret = s->pci[1].mem_base[3];
        break;
    case MV64340_PCI_1_MEMORY3_SIZE:
        ret = s->pci[1].mem_size[3];
        break;
    case MV64340_PCI_1_MEMORY3_LOW_ADDR_REMAP:
        ret = (s->pci[1].remap[3] & 0xffff0000) >> 16;
        break;
    case MV64340_PCI_1_MEMORY3_HIGH_ADDR_REMAP:
        ret = s->pci[1].remap[3] >> 32;
        break;
    case MV64340_INTERNAL_SPACE_BASE_ADDR:
        ret = s->regs_base;
        break;
    case MV64340_BASE_ADDR_ENABLE:
        ret = s->base_addr_enable;
        break;
    case MV64340_PCI_0_CONFIG_ADDR:
        ret = pci_host_conf_le_ops.read(PCI_HOST_BRIDGE(&s->pci[0]), 0, size);
        break;
    case MV64340_PCI_0_CONFIG_DATA_VIRTUAL_REG ...
         MV64340_PCI_0_CONFIG_DATA_VIRTUAL_REG + 3:
        ret = pci_host_data_le_ops.read(PCI_HOST_BRIDGE(&s->pci[0]),
                  addr - MV64340_PCI_0_CONFIG_DATA_VIRTUAL_REG, size);
        break;
    case MV64340_PCI_1_CONFIG_ADDR:
        ret = pci_host_conf_le_ops.read(PCI_HOST_BRIDGE(&s->pci[1]), 0, size);
        break;
    case MV64340_PCI_1_CONFIG_DATA_VIRTUAL_REG ...
         MV64340_PCI_1_CONFIG_DATA_VIRTUAL_REG + 3:
        ret = pci_host_data_le_ops.read(PCI_HOST_BRIDGE(&s->pci[1]),
                  addr - MV64340_PCI_1_CONFIG_DATA_VIRTUAL_REG, size);
        break;
    case MV64340_PCI_1_INTERRUPT_ACKNOWLEDGE_VIRTUAL_REG:
        /* FIXME: This should be sent via the PCI bus? */
        if (s->gpp_int_level && (s->gpp_value & BIT(31))) {
            ret = pic_read_irq(isa_pic);
        }
        break;
    case MV64340_MAIN_INTERRUPT_CAUSE_LOW:
        ret = s->main_int_cr;
        break;
    case MV64340_MAIN_INTERRUPT_CAUSE_HIGH:
        ret = s->main_int_cr >> 32;
        break;
    case MV64340_CPU_INTERRUPT0_MASK_LOW:
        ret = s->cpu0_int_mask;
        break;
    case MV64340_CPU_INTERRUPT0_MASK_HIGH:
        ret = s->cpu0_int_mask >> 32;
        break;
    case MV64340_CPU_INTERRUPT0_SELECT_CAUSE:
        ret = s->main_int_cr;
        if (s->main_int_cr & s->cpu0_int_mask) {
            if (!(s->main_int_cr & s->cpu0_int_mask & 0xffffffff)) {
                ret = s->main_int_cr >> 32 | BIT(30);
            } else if ((s->main_int_cr & s->cpu0_int_mask) >> 32) {
                ret |= BIT(31);
            }
        }
        break;
    case MV64340_CUNIT_ARBITER_CONTROL_REG:
        ret = 0x11ff0000 | (s->gpp_int_level << 10);
        break;
    case MV64340_GPP_IO_CONTROL:
        ret = s->gpp_io;
        break;
    case MV64340_GPP_LEVEL_CONTROL:
        ret = s->gpp_level;
        break;
    case MV64340_GPP_VALUE:
        ret = s->gpp_value;
        break;
    case MV64340_GPP_VALUE_SET:
    case MV64340_GPP_VALUE_CLEAR:
        ret = 0;
        break;
    case MV64340_GPP_INTERRUPT_CAUSE:
        ret = s->gpp_int_cr;
        break;
    case MV64340_GPP_INTERRUPT_MASK0:
    case MV64340_GPP_INTERRUPT_MASK1:
        ret = s->gpp_int_mask;
        break;
    default:
        qemu_log_mask(LOG_UNIMP, "%s: Unimplemented register read 0x%"
                      HWADDR_PRIx "\n", __func__, addr);
        break;
    }
    if (addr != MV64340_PCI_1_INTERRUPT_ACKNOWLEDGE_VIRTUAL_REG) {
        printf("%s: %"PRIx64" -> %x\n", __func__, addr, ret);
    }
    return ret;
}

static void warn_swap_bit(uint64_t val)
{
    if ((val & 0x3000000ULL) >> 24 != 1) {
        qemu_log_mask(LOG_UNIMP, "%s: Data swap not implemented", __func__);
    }
}

static void mv64361_set_pci_mem_remap(MV64361State *s, int bus, int idx,
                                      uint64_t val, bool high)
{
    if (high) {
        s->pci[bus].remap[idx] = val;
    } else {
        s->pci[bus].remap[idx] &= 0xffffffff00000000ULL;
        s->pci[bus].remap[idx] |= (val & 0xffffULL) << 16;
    }
}

static void mv64361_write(void *opaque, hwaddr addr, uint64_t val,
                          unsigned int size)
{
    MV64361State *s = MV64361(opaque);

    printf("%s: %"PRIx64" <- %"PRIx64"\n", __func__, addr, val);
    switch (addr) {
    case MV64340_CPU_CONFIG:
        s->cpu_conf = val & 0xe4e3bffULL;
        s->cpu_conf |= BIT(23);
        break;
    case MV64340_PCI_0_IO_BASE_ADDR:
        s->pci[0].io_base = val & 0x30fffffULL;
        warn_swap_bit(val);
        if (!(s->cpu_conf & BIT(27))) {
            s->pci[0].remap[4] = (val & 0xffffULL) << 16;
        }
        break;
    case MV64340_PCI_0_IO_SIZE:
        s->pci[0].io_size = val & 0xffffULL;
        break;
    case MV64340_PCI_0_IO_ADDR_REMAP:
        s->pci[0].remap[4] = (val & 0xffffULL) << 16;
        break;
    case MV64340_PCI_0_MEMORY0_BASE_ADDR:
        s->pci[0].mem_base[0] = val & 0x70fffffULL;
        warn_swap_bit(val);
        if (!(s->cpu_conf & BIT(27))) {
            mv64361_set_pci_mem_remap(s, 0, 0, val, false);
        }
        break;
    case MV64340_PCI_0_MEMORY0_SIZE:
        s->pci[0].mem_size[0] = val & 0xffffULL;
        break;
    case MV64340_PCI_0_MEMORY0_LOW_ADDR_REMAP:
    case MV64340_PCI_0_MEMORY0_HIGH_ADDR_REMAP:
        mv64361_set_pci_mem_remap(s, 0, 0, val,
            (addr == MV64340_PCI_0_MEMORY0_HIGH_ADDR_REMAP));
        break;
    case MV64340_PCI_0_MEMORY1_BASE_ADDR:
        s->pci[0].mem_base[1] = val & 0x70fffffULL;
        warn_swap_bit(val);
        if (!(s->cpu_conf & BIT(27))) {
            mv64361_set_pci_mem_remap(s, 0, 1, val, false);
        }
        break;
    case MV64340_PCI_0_MEMORY1_SIZE:
        s->pci[0].mem_size[1] = val & 0xffffULL;
        break;
    case MV64340_PCI_0_MEMORY1_LOW_ADDR_REMAP:
    case MV64340_PCI_0_MEMORY1_HIGH_ADDR_REMAP:
        mv64361_set_pci_mem_remap(s, 0, 1, val,
            (addr == MV64340_PCI_0_MEMORY1_HIGH_ADDR_REMAP));
        break;
    case MV64340_PCI_0_MEMORY2_BASE_ADDR:
        s->pci[0].mem_base[2] = val & 0x70fffffULL;
        warn_swap_bit(val);
        if (!(s->cpu_conf & BIT(27))) {
            mv64361_set_pci_mem_remap(s, 0, 2, val, false);
        }
        break;
    case MV64340_PCI_0_MEMORY2_SIZE:
        s->pci[0].mem_size[2] = val & 0xffffULL;
        break;
    case MV64340_PCI_0_MEMORY2_LOW_ADDR_REMAP:
    case MV64340_PCI_0_MEMORY2_HIGH_ADDR_REMAP:
        mv64361_set_pci_mem_remap(s, 0, 2, val,
            (addr == MV64340_PCI_0_MEMORY2_HIGH_ADDR_REMAP));
        break;
    case MV64340_PCI_0_MEMORY3_BASE_ADDR:
        s->pci[0].mem_base[3] = val & 0x70fffffULL;
        warn_swap_bit(val);
        if (!(s->cpu_conf & BIT(27))) {
            mv64361_set_pci_mem_remap(s, 0, 3, val, false);
        }
        break;
    case MV64340_PCI_0_MEMORY3_SIZE:
        s->pci[0].mem_size[3] = val & 0xffffULL;
        break;
    case MV64340_PCI_0_MEMORY3_LOW_ADDR_REMAP:
    case MV64340_PCI_0_MEMORY3_HIGH_ADDR_REMAP:
        mv64361_set_pci_mem_remap(s, 0, 3, val,
            (addr == MV64340_PCI_0_MEMORY3_HIGH_ADDR_REMAP));
        break;
    case MV64340_PCI_1_IO_BASE_ADDR:
        s->pci[1].io_base = val & 0x30fffffULL;
        warn_swap_bit(val);
        break;
        if (!(s->cpu_conf & BIT(27))) {
            s->pci[1].remap[4] = (val & 0xffffULL) << 16;
        }
        break;
    case MV64340_PCI_1_IO_SIZE:
        s->pci[1].io_size = val & 0xffffULL;
        break;
    case MV64340_PCI_1_MEMORY0_BASE_ADDR:
        s->pci[1].mem_base[0] = val & 0x70fffffULL;
        warn_swap_bit(val);
        if (!(s->cpu_conf & BIT(27))) {
            mv64361_set_pci_mem_remap(s, 1, 0, val, false);
        }
        break;
    case MV64340_PCI_1_MEMORY0_SIZE:
        s->pci[1].mem_size[0] = val & 0xffffULL;
        break;
    case MV64340_PCI_1_MEMORY0_LOW_ADDR_REMAP:
    case MV64340_PCI_1_MEMORY0_HIGH_ADDR_REMAP:
        mv64361_set_pci_mem_remap(s, 1, 0, val,
            (addr == MV64340_PCI_1_MEMORY0_HIGH_ADDR_REMAP));
        break;
    case MV64340_PCI_1_MEMORY1_BASE_ADDR:
        s->pci[1].mem_base[1] = val & 0x70fffffULL;
        warn_swap_bit(val);
        if (!(s->cpu_conf & BIT(27))) {
            mv64361_set_pci_mem_remap(s, 1, 1, val, false);
        }
        break;
    case MV64340_PCI_1_MEMORY1_SIZE:
        s->pci[1].mem_size[1] = val & 0xffffULL;
        break;
    case MV64340_PCI_1_MEMORY1_LOW_ADDR_REMAP:
    case MV64340_PCI_1_MEMORY1_HIGH_ADDR_REMAP:
        mv64361_set_pci_mem_remap(s, 1, 1, val,
            (addr == MV64340_PCI_1_MEMORY1_HIGH_ADDR_REMAP));
        break;
    case MV64340_PCI_1_MEMORY2_BASE_ADDR:
        s->pci[1].mem_base[2] = val & 0x70fffffULL;
        warn_swap_bit(val);
        if (!(s->cpu_conf & BIT(27))) {
            mv64361_set_pci_mem_remap(s, 1, 2, val, false);
        }
        break;
    case MV64340_PCI_1_MEMORY2_SIZE:
        s->pci[1].mem_size[2] = val & 0xffffULL;
        break;
    case MV64340_PCI_1_MEMORY2_LOW_ADDR_REMAP:
    case MV64340_PCI_1_MEMORY2_HIGH_ADDR_REMAP:
        mv64361_set_pci_mem_remap(s, 1, 2, val,
            (addr == MV64340_PCI_1_MEMORY2_HIGH_ADDR_REMAP));
        break;
    case MV64340_PCI_1_MEMORY3_BASE_ADDR:
        s->pci[1].mem_base[3] = val & 0x70fffffULL;
        warn_swap_bit(val);
        if (!(s->cpu_conf & BIT(27))) {
            mv64361_set_pci_mem_remap(s, 1, 3, val, false);
        }
        break;
    case MV64340_PCI_1_MEMORY3_SIZE:
        s->pci[1].mem_size[3] = val & 0xffffULL;
        break;
    case MV64340_PCI_1_MEMORY3_LOW_ADDR_REMAP:
    case MV64340_PCI_1_MEMORY3_HIGH_ADDR_REMAP:
        mv64361_set_pci_mem_remap(s, 1, 3, val,
            (addr == MV64340_PCI_1_MEMORY3_HIGH_ADDR_REMAP));
        break;
    case MV64340_INTERNAL_SPACE_BASE_ADDR:
        s->regs_base = val & 0xfffffULL;
        break;
    case MV64340_BASE_ADDR_ENABLE:
        setup_mem_windows(s, val);
        s->base_addr_enable = val & 0x1fffffULL;
        break;
    case MV64340_PCI_0_CONFIG_ADDR:
        pci_host_conf_le_ops.write(PCI_HOST_BRIDGE(&s->pci[0]), 0, val, size);
        break;
    case MV64340_PCI_0_CONFIG_DATA_VIRTUAL_REG ...
         MV64340_PCI_0_CONFIG_DATA_VIRTUAL_REG + 3:
        pci_host_data_le_ops.write(PCI_HOST_BRIDGE(&s->pci[0]),
            addr - MV64340_PCI_0_CONFIG_DATA_VIRTUAL_REG, val, size);
        break;
    case MV64340_PCI_1_CONFIG_ADDR:
        pci_host_conf_le_ops.write(PCI_HOST_BRIDGE(&s->pci[1]), 0, val, size);
        break;
    case MV64340_PCI_1_CONFIG_DATA_VIRTUAL_REG ...
         MV64340_PCI_1_CONFIG_DATA_VIRTUAL_REG + 3:
        pci_host_data_le_ops.write(PCI_HOST_BRIDGE(&s->pci[1]),
            addr - MV64340_PCI_1_CONFIG_DATA_VIRTUAL_REG, val, size);
        break;
    case MV64340_CPU_INTERRUPT0_MASK_LOW:
        s->cpu0_int_mask &= 0xffffffff00000000ULL;
        s->cpu0_int_mask |= val & 0xffffffffULL;
        break;
    case MV64340_CPU_INTERRUPT0_MASK_HIGH:
        s->cpu0_int_mask &= 0xffffffffULL;
        s->cpu0_int_mask |= val << 32;
        break;
    case MV64340_CUNIT_ARBITER_CONTROL_REG:
        s->gpp_int_level = !!(val & BIT(10));
        break;
    case MV64340_GPP_IO_CONTROL:
        s->gpp_io = val;
        break;
    case MV64340_GPP_LEVEL_CONTROL:
        s->gpp_level = val;
        break;
    case MV64340_GPP_VALUE:
        s->gpp_value &= ~s->gpp_io;
        s->gpp_value |= val & s->gpp_io;
        break;
    case MV64340_GPP_VALUE_SET:
        s->gpp_value |= val & s->gpp_io;
        break;
    case MV64340_GPP_VALUE_CLEAR:
        s->gpp_value &= ~(val & s->gpp_io);
        break;
    case MV64340_GPP_INTERRUPT_CAUSE:
        if (!s->gpp_int_level && val != s->gpp_int_cr) {
            int i;
            uint32_t ch = s->gpp_int_cr ^ val;
            s->gpp_int_cr = val;
            for (i = 0; i < 4; i++) {
                if ((ch & 0xff << i) && !(val & 0xff << i)) {
                    mv64361_update_irq(opaque, MV64361_IRQ_P0_GPP0_7 + i, 0);
                }
            }
        } else {
            s->gpp_int_cr = val;
        }
        break;
    case MV64340_GPP_INTERRUPT_MASK0:
    case MV64340_GPP_INTERRUPT_MASK1:
        s->gpp_int_mask = val;
        break;
    default:
        qemu_log_mask(LOG_UNIMP, "%s: Unimplemented register write 0x%"
                      HWADDR_PRIx " = %"PRIx64"\n", __func__, addr, val);
        break;
    }
}

static const MemoryRegionOps mv64361_ops = {
    .read = mv64361_read,
    .write = mv64361_write,
    .valid.min_access_size = 1,
    .valid.max_access_size = 4,
    .endianness = DEVICE_LITTLE_ENDIAN,
};

static void mv64361_gpp_irq(void *opaque, int n, int level)
{
    MV64361State *s = opaque;
    uint32_t mask = BIT(n);
    uint32_t val = s->gpp_value & ~mask;

    if (s->gpp_level & mask) {
        level = !level;
    }
    val |= level << n;
    if (val > s->gpp_value) {
        s->gpp_value = val;
        s->gpp_int_cr |= mask;
        if (s->gpp_int_mask & mask) {
            mv64361_update_irq(opaque, MV64361_IRQ_P0_GPP0_7 + n / 8, 1);
        }
    } else if (val < s->gpp_value) {
        int b = n / 8;
        s->gpp_value = val;
        if (s->gpp_int_level && !(val & 0xff << b)) {
            mv64361_update_irq(opaque, MV64361_IRQ_P0_GPP0_7 + b, 0);
        }
    }
}

static void mv64361_realize(DeviceState *dev, Error **errp)
{
    MV64361State *s = MV64361(dev);
    int i;

    s->base_addr_enable = 0x1fffff;
    memory_region_init_io(&s->regs, OBJECT(s), &mv64361_ops, s,
                          TYPE_MV64361, 0x10000);
    for (i = 0; i < 2; i++) {
        char *name = g_strdup_printf("pcihost%d", i);
        sysbus_init_child_obj(OBJECT(dev), name,
                              &s->pci[i], sizeof(s->pci[i]), TYPE_MV64361_PCI);
        g_free(name);
        DeviceState *pci = DEVICE(&s->pci[i]);
        qdev_prop_set_uint8(pci, "index", i);
        qdev_init_nofail(pci);
    }
    sysbus_init_irq(SYS_BUS_DEVICE(dev), &s->cpu_irq);
    qdev_init_gpio_in_named(dev, mv64361_gpp_irq, "gpp", 32);
    /* FIXME: PCI IRQ connections may be board specific */
    for (i = 0; i < 4; i++) {
        s->pci[1].irq[i] = qdev_get_gpio_in_named(dev, "gpp", 12 + i);
    }
}

static void mv64361_reset(DeviceState *dev)
{
    MV64361State *s = MV64361(dev);
    int i, j;

    /*
     * These values may be board specific
     * Real chip supports init from an eprom but that's not modelled
     */
    setup_mem_windows(s, 0x1fffff);
    s->base_addr_enable = 0x1fffff;
    s->cpu_conf = 0x28000ff;
    s->regs_base = 0x100f100;
    s->pci[0].io_base = 0x100f800;
    s->pci[0].io_size = 0xff;
    s->pci[0].mem_base[0] = 0x100c000;
    s->pci[0].mem_size[0] = 0x1fff;
    s->pci[0].mem_base[1] = 0x100f900;
    s->pci[0].mem_size[1] = 0xff;
    s->pci[0].mem_base[2] = 0x100f400;
    s->pci[0].mem_size[2] = 0x1ff;
    s->pci[0].mem_base[3] = 0x100f600;
    s->pci[0].mem_size[3] = 0x1ff;
    s->pci[1].io_base = 0x100fe00;
    s->pci[1].io_size = 0xff;
    s->pci[1].mem_base[0] = 0x1008000;
    s->pci[1].mem_size[0] = 0x3fff;
    s->pci[1].mem_base[1] = 0x100fd00;
    s->pci[1].mem_size[1] = 0xff;
    s->pci[1].mem_base[2] = 0x1002600;
    s->pci[1].mem_size[2] = 0x1ff;
    s->pci[1].mem_base[3] = 0x100ff80;
    s->pci[1].mem_size[3] = 0x7f;
    for (i = 0; i < 2; i++) {
        for (j = 0; j < 4; j++) {
            s->pci[i].remap[j] = s->pci[i].mem_base[j] << 16;
        }
    }
    s->pci[0].remap[1] = 0;
    s->pci[1].remap[1] = 0;
    setup_mem_windows(s, 0xfbfff);
    s->base_addr_enable = 0xfbfff;
}

static void mv64361_class_init(ObjectClass *klass, void *data)
{
    DeviceClass *dc = DEVICE_CLASS(klass);

    dc->realize = mv64361_realize;
    dc->reset = mv64361_reset;
}

static const TypeInfo mv64361_type_info = {
    .name = TYPE_MV64361,
    .parent = TYPE_SYS_BUS_DEVICE,
    .instance_size = sizeof(MV64361State),
    .class_init = mv64361_class_init,
};

static void mv64361_register_types(void)
{
    type_register_static(&mv64361_type_info);
}

type_init(mv64361_register_types)

/* ------------------------------------------------------------------------- */
/* VIA VT8231 South Bridge, very similar to VT82C686B */

/* vt8231.c */

typedef struct SuperIOConfig {
    uint8_t config[0x100];
    uint8_t index;
    uint8_t data;
} SuperIOConfig;

typedef struct VT8231ISAState {
    PCIDevice dev;
    MemoryRegion superio;
    SuperIOConfig superio_conf;
} VT8231ISAState;

#define TYPE_VT8231_ISA "vt8231-isa"
#define VT8231_ISA(obj) OBJECT_CHECK(VT8231ISAState, (obj), TYPE_VT8231_ISA)

static uint64_t superio_ioport_readb(void *opaque, hwaddr addr, unsigned size)
{
    SuperIOConfig *sc = opaque;

    printf("%s: address 0x%lx -> %x\n", __func__, addr, sc->config[sc->index]);
    return (sc->config[sc->index]);
}

static void superio_ioport_writeb(void *opaque, hwaddr addr, uint64_t data,
                                  unsigned size)
{
    SuperIOConfig *sc = opaque;

    printf("%s: address 0x%lx  val 0x%"PRIx64"\n", __func__, addr, data);
    if (addr == 0x3f0) { /* config index */
        sc->index = data & 0xff;
    } else {
        bool can_write = true;
        /* 0x3f1 - config data */
        switch (sc->index) {
        case 0x00 ... 0xdf:
        case 0xe4:
        case 0xe5:
        case 0xe7 ... 0xed:
        case 0xf3:
        case 0xf5:
        case 0xf7:
        case 0xf9 ... 0xfb:
        case 0xfd ... 0xff:
            can_write = false;
            break;
        default:
            break;
        }
        if (can_write) {
            sc->config[sc->index] = data & 0xff;
        }
    }
}

static const MemoryRegionOps superio_ops = {
    .read = superio_ioport_readb,
    .write = superio_ioport_writeb,
    .endianness = DEVICE_NATIVE_ENDIAN,
    .impl = {
        .min_access_size = 1,
        .max_access_size = 1,
    },
};

static void vt8231_isa_reset(void *opaque)
{
    PCIDevice *d = opaque;
    VT8231ISAState *s = VT8231_ISA(d);
    uint8_t *pci_conf = d->config;

    pci_set_long(pci_conf + PCI_CAPABILITY_LIST, 0x000000c0);
    pci_set_word(pci_conf + PCI_COMMAND, PCI_COMMAND_IO | PCI_COMMAND_MEMORY |
                 PCI_COMMAND_MASTER | PCI_COMMAND_SPECIAL);
    pci_set_word(pci_conf + PCI_STATUS, PCI_STATUS_DEVSEL_MEDIUM);

    pci_conf[0x58] = 0x40; /* Miscellaneous Control 0 */
    pci_conf[0x67] = 0x08; /* Fast IR Config */
    pci_conf[0x6b] = 0x01; /* Fast IR I/O Base */

    s->superio_conf.config[0xf0] = 0x3c; /* Super-I/O Device-ID */
    s->superio_conf.config[0xf1] = 0x01; /* Super-I/O Device Revision */
    s->superio_conf.config[0xf2] = 0x03; /* Function Select */
    s->superio_conf.config[0xf4] = 0xfe; /* Serial Port Base Addr */
    s->superio_conf.config[0xf6] = 0xde; /* Parallel Port Base Addr */
    s->superio_conf.config[0xf7] = 0xfc; /* Floppy Ctrlr Base Addr */
}

static void vt8231_isa_write_config(PCIDevice *d, uint32_t address,
                                    uint32_t val, int len)
{
    VT8231ISAState *s = VT8231_ISA(d);

    printf("%s: address 0x%x  val 0x%x len 0x%x\n", __func__,
           address, val, len);

    pci_default_write_config(d, address, val, len);
    if (address == 0x50) {  /* enable or disable super IO configure */
        memory_region_set_enabled(&s->superio, val & 4);
    }
}

static void vt8231_isa_realize(PCIDevice *d, Error **errp)
{
    VT8231ISAState *s = VT8231_ISA(d);
    ISABus *isa_bus;

    isa_bus = isa_bus_new(DEVICE(d), get_system_memory(),
                          pci_address_space_io(d), errp);
    if (!isa_bus) {
        return;
    }

    memory_region_init_io(&s->superio, OBJECT(d), &superio_ops,
                          &s->superio_conf, "superio", 2);
    memory_region_set_enabled(&s->superio, false);
    /* The floppy also uses 0x3f0 and 0x3f1.
     * But we do not emulate a floppy, so just set it here. */
    memory_region_add_subregion(isa_bus->address_space_io, 0x3f0,
                                &s->superio);

    qemu_register_reset(vt8231_isa_reset, d);
}

static void vt8231_isa_class_init(ObjectClass *klass, void *data)
{
    DeviceClass *dc = DEVICE_CLASS(klass);
    PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);

    k->realize = vt8231_isa_realize;
    k->config_write = vt8231_isa_write_config;
    k->vendor_id = PCI_VENDOR_ID_VIA;
    k->device_id = 0x8231;
    k->class_id = PCI_CLASS_BRIDGE_ISA;
    dc->desc = "PCI-to-ISA bridge";
    /* Reason: part of VIA VT8231 southbridge */
    dc->user_creatable = false;
}

static const TypeInfo vt8231_isa_info = {
    .name          = TYPE_VT8231_ISA,
    .parent        = TYPE_PCI_DEVICE,
    .instance_size = sizeof(VT8231ISAState),
    .class_init    = vt8231_isa_class_init,
    .interfaces = (InterfaceInfo[]) {
        { INTERFACE_CONVENTIONAL_PCI_DEVICE },
        { },
    },
};

static uint16_t vt8231_superio_get_iobase(ISASuperIODevice *sio, uint8_t index)
{
    return 0x2f8; /* FIXME: This should be settable via a register */
}

static bool vt8231_superio_floppy_is_enabled(ISASuperIODevice *sio, uint8_t index)
{
    return false; /* FIXME: Disabled due to clash with SuperIO Ctrl */
}

static void vt8231_superio_class_init(ObjectClass *klass, void *data)
{
    ISASuperIOClass *sc = ISA_SUPERIO_CLASS(klass);

    sc->serial.count = 1;
    sc->serial.get_iobase = vt8231_superio_get_iobase;
    sc->parallel.count = 1;
    sc->ide.count = 0;
    sc->floppy.is_enabled = vt8231_superio_floppy_is_enabled;
}

#define TYPE_VT8231_SUPERIO "vt8231-superio"

static const TypeInfo vt8231_superio_info = {
    .name          = TYPE_VT8231_SUPERIO,
    .parent        = TYPE_ISA_SUPERIO,
    .instance_size = sizeof(ISASuperIODevice),
    .class_size    = sizeof(ISASuperIOClass),
    .class_init    = vt8231_superio_class_init,
};

#define TYPE_VT8231_PM "vt8231-pm"
#define VT8231_PM(obj) OBJECT_CHECK(VT8231PMState, (obj), TYPE_VT8231_PM)

typedef struct VT8231PMState {
    PCIDevice dev;
    PMSMBus smb;
} VT8231PMState;

static void vt8231_pm_write_config(PCIDevice *d, uint32_t addr,
                                   uint32_t val, int len)
{
    VT8231PMState *s = VT8231_PM(d);

    printf("%s: address 0x%x  val 0x%x len 0x%x\n", __func__,
           addr, val, len);

    pci_default_write_config(d, addr, val, len);
    if (addr == 0xd2) {  /* enable or disable smbus IO range */
        uint16_t iobase = pci_get_word(d->config + 0x90);
        printf("%s: %s SMBus @ 0x%x\n", __func__, (val & 1 ? "enabling" : "disabling"), iobase);
        memory_region_set_address(&s->smb.io, iobase);
        memory_region_set_enabled(&s->smb.io, val & 1);
    }
}

static void vt8231_pm_realize(PCIDevice *d, Error **errp)
{
    VT8231PMState *s = VT8231_PM(d);

    pci_set_word(d->config + PCI_STATUS, PCI_STATUS_FAST_BACK |
                 PCI_STATUS_DEVSEL_MEDIUM);

    /* 0x48-0x4B is Power Management I/O Base */
    pci_set_long(d->config + 0x48, 0x00000001);

    /* 0x90-0x93 is SMBus I/O Base */
    pci_set_long(d->config + 0x90, 0x00000001);
    pm_smbus_init(&s->dev.qdev, &s->smb, false);
    memory_region_add_subregion(pci_address_space_io(d), 0, &s->smb.io);
    memory_region_set_enabled(&s->smb.io, false);
}

static void vt8231_pm_class_init(ObjectClass *klass, void *data)
{
    PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);

    k->realize = vt8231_pm_realize;
    k->config_write = vt8231_pm_write_config;
    k->vendor_id = PCI_VENDOR_ID_VIA;
    k->device_id = 0x8235;
}

static const TypeInfo vt8231_pm_info = {
    .name          = TYPE_VT8231_PM,
    .parent        = TYPE_PCI_DEVICE,
    .instance_size = sizeof(VT8231PMState),
    .class_init    = vt8231_pm_class_init,
    .interfaces = (InterfaceInfo[]) {
        { INTERFACE_CONVENTIONAL_PCI_DEVICE },
        { },
    },
};

static void vt8231_isa_register_types(void)
{
    type_register_static(&vt8231_isa_info);
    type_register_static(&vt8231_superio_info);
    type_register_static(&vt8231_pm_info);
}

type_init(vt8231_isa_register_types)

/* ------------------------------------------------------------------------- */
/* board code starts here (pegasos2.c) */

#include "sysemu/device_tree.h"

#include <libfdt.h>

#define PROM_FILENAME "pegrom.bin"
#define PROM_ADDR     0xfff00000
#define PROM_SIZE     0x80000

#define BUS_FREQ 133333333

#define FDT_ADDR      (2 * MiB)
#define FDT_MAX_SIZE  (1 * MiB)

static void *build_fdt(MachineState *machine, PowerPCCPU *cpu, int *fdt_size);

static void pegasos2_reset(void *opaque)
{
    PowerPCCPU *cpu = opaque;

    cpu_reset(CPU(cpu));
    cpu->env.spr[SPR_HID1] = 7ULL << 28;
}

static void pegasos2_init(MachineState *machine)
{
    PowerPCCPU *cpu = NULL;
    MemoryRegion *rom = g_new(MemoryRegion, 1);
    MV64361State *mv;
    PCIBus *pci_bus;
    PCIDevice *dev;
    ISABus *isa_bus;
    I2CBus *i2c_bus;
    qemu_irq *i8259;
    char *filename;
    int sz;
    void *fdt;
    uint8_t *spd_data;
    Error *err = NULL;

    /* init CPU */
    cpu = POWERPC_CPU(cpu_create(machine->cpu_type));
    if (PPC_INPUT(&cpu->env) != PPC_FLAGS_INPUT_6xx) {
        error_report("Incompatible CPU, only 6xx bus supported");
        exit(1);
    }

    /* Set time-base frequency */
    cpu_ppc_tb_init(&cpu->env, BUS_FREQ / 4);
    qemu_register_reset(pegasos2_reset, cpu);

    /* RAM */
    memory_region_add_subregion(get_system_memory(), 0, machine->ram);

    /* allocate and load firmware */
    if (!bios_name) {
        bios_name = PROM_FILENAME;
    }
    filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);
    if (!filename) {
        error_report("Could not find firmware '%s'", bios_name);
        exit(1);
    }
    memory_region_init_rom(rom, NULL, "pegasos2.rom", PROM_SIZE, &error_fatal);
    memory_region_add_subregion(get_system_memory(), PROM_ADDR, rom);
    sz = load_elf(filename, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 1,
                  PPC_ELF_MACHINE, 0, 0);
    if (sz <= 0) {
        sz = load_image_targphys(filename, PROM_ADDR, PROM_SIZE);
    }
    if (sz <= 0 || sz > PROM_SIZE) {
        error_report("Could not load firmware '%s'", filename);
        exit(1);
    }
    g_free(filename);

    /* Marvell Discovery II system controller */
    mv = MV64361(sysbus_create_simple(TYPE_MV64361, -1,
                 ((qemu_irq *)cpu->env.irq_inputs)[PPC6xx_INPUT_INT]));
    pci_bus = PCI_HOST_BRIDGE(&mv->pci[1])->bus;

    /* VIA VT8231 South Bridge (multifunction PCI device) */
    /* VT8231 function 0: PCI-to-ISA Bridge */
    dev = pci_create_simple_multifunction(pci_bus, PCI_DEVFN(12, 0), true,
                                          "vt8231-isa");
    isa_bus = ISA_BUS(qdev_get_child_bus(DEVICE(dev), "isa.0"));
    i8259 = i8259_init(isa_bus, qdev_get_gpio_in_named(DEVICE(mv), "gpp", 31));
    isa_bus_irqs(isa_bus, i8259);
    i8254_pit_init(isa_bus, 0x40, 0, NULL);
    i8257_dma_init(isa_bus, 0);
    isa_create_simple(isa_bus, TYPE_VT8231_SUPERIO);
    mc146818_rtc_init(isa_bus, 2000, NULL);

    /* VT8231 function 1: IDE Controller */
    dev = pci_create_simple(pci_bus, PCI_DEVFN(12, 1), "via-ide");
    pci_ide_create_devs(dev);

    /* VT8231 function 2-3: USB Ports */
    pci_create_simple(pci_bus, PCI_DEVFN(12, 2), "vt82c686b-usb-uhci");
    pci_create_simple(pci_bus, PCI_DEVFN(12, 3), "vt82c686b-usb-uhci");

    /* VT8231 function 4: Power Management Controller */
    dev = pci_create_simple(pci_bus, PCI_DEVFN(12, 4), "vt8231-pm");
    i2c_bus = I2C_BUS(qdev_get_child_bus(DEVICE(dev), "i2c"));
    spd_data = spd_data_generate(DDR, machine->ram_size, &err);
    if (err) {
        warn_report_err(err);
    }
    if (spd_data) {
        smbus_eeprom_init_one(i2c_bus, 0x57, spd_data);
    }

    /* VT8231 function 5-6: AC97 Audio & Modem */
    vt82c686b_ac97_init(pci_bus, PCI_DEVFN(12, 5));
    vt82c686b_mc97_init(pci_bus, PCI_DEVFN(12, 6));

    /* other PC hardware */
    pci_vga_init(pci_bus);

    fdt = build_fdt(machine, cpu, &sz);
    /* fdt_pack should only fail if we've built a corrupted tree */
    if (fdt_pack(fdt) || fdt_totalsize(fdt) > FDT_MAX_SIZE) {
        g_free(fdt);
        error_report("Error creating FDT (0x%x bytes, max is 0x%lx)",
                     fdt_totalsize(fdt), FDT_MAX_SIZE);
        exit(1);
    }
    /* Place DTB in client memory for firmware */
    qemu_fdt_dumpdtb(fdt, fdt_totalsize(fdt));
    cpu_physical_memory_write(FDT_ADDR, fdt, fdt_totalsize(fdt));
    g_free(fdt);
}

static void pegasos2_machine_class_init(ObjectClass *oc, void *data)
{
    MachineClass *mc = MACHINE_CLASS(oc);

    mc->desc = "Genesi/bPlan Pegasos II";
    mc->init = pegasos2_init;
    mc->block_default_type = IF_IDE;
    mc->default_boot_order = "cd";
    mc->default_display = "std";
    mc->default_cpu_type = POWERPC_CPU_TYPE_NAME("750cxe_v3.1b");
    mc->default_ram_id = "pegasos2.ram";
    mc->default_ram_size = 512 * MiB;
}

static const TypeInfo pegasos2_machine_info = {
    .name          = MACHINE_TYPE_NAME("pegasos2"),
    .parent        = TYPE_MACHINE,
    .class_init    = pegasos2_machine_class_init,
    .instance_size = sizeof(MachineState),
};

static void pegasos2_machine_register_types(void)
{
    type_register_static(&pegasos2_machine_info);
}

type_init(pegasos2_machine_register_types)

/* FDT creation for passing to firmware */
static void *build_fdt(MachineState *machine, PowerPCCPU *cpu, int *fdt_size)
{
    PowerPCCPUClass *pcc = POWERPC_CPU_GET_CLASS(CPU(cpu));
    uint32_t mem_reg[] = { 0, cpu_to_be32(machine->ram_size) };
    void *fdt = create_device_tree(fdt_size);

    /* root node */
    qemu_fdt_setprop_string(fdt, "/", "name", "bplan,Pegasos2");
    qemu_fdt_setprop_cell(fdt, "/", "#address-cells", 1);
    qemu_fdt_setprop_string(fdt, "/", "device_type", "chrp");
    qemu_fdt_setprop_string(fdt, "/", "model", "Pegasos2");
    qemu_fdt_setprop_string(fdt, "/", "revision", "2B");
    qemu_fdt_setprop_string(fdt, "/", "CODEGEN,vendor", "bplan GmbH");
    qemu_fdt_setprop_string(fdt, "/", "CODEGEN,board", "Pegasos2");
    qemu_fdt_setprop_string(fdt, "/", "CODEGEN,description",
                            "Pegasos CHRP PowerPC System");
    /* extra props for OpenFirmware */
    qemu_fdt_setprop_cell(fdt, "/", "#size-cells", 1);
    qemu_fdt_setprop_cell(fdt, "/", "clock-frequency", BUS_FREQ);

    /* memory */
    qemu_fdt_add_subnode(fdt, "/memory");
    qemu_fdt_setprop_string(fdt, "/memory", "device_type", "memory");
    qemu_fdt_setprop(fdt, "/memory", "reg", mem_reg, sizeof(mem_reg));

    /* cpus */
    qemu_fdt_add_subnode(fdt, "/cpus");
    qemu_fdt_setprop_cell(fdt, "/cpus", "#size-cells", 0);
    qemu_fdt_setprop_cell(fdt, "/cpus", "#address-cells", 1);
    qemu_fdt_setprop_cell(fdt, "/cpus", "#cpus", 1);

    /* FIXME Get CPU name from CPU object */
    const char *cp = "/cpus/PowerPC,750CXE";
    qemu_fdt_add_subnode(fdt, cp);
    qemu_fdt_setprop_string(fdt, cp, "device_type", "cpu");
    qemu_fdt_setprop_cell(fdt, cp, "reg", 0);
    qemu_fdt_setprop_cell(fdt, cp, "cpu-version", cpu->env.spr[SPR_PVR]);
    qemu_fdt_setprop_cell(fdt, cp, "clock-frequency", BUS_FREQ * 4.5);
    qemu_fdt_setprop_cell(fdt, cp, "bus-frequency", BUS_FREQ);
    qemu_fdt_setprop_cell(fdt, cp, "timebase-frequency",
                          cpu->env.tb_env->tb_freq);
    qemu_fdt_setprop_string(fdt, cp, "state", "running");
    qemu_fdt_setprop_cell(fdt, cp, "tlb-size", cpu->env.nb_tlb);
    qemu_fdt_setprop_cell(fdt, cp, "tlb-sets", cpu->env.nb_ways);
    if (cpu->env.id_tlbs) {
        qemu_fdt_setprop_cell(fdt, cp, "d-tlb-size", cpu->env.tlb_per_way);
        qemu_fdt_setprop_cell(fdt, cp, "d-tlb-sets", cpu->env.nb_ways);
        qemu_fdt_setprop_cell(fdt, cp, "i-tlb-size", cpu->env.tlb_per_way);
        qemu_fdt_setprop_cell(fdt, cp, "i-tlb-sets", cpu->env.nb_ways);
    }
    qemu_fdt_setprop_cell(fdt, cp, "i-cache-line-size",
                          cpu->env.icache_line_size);
    qemu_fdt_setprop_cell(fdt, cp, "i-cache-block-size",
                          cpu->env.icache_line_size);
    qemu_fdt_setprop_cell(fdt, cp, "i-cache-size", pcc->l1_icache_size);
    qemu_fdt_setprop_cell(fdt, cp, "d-cache-line-size",
                          cpu->env.dcache_line_size);
    qemu_fdt_setprop_cell(fdt, cp, "d-cache-block-size",
                          cpu->env.dcache_line_size);
    qemu_fdt_setprop_cell(fdt, cp, "d-cache-size", pcc->l1_dcache_size);
    return fdt;
}
