/*
 * Virtio Balloon Device
 *
 * Copyright IBM, Corp. 2008
 * Copyright (C) 2011 Red Hat, Inc.
 * Copyright (C) 2011 Amit Shah <amit.shah@redhat.com>
 * Copyright (C) 2018 Virtual Open Systems
 *
 * Authors:
 *  Anthony Liguori   <aliguori@us.ibm.com>
 *
 * This work is licensed under the terms of the GNU GPL, version 2.  See
 * the COPYING file in the top-level directory.
 *
 */

#include "qemu/osdep.h"
#include "qemu/iov.h"
#include "qemu/config-file.h"
#include "qemu/option.h"
#include "qemu/timer.h"
#include "qemu-common.h"
#include "hw/virtio/virtio.h"
#include "hw/mem/pc-dimm.h"
#include "sysemu/balloon.h"
#include "hw/virtio/virtio-balloon.h"
#include "sysemu/kvm.h"
#include "exec/address-spaces.h"
#include "qapi/error.h"
#include "qapi/qapi-events-misc.h"
#include "qapi/visitor.h"
#include "trace.h"
#include "qemu/error-report.h"
#include "qom/object_interfaces.h"
#include "monitor/monitor.h"
#include "sysemu/numa.h"
#include "qemu/rcu_queue.h"
#include "qemu/int128.h"
#include "hw/boards.h"
#include "hw/arm/virt.h"
#include "sysemu/hostmem-remote.h"
#include "sysemu/setmaxmem.h"
#include "qom/object.h"

#include "hw/virtio/virtio-bus.h"
#include "hw/virtio/virtio-access.h"

#define BALLOON_PAGE_SIZE  (1 << VIRTIO_BALLOON_PFN_SHIFT)

#define VIRT_RAM "mach-virt.ram"

#define DEBUG_VIRTIO_BALLOON 1
#ifdef DEBUG_VIRTIO_BALLOON

#define DPRINTF(fmt, ...) \
do { fprintf(stderr, "%s: " fmt "\n", __func__ , ##__VA_ARGS__); } while (0)

#else
#define DPRINTF(fmt, ...) do {} while (0)
#endif

#define BKND_ID_SIZE 32

static void balloon_page(void *addr, int deflate)
{
    if (!qemu_balloon_is_inhibited() && (!kvm_enabled() ||
                                         kvm_has_sync_mmu())) {
        qemu_madvise(addr, BALLOON_PAGE_SIZE,
                deflate ? QEMU_MADV_WILLNEED : QEMU_MADV_DONTNEED);
    }
}

static const char *balloon_stat_names[] = {
   [VIRTIO_BALLOON_S_SWAP_IN] = "stat-swap-in",
   [VIRTIO_BALLOON_S_SWAP_OUT] = "stat-swap-out",
   [VIRTIO_BALLOON_S_MAJFLT] = "stat-major-faults",
   [VIRTIO_BALLOON_S_MINFLT] = "stat-minor-faults",
   [VIRTIO_BALLOON_S_MEMFREE] = "stat-free-memory",
   [VIRTIO_BALLOON_S_MEMTOT] = "stat-total-memory",
   [VIRTIO_BALLOON_S_AVAIL] = "stat-available-memory",
   [VIRTIO_BALLOON_S_CACHES] = "stat-disk-caches",
   [VIRTIO_BALLOON_S_NR] = NULL
};

/*
 * reset_stats - Mark all items in the stats array as unset
 *
 * This function needs to be called at device initialization and before
 * updating to a set of newly-generated stats.  This will ensure that no
 * stale values stick around in case the guest reports a subset of the supported
 * statistics.
 */
static inline void reset_stats(VirtIOBalloon *dev)
{
    int i;
    for (i = 0; i < VIRTIO_BALLOON_S_NR; dev->stats[i++] = -1);
}

static bool balloon_stats_supported(const VirtIOBalloon *s)
{
    VirtIODevice *vdev = VIRTIO_DEVICE(s);
    return virtio_vdev_has_feature(vdev, VIRTIO_BALLOON_F_STATS_VQ);
}

static bool balloon_stats_enabled(const VirtIOBalloon *s)
{
    return s->stats_poll_interval > 0;
}

static void balloon_stats_destroy_timer(VirtIOBalloon *s)
{
    if (balloon_stats_enabled(s)) {
        timer_del(s->stats_timer);
        timer_free(s->stats_timer);
        s->stats_timer = NULL;
        s->stats_poll_interval = 0;
    }
}

static void balloon_stats_change_timer(VirtIOBalloon *s, int64_t secs)
{
    timer_mod(s->stats_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) + secs * 1000);
}

static void balloon_stats_poll_cb(void *opaque)
{
    VirtIOBalloon *s = opaque;
    VirtIODevice *vdev = VIRTIO_DEVICE(s);

    if (s->stats_vq_elem == NULL || !balloon_stats_supported(s)) {
        /* re-schedule */
        balloon_stats_change_timer(s, s->stats_poll_interval);
        return;
    }

    virtqueue_push(s->svq, s->stats_vq_elem, s->stats_vq_offset);
    virtio_notify(vdev, s->svq);
    g_free(s->stats_vq_elem);
    s->stats_vq_elem = NULL;
}

static void balloon_stats_get_all(Object *obj, Visitor *v, const char *name,
                                  void *opaque, Error **errp)
{
    Error *err = NULL;
    VirtIOBalloon *s = opaque;
    int i;

    visit_start_struct(v, name, NULL, 0, &err);
    if (err) {
        goto out;
    }
    visit_type_int(v, "last-update", &s->stats_last_update, &err);
    if (err) {
        goto out_end;
    }

    visit_start_struct(v, "stats", NULL, 0, &err);
    if (err) {
        goto out_end;
    }
    for (i = 0; i < VIRTIO_BALLOON_S_NR; i++) {
        visit_type_uint64(v, balloon_stat_names[i], &s->stats[i], &err);
        if (err) {
            goto out_nested;
        }
    }
    visit_check_struct(v, &err);
out_nested:
    visit_end_struct(v, NULL);

    if (!err) {
        visit_check_struct(v, &err);
    }
out_end:
    visit_end_struct(v, NULL);
out:
    error_propagate(errp, err);
}

static void balloon_stats_get_poll_interval(Object *obj, Visitor *v,
                                            const char *name, void *opaque,
                                            Error **errp)
{
    VirtIOBalloon *s = opaque;
    visit_type_int(v, name, &s->stats_poll_interval, errp);
}

static void balloon_stats_set_poll_interval(Object *obj, Visitor *v,
                                            const char *name, void *opaque,
                                            Error **errp)
{
    VirtIOBalloon *s = opaque;
    Error *local_err = NULL;
    int64_t value;

    visit_type_int(v, name, &value, &local_err);
    if (local_err) {
        error_propagate(errp, local_err);
        return;
    }

    if (value < 0) {
        error_setg(errp, "timer value must be greater than zero");
        return;
    }

    if (value > UINT32_MAX) {
        error_setg(errp, "timer value is too big");
        return;
    }

    if (value == s->stats_poll_interval) {
        return;
    }

    if (value == 0) {
        /* timer=0 disables the timer */
        balloon_stats_destroy_timer(s);
        return;
    }

    if (balloon_stats_enabled(s)) {
        /* timer interval change */
        s->stats_poll_interval = value;
        balloon_stats_change_timer(s, value);
        return;
    }

    /* create a new timer */
    g_assert(s->stats_timer == NULL);
    s->stats_timer = timer_new_ms(QEMU_CLOCK_VIRTUAL, balloon_stats_poll_cb, s);
    s->stats_poll_interval = value;
    balloon_stats_change_timer(s, 0);
}

static void virtio_balloon_handle_output(VirtIODevice *vdev, VirtQueue *vq)
{
    VirtIOBalloon *s = VIRTIO_BALLOON(vdev);
    VirtQueueElement *elem;
    MemoryRegionSection section;

    for (;;) {
        size_t offset = 0;
        uint32_t pfn;
        elem = virtqueue_pop(vq, sizeof(VirtQueueElement));
        if (!elem) {
            return;
        }

        while (iov_to_buf(elem->out_sg, elem->out_num, offset, &pfn, 4) == 4) {
            ram_addr_t pa;
            ram_addr_t addr;
            int p = virtio_ldl_p(vdev, &pfn);

            pa = (ram_addr_t) p << VIRTIO_BALLOON_PFN_SHIFT;
            offset += 4;

            /* FIXME: remove get_system_memory(), but how? */
            section = memory_region_find(get_system_memory(), pa, 1);
            if (!int128_nz(section.size) ||
                !memory_region_is_ram(section.mr) ||
                memory_region_is_rom(section.mr) ||
                memory_region_is_romd(section.mr)) {
                trace_virtio_balloon_bad_addr(pa);
                memory_region_unref(section.mr);
                continue;
            }

            trace_virtio_balloon_handle_output(memory_region_name(section.mr),
                                               pa);
            /* Using memory_region_get_ram_ptr is bending the rules a bit, but
               should be OK because we only want a single page.  */
            addr = section.offset_within_region;
            balloon_page(memory_region_get_ram_ptr(section.mr) + addr,
                         !!(vq == s->dvq));
            memory_region_unref(section.mr);
        }

        virtqueue_push(vq, elem, offset);
        virtio_notify(vdev, vq);
        g_free(elem);
    }
}

static void virtio_balloon_receive_stats(VirtIODevice *vdev, VirtQueue *vq)
{
    VirtIOBalloon *s = VIRTIO_BALLOON(vdev);
    VirtQueueElement *elem;
    VirtIOBalloonStat stat;
    size_t offset = 0;
    qemu_timeval tv;

    elem = virtqueue_pop(vq, sizeof(VirtQueueElement));
    if (!elem) {
        goto out;
    }

    if (s->stats_vq_elem != NULL) {
        /* This should never happen if the driver follows the spec. */
        virtqueue_push(vq, s->stats_vq_elem, 0);
        virtio_notify(vdev, vq);
        g_free(s->stats_vq_elem);
    }

    s->stats_vq_elem = elem;

    /* Initialize the stats to get rid of any stale values.  This is only
     * needed to handle the case where a guest supports fewer stats than it
     * used to (ie. it has booted into an old kernel).
     */
    reset_stats(s);

    while (iov_to_buf(elem->out_sg, elem->out_num, offset, &stat, sizeof(stat))
           == sizeof(stat)) {
        uint16_t tag = virtio_tswap16(vdev, stat.tag);
        uint64_t val = virtio_tswap64(vdev, stat.val);

        offset += sizeof(stat);
        if (tag < VIRTIO_BALLOON_S_NR)
            s->stats[tag] = val;
    }
    s->stats_vq_offset = offset;

    if (qemu_gettimeofday(&tv) < 0) {
        warn_report("%s: failed to get time of day", __func__);
        goto out;
    }

    s->stats_last_update = tv.tv_sec;

out:
    if (balloon_stats_enabled(s)) {
        balloon_stats_change_timer(s, s->stats_poll_interval);
    }
}

static void virtio_balloon_get_config(VirtIODevice *vdev, uint8_t *config_data)
{
    VirtIOBalloon *dev = VIRTIO_BALLOON(vdev);
    struct virtio_balloon_config config;

    config.num_pages = cpu_to_le32(dev->num_pages);
    config.actual = cpu_to_le32(dev->actual);

    for (uint8_t i = 0; i < VIRTIO_MEMSET_SECTION_SLOTS; ++i) {
        config.size_low[i] = cpu_to_le32(dev->resized[i].size &
           ((1UL << 32) - 1));
        config.size_high[i] = cpu_to_le32(dev->resized[i].size >> 32);
        config.offset_low[i] = cpu_to_le32(dev->resized[i].base &
           ((1UL << 32) - 1));
        config.offset_high[i] = cpu_to_le32(dev->resized[i].base >> 32);
    }

    config.state_flag = cpu_to_le32(dev->state_flag);

    trace_virtio_balloon_get_config(config.num_pages, config.actual);
    memcpy(config_data, &config, sizeof(struct virtio_balloon_config));
}

static int build_dimm_list(Object *obj, void *opaque)
{
    GSList **list = opaque;

    if (object_dynamic_cast(obj, TYPE_PC_DIMM)) {
        DeviceState *dev = DEVICE(obj);
        if (dev->realized) { /* only realized DIMMs matter */
            *list = g_slist_prepend(*list, dev);
        }
    }

    object_child_foreach(obj, build_dimm_list, opaque);
    return 0;
}

ram_addr_t get_current_ram_size(void)
{
    GSList *list = NULL, *item;
    ram_addr_t size = ram_size;

    build_dimm_list(qdev_get_machine(), &list);
    for (item = list; item; item = g_slist_next(item)) {
        Object *obj = OBJECT(item->data);
        if (!strcmp(object_get_typename(obj), TYPE_PC_DIMM)) {
            size += object_property_get_int(obj, PC_DIMM_SIZE_PROP,
                                            &error_abort);
        }
    }
    g_slist_free(list);

    return size;
}

static void create_new_backend_object(const char *id, int64_t size)
{
    Object *obj = object_new(TYPE_MEMORY_BACKEND_REMOTE);
    HostMemoryBackend *backend = MEMORY_BACKEND(obj);
    Error *local_err = NULL;

    object_property_set_str(obj, id, "id", &local_err);
    if (local_err) {
        goto out;
    }
    backend->size = size;

    object_property_add_child(object_get_objects_root(), id, obj, &local_err);
    if (local_err) {
        goto out;
    }
    user_creatable_complete(obj, &error_abort);
    if (local_err) {
        object_property_del(object_get_objects_root(), id, &local_err);
        goto out;
    }

    DPRINTF("Backend created: %s", id);

out:
    if (local_err) {
        DPRINTF("ERROR!!!: %s", id);
        object_unref(obj);
    }
}

#if defined(TARGET_AARCH64)
static uint64_t setup_numa_offset(Object **memdev, const char *id)
{
    uint64_t next_mem_start = 0;
    uint32_t nodenr = nb_numa_nodes;
    MemoryRegion *mr_prev = &numa_info[nodenr - 1].node_memdev->mr;

    *memdev = object_resolve_path_type(id, TYPE_MEMORY_BACKEND, NULL);
    numa_info[nodenr].node_mem = object_property_get_int(*memdev, "size", NULL);
    numa_info[nodenr].node_memdev = MEMORY_BACKEND(*memdev);
    numa_info[nodenr].present = true;
    object_ref(*memdev);

    next_mem_start = QEMU_ALIGN_UP(mr_prev->addr + mr_prev->size, MEM_SECTION_SIZE);

    return next_mem_start;
}

static MemoryRegion *find_ram_mr(void)
{
    MemoryRegion *submr = NULL;

    QTAILQ_FOREACH_REVERSE(submr, &address_space_memory.root->subregions,
            subregions, subregions_link) {
        if (!strncmp(submr->name, VIRT_RAM, strlen(VIRT_RAM))) {
            break;
        }
    }
    return submr;
}

static void setup_backend_id(char *id)
{
    /* Initializes the object */
    ObjectClass *klass = object_class_by_name(TYPE_MEMORY_BACKEND_REMOTE);
    RemoteMemoryBackendClass *rmbc = REMOTE_MEMORY_BACKEND_CLASS(klass);

    memset(id, 0, BKND_ID_SIZE);
    snprintf(id, BKND_ID_SIZE, "%s%u", TYPE_MEMORY_BACKEND_REMOTE,
            rmbc->get_instances_nb() + 1);
}

static inline uint64_t megs_to_bytes(int64_t megs)
{
    return megs * 1024 * 1024;
};

/* MemMapEntry is reused because it already provides necessary fields
 * .base stands for new memory offset
 * XXX: the struct name is a bit misleading
 */
static void attach_remote_memory(VirtIOBalloon *dev, uint8_t idx)
{
#ifdef DEBUG_VIRTIO_BALLOON
    VirtMachineState *vms = VIRT_MACHINE(qdev_get_machine());
#endif /* DEBUG_VIRTIO_BALLOON */
    MachineState *ms = MACHINE(qdev_get_machine());
    MemMapEntry *resized = &dev->resized[idx];
    Object *memdev = NULL;
    uint64_t req_resize = megs_to_bytes(resized->size);
    Int128 new_size128;

    char bknd_id[BKND_ID_SIZE] = {0};

    if (req_resize <= 0) {
        DPRINTF("Negative resize requested\n");
        return;
    }
    req_resize = QEMU_ALIGN_UP(req_resize, MEM_SECTION_SIZE);
    DPRINTF("req_resize = %#llx\n", req_resize);

   /*
    * XXX: Initially it was considered an error but it can happen when
    * resize is requested proactively through 'balloon XYZ'
    *
    * if (ms->ram_size + req_resize > hw_mme->size) {
    *  fprintf(stderr,"RAM cannot be that big\n");
    *  return;
    * }
    */

    resized->size = req_resize;
    setup_backend_id(bknd_id);
    create_new_backend_object(bknd_id, resized->size);
    /* This is only offset, not an absolute value */
    resized->base = setup_numa_offset(&memdev, bknd_id);

    /* Abstract type for ram- or remote- backends */
    HostMemoryBackend *backend =  MEMORY_BACKEND(memdev);
    MemoryRegion *new_mr =
        host_memory_backend_get_memory(backend, &error_abort);
    nb_numa_nodes++;
    set_max_numa_nodeid(nb_numa_nodes);

    MemoryRegion *ram = find_ram_mr();
    assert(ram);
    memory_region_add_subregion(ram, resized->base, new_mr);
    vmstate_register_ram_global(new_mr);
    new_size128 = int128_add(ram->size, new_mr->size);
    memory_region_set_size(ram, int128_get64(new_size128));

    ms->ram_size = int128_get64(ram->size);
    ram_size = ms->ram_size;

    /* Device register has to be polled and returns an offest */
    DPRINTF("New memory address: %lx, size: %lx",
           dev->resized[idx].base + vms->memmap[VIRT_MEM].base, dev->resized[idx].size);
}

static inline int get_last_backend_id(char *id)
{
    ObjectClass *klass = object_class_by_name(TYPE_MEMORY_BACKEND_REMOTE);
    RemoteMemoryBackendClass *rmbc = REMOTE_MEMORY_BACKEND_CLASS(klass);
    uint32_t last_id;

    last_id = rmbc->get_instances_nb();
    DPRINTF("Last id= %u\n", last_id);

    /* Backend of 1 is a primary RAM and cannot be detached */
    if (last_id == 1) {
        DPRINTF("Cannot remove a primary RAM");
        return -1;
    }

    snprintf(id, BKND_ID_SIZE, "%s%u", TYPE_MEMORY_BACKEND_REMOTE,
            rmbc->get_instances_nb());

    return 0;
}

static inline void clean_numa_info(Object *memdev, ram_addr_t addr,
    uint64_t size)
{
    uint32_t nodenr = nb_numa_nodes - 1;

    numa_info[nodenr].node_mem = 0;
    numa_info[nodenr].node_memdev = NULL;

    numa_info[nodenr].present = false;
    object_unref(memdev);
}

extern void qmp_object_del(const char *id, Error **errp);

static int detach_remote_memory(VirtIOBalloon *dev, uint8_t i)
{
    int ret = 0;
    char id[BKND_ID_SIZE] = {0};
    Object *memdev = NULL;
    HostMemoryBackend *backend = NULL;
    MemoryRegion *last_mr = NULL, *ram = NULL;
    Int128 new_size128;
    MachineState *ms = MACHINE(qdev_get_machine());
    VirtMachineState *vms = VIRT_MACHINE(ms);

    /* Memory is attached based on offsets, not an absolute addr */
    dev->resized[i].base -= vms->memmap[VIRT_MEM].base;
    /*If an address falls down after the beginning of a section */
    dev->resized[i].base = QEMU_ALIGN_DOWN(dev->resized[i].base, MEM_SECTION_SIZE);

    /* Find and remove last memory region */
    ret = get_last_backend_id(id);
    if (ret) {
        goto detach_out;
    }

    memdev = object_resolve_path_type(id, TYPE_MEMORY_BACKEND, NULL);
    if (!memdev) {
        ret = -1;
        goto detach_out;
    }

    /* NUMA setup */
    clean_numa_info(memdev, dev->resized[i].base, dev->resized[i].size);
    nb_numa_nodes--;
    set_max_numa_nodeid(nb_numa_nodes);

    backend =  MEMORY_BACKEND(memdev);
    last_mr = host_memory_backend_get_memory(backend, &error_abort);
    if (!last_mr) {
        ret = -1;
        goto detach_out;
    }
    vmstate_unregister_ram(last_mr, NULL);
    ram = find_ram_mr();
    memory_region_del_subregion(ram, last_mr);

    new_size128 = int128_sub(ram->size, last_mr->size);
    memory_region_set_size(ram, int128_get64(new_size128));
    ms->ram_size = int128_get64(ram->size);
    ram_size = ms->ram_size;

    qmp_object_del(id, &error_abort);

detach_out:
    if (ret) {
        DPRINTF("Error!");
    }

    return ret;
}

#else
static void attach_remote_memory(VirtIOBalloon *dev, uint8_t idx) {}
static void detach_remote_memory(VirtIOBalloon *dev, uint8_t i) {}
#endif /* defined(TARGET_AARCH64) */

/*
 * It is called 8 times to read 8 bytes and merge them up to u64. Actually, the
 * register is u32 so in fact the invokation 1,2,3,5,6,7th are ignored and
 * reading done only at 4th and 8th call.
 * TODO: Once started, it should be locked until finished?
 */
static bool merged_conf_reg_iteratively(uint32_t word_low, uint32_t word_high,
    hwaddr *out_sz)
{
    static uint8_t cnt;
    bool completed = false;

    if (!cnt) {
        *out_sz = 0ULL;
    }
    /* bytes remain rememberred so its enough to read the whole word once its ready */
    switch (cnt) {
    //UNCOMMENT THIS FOR Juno or ZCU102
    //On Juno and ZCU102 writing an ACK (u32) by virtio_cwrite was received
    //here as 4 writes of u8 so 3 intermediate values were stored.
    // case 3:
    //UNCOMMENT THIS FOR the prototype
    //On the prototype it is u32 written once.
    case 0:
        *out_sz |= le32_to_cpu(word_low);
        break;
    //UNCOMMENT THIS FOR Juno or ZCU102
    //On Juno and ZCU102 writing an ACK (u32) by virtio_cwrite was received
    //here as 4 writes of u8 so 3 intermediate values were stored.
    // case 7:
    //UNCOMMENT THIS FOR the prototype
    //On the prototype it is u32 written once.
    case 1:
        *out_sz |= (((uint64_t)le32_to_cpu(word_high)) << 32);
        completed = true;
        break;
    }
    //UNCOMMENT THIS FOR Juno or ZCU102
    // cnt = (cnt + 1) % 8;
    //UNCOMMENT THIS FOR the prototype
    cnt = (cnt + 1) % 2;

    return completed;
}

static bool merged_partial_ack(void)
{
    static uint8_t cnt;
    bool completed = false;
    DPRINTF("cnt: %d", cnt);

    //UNCOMMENT THIS FOR Juno or ZCU102
    //On Juno and ZCU102 writing an ACK (u32) by virtio_cwrite was received
    //here as 4 writes of u8 so 3 intermediate values were stored.
    //Of course this is not the most elegant way of coding.
    // if (3 == cnt) {
    //     completed = true;
    // }
    // cnt = (cnt + 1) % 4;
    //
    //UNCOMMENT THIS FOR the prototype
    //On the prototype it is u32 written once.
    completed = true;

    return completed;
}

static bool merged_partial_reg(void)
{
    static uint8_t cnt;
    bool completed = false;
    DPRINTF("%s: cnt = %d", __func__, cnt);

    //UNCOMMENT THIS FOR Juno or ZCU102
    //On Juno and ZCU102 writing an ACK (u32) by virtio_cwrite was received
    //here as 4 writes of u8 so 3 intermediate values were stored.
    //Of course this is not the most elegant way of coding.
    // if (3 == cnt) {
    //     completed = true;
    // }
    // cnt = (cnt + 1) % 4;
    //UNCOMMENT THIS FOR the prototype
    //On the prototype it is u32 written once.
    completed = true;

    return completed;
}

static inline void virtio_balloon_config_reset_state(VirtIOBalloon *dev)
{
    dev->state_flag = VIRTIO_BALLOON_F_NEUTRAL;
    memset(dev->resized, 0, sizeof(struct MemMapEntry) *
            VIRTIO_MEMSET_SECTION_SLOTS);
    DPRINTF("ACK: Reset size and zeroize offset registers\n");
}

static inline void add_vm_ram_sections_loop(VirtIOBalloon *dev,
    ram_addr_t target)
{
    for (uint8_t i = 0;
            i < VIRTIO_MEMSET_SECTION_SLOTS && target > get_current_ram_size();
            ++i) {
        dev->resized[i].size = (MEM_SECTION_SIZE >> 20);
        attach_remote_memory(dev, i);
    }
}

static void virtio_balloon_set_config(VirtIODevice *vdev,
                                      const uint8_t *config_data)
{
    static uint8_t rem_cnt;
    VirtIOBalloon *dev = VIRTIO_BALLOON(vdev);
    struct virtio_balloon_config config = {0};
    uint32_t oldactual = dev->actual;
    ram_addr_t vm_ram_size = get_current_ram_size();

    memcpy(&config, config_data, sizeof(struct virtio_balloon_config));

    DPRINTF("Input flag :%u, state: %u\n", config.state_flag, dev->state_flag);
    /*
     * State can be changed only if returned back to neutral - 0.
     *
     * Corner_case1: Initially it was considered to work only in OOM-case but
     * the resize can be also requested proactively by QEMU monitor. In this
     * case it is possible that the state is NEUTRAL (because resize was not
     * requested by guest) and ACK is incoming (because guest consumes the info
     * about new RAM).
     *
     * Corner_case2: during hotunplug the series of data is passed in
     * subsequent calls (up to VIRTIO_MEMSET_SECTION_SLOTS) and it is not known
     * a'priori how many of them will be so when VIRTIO_BALLOON_F_HOTUNPLUG_EXE
     * arrives the dev->state has to be changed and jumped to, in the same call
     */
    if (!dev->state_flag && config.state_flag &&
           VIRTIO_BALLOON_F_HOTPLUG_ACK != config.state_flag) {
        /*
         * The flag is 32 bit so they all have to be consumed.
         * Calling merged_parial_reg has a side effect!
         */
        if (merged_partial_reg()) {
            dev->state_flag = le32_to_cpu(config.state_flag);
            DPRINTF("State changed to :%u\n", dev->state_flag);
            /* setup the static counter when entering hotunplug mode */
            /* thanks to this the flag does not have to be send twice */
            if (dev->state_flag == VIRTIO_BALLOON_F_HOTUNPLUG_EXE) {
                DPRINTF("Launching hotunplug action\n");
                goto action;
            }
        }

        return;
    }
    /*
     * If dev->state_flag == 0 and we receive an ACK (config.state_flag==2) we
     * pretend it to be awaited to end-up in a proper case.
     */
    if (!dev->state_flag &&
           VIRTIO_BALLOON_F_HOTPLUG_ACK == config.state_flag) {
        dev->state_flag = VIRTIO_BALLOON_F_HOTPLUG_ACK;
    }

action:
    switch (dev->state_flag) {
    case VIRTIO_BALLOON_F_HOTPLUG:
        /*
         * We are receiving 64-bit value in bytes.  Virtio (ver 1) sends this
         * like that, however it is possible to read multiple values at once
         * but up to 32 bits. Therefore 64bit data has to be read in 2 steps
         * but the function will be called 8 times.
         */
        if (merged_conf_reg_iteratively(config.size_low[0], config.size_high[0],
               &dev->resized[0].size)) {
            /*
             * Upon being interrupted the driver will read configuration registers,
             * which will trigger virtio_balloon_get_config function. After, it
             * will send an ACK.
             */
            add_vm_ram_sections_loop(dev, dev->resized[0].size << 20);
            dev->state_flag = VIRTIO_BALLOON_F_HOTPLUG_ACK;
            virtio_notify_config(vdev);
        }
        break;

    case VIRTIO_BALLOON_F_HOTPLUG_ACK:
        /*
         * Assumption that (offset|size)_low[] _high[] are contiguous in memory
         * and in this order
         */
        if (merged_partial_ack()) {
            DPRINTF("Merged ACK: true");
            memset(config.offset_low, 0, sizeof(typeof(config.offset_low[0])) *
                    VIRTIO_MEMSET_SECTION_SLOTS * 4);
            config.state_flag = VIRTIO_BALLOON_F_NEUTRAL;
            virtio_balloon_config_reset_state(dev);
            memcpy(config_data, &config, sizeof(struct virtio_balloon_config));
        } else {
            DPRINTF("Merged ACK: false");
	}
        break;

    case VIRTIO_BALLOON_F_HOTUNPLUG:
        /*
         * Guest requests for unplugging several phys sections, sends ack when
         * transfer is done and detaching can be performed in a bulk
         */
        if (merged_conf_reg_iteratively(config.offset_low[rem_cnt],
               config.offset_high[rem_cnt], &dev->resized[rem_cnt].base)) {
            /* For now, no need for an ACK sent the guest */
            DPRINTF("to detach [%u] = %#llx\n", rem_cnt,
                    dev->resized[rem_cnt].base);
            rem_cnt++;
            dev->state_flag = VIRTIO_BALLOON_F_NEUTRAL;
        }
        break;

    case VIRTIO_BALLOON_F_HOTUNPLUG_EXE:
        for (uint8_t i = 0; i < rem_cnt; ++i) {
            DPRINTF("detaching[%u]: %#llx\n", i, dev->resized[i].base);
            detach_remote_memory(dev, i);
        }
        rem_cnt = 0;
        virtio_balloon_config_reset_state(dev);
        memcpy(config_data, &config, sizeof(struct virtio_balloon_config));
        break;

    default:
    case VIRTIO_BALLOON_F_NEUTRAL:

        DPRINTF("Default ballooning");
        /* I have setup num_pages after hotplug for future reads */
        if (config.num_pages) {
            DPRINTF("Setting config.num_pages");
            dev->num_pages = le32_to_cpu(config.num_pages);
        }

        dev->actual = le32_to_cpu(config.actual);

        if (dev->actual != oldactual) {
            qapi_event_send_balloon_change(vm_ram_size -
                           ((ram_addr_t) dev->actual << VIRTIO_BALLOON_PFN_SHIFT),
                           &error_abort);
        }
        trace_virtio_balloon_set_config(dev->actual, oldactual);
        break;
    }
    trace_virtio_balloon_set_config(dev->actual, oldactual);
}

static uint64_t virtio_balloon_get_features(VirtIODevice *vdev, uint64_t f,
                                            Error **errp)
{
    VirtIOBalloon *dev = VIRTIO_BALLOON(vdev);
    f |= dev->host_features;
    virtio_add_feature(&f, VIRTIO_BALLOON_F_STATS_VQ);
    return f;
}

static void virtio_balloon_stat(void *opaque, BalloonInfo *info)
{
    VirtIOBalloon *dev = opaque;
    info->actual = get_current_ram_size() - ((uint64_t) dev->actual <<
                                             VIRTIO_BALLOON_PFN_SHIFT);
}

static void virtio_balloon_to_target(void *opaque, ram_addr_t target)
{
    VirtIOBalloon *dev = VIRTIO_BALLOON(opaque);
    VirtIODevice *vdev = VIRTIO_DEVICE(dev);
    ram_addr_t vm_ram_size = get_current_ram_size();

    if (target > vm_ram_size) {
        target = vm_ram_size;
    }
    if (target) {
        dev->num_pages = (vm_ram_size - target) >> VIRTIO_BALLOON_PFN_SHIFT;
        virtio_notify_config(vdev);
    }
    trace_virtio_balloon_to_target(target, dev->num_pages);
}

static void virtio_setmaxmem_to_target(void *opaque, ram_addr_t target)
{
    VirtIOBalloon *dev = VIRTIO_BALLOON(opaque);
    VirtIODevice *vdev = VIRTIO_DEVICE(dev);
    ram_addr_t vm_ram_size = get_current_ram_size();
    size_t sec_to_remove = 0;

    DPRINTF("current RAM: %#llx, target: %#llx\n", vm_ram_size, target);
    if (target > vm_ram_size) {
        /* first, perform physical hotplug */
        add_vm_ram_sections_loop(dev, target);
        virtio_notify_config(vdev);
    } else if (target) {
        /*
         * ask the kernel how many memory sections to remove
         * the new ram_sz is rounded up to full memory sections so its never
         * less than requested
         */
        sec_to_remove = (vm_ram_size - target) / MEM_SECTION_SIZE;
        DPRINTF("sections to remove: %lu\n", sec_to_remove);
        for (uint8_t i = 0; i < sec_to_remove; ++i) {
            dev->resized[i].size = VIRTIO_MEMSET_HOTREMOVE_MAGIC;
            dev->resized[i].base = 0;
        }
        virtio_notify_config(vdev);
    }
}

static int virtio_balloon_post_load_device(void *opaque, int version_id)
{
    VirtIOBalloon *s = VIRTIO_BALLOON(opaque);

    if (balloon_stats_enabled(s)) {
        balloon_stats_change_timer(s, s->stats_poll_interval);
    }
    return 0;
}

static const VMStateDescription vmstate_virtio_balloon_device = {
    .name = "virtio-balloon-device",
    .version_id = 1,
    .minimum_version_id = 1,
    .post_load = virtio_balloon_post_load_device,
    .fields = (VMStateField[]) {
        VMSTATE_UINT32(num_pages, VirtIOBalloon),
        VMSTATE_UINT32(actual, VirtIOBalloon),
        VMSTATE_END_OF_LIST()
    },
};

static void virtio_balloon_device_realize(DeviceState *dev, Error **errp)
{
    VirtIODevice *vdev = VIRTIO_DEVICE(dev);
    VirtIOBalloon *s = VIRTIO_BALLOON(dev);
    int ret;

    virtio_init(vdev, "virtio-balloon", VIRTIO_ID_BALLOON,
                sizeof(struct virtio_balloon_config));

    ret = qemu_add_balloon_handler(virtio_balloon_to_target,
                                   virtio_balloon_stat, s);

    if (ret < 0) {
        error_setg(errp, "Only one balloon device is supported");
        virtio_cleanup(vdev);
        return;
    }

    s->ivq = virtio_add_queue(vdev, 128, virtio_balloon_handle_output);
    s->dvq = virtio_add_queue(vdev, 128, virtio_balloon_handle_output);
    s->svq = virtio_add_queue(vdev, 128, virtio_balloon_receive_stats);

    ret = qemu_add_setmaxmem_handler(virtio_setmaxmem_to_target, s);
    if (ret < 0) {
        error_setg(errp, "Only one setmaxmem registration allowed");
        virtio_cleanup(vdev);
        return;
    }

    reset_stats(s);
}

static void virtio_balloon_device_unrealize(DeviceState *dev, Error **errp)
{
    VirtIODevice *vdev = VIRTIO_DEVICE(dev);
    VirtIOBalloon *s = VIRTIO_BALLOON(dev);

    balloon_stats_destroy_timer(s);
    qemu_remove_balloon_handler(s);
    virtio_cleanup(vdev);
}

static void virtio_balloon_device_reset(VirtIODevice *vdev)
{
    VirtIOBalloon *s = VIRTIO_BALLOON(vdev);

    if (s->stats_vq_elem != NULL) {
        virtqueue_unpop(s->svq, s->stats_vq_elem, 0);
        g_free(s->stats_vq_elem);
        s->stats_vq_elem = NULL;
    }
}

static void virtio_balloon_set_status(VirtIODevice *vdev, uint8_t status)
{
    VirtIOBalloon *s = VIRTIO_BALLOON(vdev);

    if (!s->stats_vq_elem && vdev->vm_running &&
        (status & VIRTIO_CONFIG_S_DRIVER_OK) && virtqueue_rewind(s->svq, 1)) {
        /* poll stats queue for the element we have discarded when the VM
         * was stopped */
        virtio_balloon_receive_stats(vdev, s->svq);
    }
}

static void virtio_balloon_instance_init(Object *obj)
{
    VirtIOBalloon *s = VIRTIO_BALLOON(obj);

    object_property_add(obj, "guest-stats", "guest statistics",
                        balloon_stats_get_all, NULL, NULL, s, NULL);

    object_property_add(obj, "guest-stats-polling-interval", "int",
                        balloon_stats_get_poll_interval,
                        balloon_stats_set_poll_interval,
                        NULL, s, NULL);

    s->state_flag = VIRTIO_BALLOON_F_NEUTRAL;
}

static const VMStateDescription vmstate_virtio_balloon = {
    .name = "virtio-balloon",
    .minimum_version_id = 1,
    .version_id = 1,
    .fields = (VMStateField[]) {
        VMSTATE_VIRTIO_DEVICE,
        VMSTATE_END_OF_LIST()
    },
};

static Property virtio_balloon_properties[] = {
    DEFINE_PROP_BIT("deflate-on-oom", VirtIOBalloon, host_features,
                    VIRTIO_BALLOON_F_DEFLATE_ON_OOM, false),
    DEFINE_PROP_END_OF_LIST(),
};

static void virtio_balloon_class_init(ObjectClass *klass, void *data)
{
    DeviceClass *dc = DEVICE_CLASS(klass);
    VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass);

    dc->props = virtio_balloon_properties;
    dc->vmsd = &vmstate_virtio_balloon;
    set_bit(DEVICE_CATEGORY_MISC, dc->categories);
    vdc->realize = virtio_balloon_device_realize;
    vdc->unrealize = virtio_balloon_device_unrealize;
    vdc->reset = virtio_balloon_device_reset;
    vdc->get_config = virtio_balloon_get_config;
    vdc->set_config = virtio_balloon_set_config;
    vdc->get_features = virtio_balloon_get_features;
    vdc->set_status = virtio_balloon_set_status;
    vdc->vmsd = &vmstate_virtio_balloon_device;
}

static const TypeInfo virtio_balloon_info = {
    .name = TYPE_VIRTIO_BALLOON,
    .parent = TYPE_VIRTIO_DEVICE,
    .instance_size = sizeof(VirtIOBalloon),
    .instance_init = virtio_balloon_instance_init,
    .class_init = virtio_balloon_class_init,
};

static void virtio_register_types(void)
{
    type_register_static(&virtio_balloon_info);
}

type_init(virtio_register_types)
