static int convert_coeffs(AVFilterContext *ctx, AVFilterLink *inlink)

{

    struct HeadphoneContext *s = ctx->priv;

    const int ir_len = s->ir_len;

    int nb_irs = s->nb_irs;

    int nb_input_channels = ctx->inputs[0]->channels;

    float gain_lin = expf((s->gain - 3 * nb_input_channels) / 20 * M_LN10);

    FFTComplex *data_hrtf_l = NULL;

    FFTComplex *data_hrtf_r = NULL;

    FFTComplex *fft_in_l = NULL;

    FFTComplex *fft_in_r = NULL;

    float *data_ir_l = NULL;

    float *data_ir_r = NULL;

    int offset = 0;

    int n_fft;

    int i, j;

    s->buffer_length = 1 << (32 - ff_clz(s->ir_len));

    s->n_fft = n_fft = 1 << (32 - ff_clz(s->ir_len + inlink->sample_rate));

    if (s->type == FREQUENCY_DOMAIN) {

        fft_in_l = av_calloc(n_fft, sizeof(*fft_in_l));

        fft_in_r = av_calloc(n_fft, sizeof(*fft_in_r));

        if (!fft_in_l || !fft_in_r) {

            return AVERROR(ENOMEM);

        }

        av_fft_end(s->fft[0]);

        av_fft_end(s->fft[1]);

        s->fft[0] = av_fft_init(log2(s->n_fft), 0);

        s->fft[1] = av_fft_init(log2(s->n_fft), 0);

        av_fft_end(s->ifft[0]);

        av_fft_end(s->ifft[1]);

        s->ifft[0] = av_fft_init(log2(s->n_fft), 1);

        s->ifft[1] = av_fft_init(log2(s->n_fft), 1);

        if (!s->fft[0] || !s->fft[1] || !s->ifft[0] || !s->ifft[1]) {

            av_log(ctx, AV_LOG_ERROR, "Unable to create FFT contexts of size %d.\n", s->n_fft);

            return AVERROR(ENOMEM);

        }

    }

    s->data_ir[0] = av_calloc(FFALIGN(s->ir_len, 16), sizeof(float) * s->nb_irs);

    s->data_ir[1] = av_calloc(FFALIGN(s->ir_len, 16), sizeof(float) * s->nb_irs);

    s->delay[0] = av_malloc_array(s->nb_irs, sizeof(float));

    s->delay[1] = av_malloc_array(s->nb_irs, sizeof(float));

    if (s->type == TIME_DOMAIN) {

        s->ringbuffer[0] = av_calloc(s->buffer_length, sizeof(float) * nb_input_channels);

        s->ringbuffer[1] = av_calloc(s->buffer_length, sizeof(float) * nb_input_channels);

    } else {

        s->ringbuffer[0] = av_calloc(s->buffer_length, sizeof(float));

        s->ringbuffer[1] = av_calloc(s->buffer_length, sizeof(float));

        s->temp_fft[0] = av_malloc_array(s->n_fft, sizeof(FFTComplex));

        s->temp_fft[1] = av_malloc_array(s->n_fft, sizeof(FFTComplex));

        if (!s->temp_fft[0] || !s->temp_fft[1])

            return AVERROR(ENOMEM);

    }

    if (!s->data_ir[0] || !s->data_ir[1] ||

        !s->ringbuffer[0] || !s->ringbuffer[1])

        return AVERROR(ENOMEM);

    s->in[0].frame = ff_get_audio_buffer(ctx->inputs[0], s->size);

    if (!s->in[0].frame)

        return AVERROR(ENOMEM);

    for (i = 0; i < s->nb_irs; i++) {

        s->in[i + 1].frame = ff_get_audio_buffer(ctx->inputs[i + 1], s->ir_len);

        if (!s->in[i + 1].frame)

            return AVERROR(ENOMEM);

    }

    if (s->type == TIME_DOMAIN) {

        s->temp_src[0] = av_calloc(FFALIGN(ir_len, 16), sizeof(float));

        s->temp_src[1] = av_calloc(FFALIGN(ir_len, 16), sizeof(float));

        data_ir_l = av_calloc(nb_irs * FFALIGN(ir_len, 16), sizeof(*data_ir_l));

        data_ir_r = av_calloc(nb_irs * FFALIGN(ir_len, 16), sizeof(*data_ir_r));

        if (!data_ir_r || !data_ir_l || !s->temp_src[0] || !s->temp_src[1]) {

            av_free(data_ir_l);

            av_free(data_ir_r);

            return AVERROR(ENOMEM);

        }

    } else {

        data_hrtf_l = av_malloc_array(n_fft, sizeof(*data_hrtf_l) * nb_irs);

        data_hrtf_r = av_malloc_array(n_fft, sizeof(*data_hrtf_r) * nb_irs);

        if (!data_hrtf_r || !data_hrtf_l) {

            av_free(data_hrtf_l);

            av_free(data_hrtf_r);

            return AVERROR(ENOMEM);

        }

    }

    for (i = 0; i < s->nb_irs; i++) {

        int len = s->in[i + 1].ir_len;

        int delay_l = s->in[i + 1].delay_l;

        int delay_r = s->in[i + 1].delay_r;

        int idx = -1;

        float *ptr;

        for (j = 0; j < inlink->channels; j++) {

            if (s->mapping[i] < 0) {

                continue;

            }

            if ((av_channel_layout_extract_channel(inlink->channel_layout, j)) == (1LL << s->mapping[i])) {

                idx = j;

                break;

            }

        }

        if (idx == -1)

            continue;

        av_audio_fifo_read(s->in[i + 1].fifo, (void **)s->in[i + 1].frame->extended_data, len);

        ptr = (float *)s->in[i + 1].frame->extended_data[0];

        if (s->type == TIME_DOMAIN) {

            offset = idx * FFALIGN(len, 16);

            for (j = 0; j < len; j++) {

                data_ir_l[offset + j] = ptr[len * 2 - j * 2 - 2] * gain_lin;

                data_ir_r[offset + j] = ptr[len * 2 - j * 2 - 1] * gain_lin;

            }

        } else {

            memset(fft_in_l, 0, n_fft * sizeof(*fft_in_l));

            memset(fft_in_r, 0, n_fft * sizeof(*fft_in_r));

            offset = idx * n_fft;

            for (j = 0; j < len; j++) {

                fft_in_l[delay_l + j].re = ptr[j * 2    ] * gain_lin;

                fft_in_r[delay_r + j].re = ptr[j * 2 + 1] * gain_lin;

            }

            av_fft_permute(s->fft[0], fft_in_l);

            av_fft_calc(s->fft[0], fft_in_l);

            memcpy(data_hrtf_l + offset, fft_in_l, n_fft * sizeof(*fft_in_l));

            av_fft_permute(s->fft[0], fft_in_r);

            av_fft_calc(s->fft[0], fft_in_r);

            memcpy(data_hrtf_r + offset, fft_in_r, n_fft * sizeof(*fft_in_r));

        }

    }

    if (s->type == TIME_DOMAIN) {

        memcpy(s->data_ir[0], data_ir_l, sizeof(float) * nb_irs * FFALIGN(ir_len, 16));

        memcpy(s->data_ir[1], data_ir_r, sizeof(float) * nb_irs * FFALIGN(ir_len, 16));

        av_freep(&data_ir_l);

        av_freep(&data_ir_r);

    } else {

        s->data_hrtf[0] = av_malloc_array(n_fft * s->nb_irs, sizeof(FFTComplex));

        s->data_hrtf[1] = av_malloc_array(n_fft * s->nb_irs, sizeof(FFTComplex));

        if (!s->data_hrtf[0] || !s->data_hrtf[1]) {

            av_freep(&data_hrtf_l);

            av_freep(&data_hrtf_r);

            av_freep(&fft_in_l);

            av_freep(&fft_in_r);

            return AVERROR(ENOMEM);

        }

        memcpy(s->data_hrtf[0], data_hrtf_l,

            sizeof(FFTComplex) * nb_irs * n_fft);

        memcpy(s->data_hrtf[1], data_hrtf_r,

            sizeof(FFTComplex) * nb_irs * n_fft);

        av_freep(&data_hrtf_l);

        av_freep(&data_hrtf_r);

        av_freep(&fft_in_l);

        av_freep(&fft_in_r);

    }

    s->have_hrirs = 1;

    return 0;

}


static void nic_cleanup(VLANClientState *nc)

{

    dp8393xState *s = DO_UPCAST(NICState, nc, nc)->opaque;

    cpu_unregister_io_memory(s->mmio_index);

    qemu_del_timer(s->watchdog);

    qemu_free_timer(s->watchdog);

    g_free(s);

}


static void ide_init1(IDEBus *bus, int unit)

{

    static int drive_serial = 1;

    IDEState *s = &bus->ifs[unit];

    s->bus = bus;

    s->unit = unit;

    s->drive_serial = drive_serial++;

    /* we need at least 2k alignment for accessing CDROMs using O_DIRECT */

    s->io_buffer = qemu_memalign(2048, IDE_DMA_BUF_SECTORS*512 + 4);

    s->io_buffer_total_len = IDE_DMA_BUF_SECTORS*512 + 4;

    s->smart_selftest_data = qemu_blockalign(s->bs, 512);

    s->sector_write_timer = qemu_new_timer_ns(vm_clock,

                                           ide_sector_write_timer_cb, s);

}


static int iscsi_create(const char *filename, QEMUOptionParameter *options)

{

    int ret = 0;

    int64_t total_size = 0;

    BlockDriverState bs;

    IscsiLun *iscsilun = NULL;

    QDict *bs_options;

    memset(&bs, 0, sizeof(BlockDriverState));

    /* Read out options */

    while (options && options->name) {

        if (!strcmp(options->name, "size")) {

            total_size = options->value.n / BDRV_SECTOR_SIZE;

        }

        options++;

    }

    bs.opaque = g_malloc0(sizeof(struct IscsiLun));

    iscsilun = bs.opaque;

    bs_options = qdict_new();

    qdict_put(bs_options, "filename", qstring_from_str(filename));

    ret = iscsi_open(&bs, bs_options, 0);

    QDECREF(bs_options);

    if (ret != 0) {

        goto out;

    }

    if (iscsilun->nop_timer) {

        timer_del(iscsilun->nop_timer);

        timer_free(iscsilun->nop_timer);

    }

    if (iscsilun->type != TYPE_DISK) {

        ret = -ENODEV;

        goto out;

    }

    if (bs.total_sectors < total_size) {

        ret = -ENOSPC;

        goto out;

    }

    ret = 0;

out:

    if (iscsilun->iscsi != NULL) {

        iscsi_destroy_context(iscsilun->iscsi);

    }

    g_free(bs.opaque);

    return ret;

}


Exynos4210State *exynos4210_init(MemoryRegion *system_mem,

        unsigned long ram_size)

{

    int i, n;

    Exynos4210State *s = g_new(Exynos4210State, 1);

    qemu_irq gate_irq[EXYNOS4210_NCPUS][EXYNOS4210_IRQ_GATE_NINPUTS];

    unsigned long mem_size;

    DeviceState *dev;

    SysBusDevice *busdev;

    ObjectClass *cpu_oc;

    cpu_oc = cpu_class_by_name(TYPE_ARM_CPU, "cortex-a9");

    assert(cpu_oc);

    for (n = 0; n < EXYNOS4210_NCPUS; n++) {

        Object *cpuobj = object_new(object_class_get_name(cpu_oc));

        Error *err = NULL;

        /* By default A9 CPUs have EL3 enabled.  This board does not currently

         * support EL3 so the CPU EL3 property is disabled before realization.

         */

        if (object_property_find(cpuobj, "has_el3", NULL)) {

            object_property_set_bool(cpuobj, false, "has_el3", &err);

            if (err) {

                error_report_err(err);

                exit(1);

            }

        }

        s->cpu[n] = ARM_CPU(cpuobj);

        object_property_set_int(cpuobj, EXYNOS4210_SMP_PRIVATE_BASE_ADDR,

                                "reset-cbar", &error_abort);

        object_property_set_bool(cpuobj, true, "realized", &err);

        if (err) {

            error_report_err(err);

            exit(1);

        }

    }

    /*** IRQs ***/

    s->irq_table = exynos4210_init_irq(&s->irqs);

    /* IRQ Gate */

    for (i = 0; i < EXYNOS4210_NCPUS; i++) {

        dev = qdev_create(NULL, "exynos4210.irq_gate");

        qdev_prop_set_uint32(dev, "n_in", EXYNOS4210_IRQ_GATE_NINPUTS);

        qdev_init_nofail(dev);

        /* Get IRQ Gate input in gate_irq */

        for (n = 0; n < EXYNOS4210_IRQ_GATE_NINPUTS; n++) {

            gate_irq[i][n] = qdev_get_gpio_in(dev, n);

        }

        busdev = SYS_BUS_DEVICE(dev);

        /* Connect IRQ Gate output to CPU's IRQ line */

        sysbus_connect_irq(busdev, 0,

                           qdev_get_gpio_in(DEVICE(s->cpu[i]), ARM_CPU_IRQ));

    }

    /* Private memory region and Internal GIC */

    dev = qdev_create(NULL, "a9mpcore_priv");

    qdev_prop_set_uint32(dev, "num-cpu", EXYNOS4210_NCPUS);

    qdev_init_nofail(dev);

    busdev = SYS_BUS_DEVICE(dev);

    sysbus_mmio_map(busdev, 0, EXYNOS4210_SMP_PRIVATE_BASE_ADDR);

    for (n = 0; n < EXYNOS4210_NCPUS; n++) {

        sysbus_connect_irq(busdev, n, gate_irq[n][0]);

    }

    for (n = 0; n < EXYNOS4210_INT_GIC_NIRQ; n++) {

        s->irqs.int_gic_irq[n] = qdev_get_gpio_in(dev, n);

    }

    /* Cache controller */

    sysbus_create_simple("l2x0", EXYNOS4210_L2X0_BASE_ADDR, NULL);

    /* External GIC */

    dev = qdev_create(NULL, "exynos4210.gic");

    qdev_prop_set_uint32(dev, "num-cpu", EXYNOS4210_NCPUS);

    qdev_init_nofail(dev);

    busdev = SYS_BUS_DEVICE(dev);

    /* Map CPU interface */

    sysbus_mmio_map(busdev, 0, EXYNOS4210_EXT_GIC_CPU_BASE_ADDR);

    /* Map Distributer interface */

    sysbus_mmio_map(busdev, 1, EXYNOS4210_EXT_GIC_DIST_BASE_ADDR);

    for (n = 0; n < EXYNOS4210_NCPUS; n++) {

        sysbus_connect_irq(busdev, n, gate_irq[n][1]);

    }

    for (n = 0; n < EXYNOS4210_EXT_GIC_NIRQ; n++) {

        s->irqs.ext_gic_irq[n] = qdev_get_gpio_in(dev, n);

    }

    /* Internal Interrupt Combiner */

    dev = qdev_create(NULL, "exynos4210.combiner");

    qdev_init_nofail(dev);

    busdev = SYS_BUS_DEVICE(dev);

    for (n = 0; n < EXYNOS4210_MAX_INT_COMBINER_OUT_IRQ; n++) {

        sysbus_connect_irq(busdev, n, s->irqs.int_gic_irq[n]);

    }

    exynos4210_combiner_get_gpioin(&s->irqs, dev, 0);

    sysbus_mmio_map(busdev, 0, EXYNOS4210_INT_COMBINER_BASE_ADDR);

    /* External Interrupt Combiner */

    dev = qdev_create(NULL, "exynos4210.combiner");

    qdev_prop_set_uint32(dev, "external", 1);

    qdev_init_nofail(dev);

    busdev = SYS_BUS_DEVICE(dev);

    for (n = 0; n < EXYNOS4210_MAX_INT_COMBINER_OUT_IRQ; n++) {

        sysbus_connect_irq(busdev, n, s->irqs.ext_gic_irq[n]);

    }

    exynos4210_combiner_get_gpioin(&s->irqs, dev, 1);

    sysbus_mmio_map(busdev, 0, EXYNOS4210_EXT_COMBINER_BASE_ADDR);

    /* Initialize board IRQs. */

    exynos4210_init_board_irqs(&s->irqs);

    /*** Memory ***/

    /* Chip-ID and OMR */

    memory_region_init_io(&s->chipid_mem, NULL, &exynos4210_chipid_and_omr_ops,

        NULL, "exynos4210.chipid", sizeof(chipid_and_omr));

    memory_region_add_subregion(system_mem, EXYNOS4210_CHIPID_ADDR,

                                &s->chipid_mem);

    /* Internal ROM */

    memory_region_init_ram(&s->irom_mem, NULL, "exynos4210.irom",

                           EXYNOS4210_IROM_SIZE, &error_abort);

    vmstate_register_ram_global(&s->irom_mem);

    memory_region_set_readonly(&s->irom_mem, true);

    memory_region_add_subregion(system_mem, EXYNOS4210_IROM_BASE_ADDR,

                                &s->irom_mem);

    /* mirror of iROM */

    memory_region_init_alias(&s->irom_alias_mem, NULL, "exynos4210.irom_alias",

                             &s->irom_mem,

                             0,

                             EXYNOS4210_IROM_SIZE);

    memory_region_set_readonly(&s->irom_alias_mem, true);

    memory_region_add_subregion(system_mem, EXYNOS4210_IROM_MIRROR_BASE_ADDR,

                                &s->irom_alias_mem);

    /* Internal RAM */

    memory_region_init_ram(&s->iram_mem, NULL, "exynos4210.iram",

                           EXYNOS4210_IRAM_SIZE, &error_abort);

    vmstate_register_ram_global(&s->iram_mem);

    memory_region_add_subregion(system_mem, EXYNOS4210_IRAM_BASE_ADDR,

                                &s->iram_mem);

    /* DRAM */

    mem_size = ram_size;

    if (mem_size > EXYNOS4210_DRAM_MAX_SIZE) {

        memory_region_init_ram(&s->dram1_mem, NULL, "exynos4210.dram1",

                mem_size - EXYNOS4210_DRAM_MAX_SIZE, &error_abort);

        vmstate_register_ram_global(&s->dram1_mem);

        memory_region_add_subregion(system_mem, EXYNOS4210_DRAM1_BASE_ADDR,

                &s->dram1_mem);

        mem_size = EXYNOS4210_DRAM_MAX_SIZE;

    }

    memory_region_init_ram(&s->dram0_mem, NULL, "exynos4210.dram0", mem_size,

                           &error_abort);

    vmstate_register_ram_global(&s->dram0_mem);

    memory_region_add_subregion(system_mem, EXYNOS4210_DRAM0_BASE_ADDR,

            &s->dram0_mem);

   /* PMU.

    * The only reason of existence at the moment is that secondary CPU boot

    * loader uses PMU INFORM5 register as a holding pen.

    */

    sysbus_create_simple("exynos4210.pmu", EXYNOS4210_PMU_BASE_ADDR, NULL);

    /* PWM */

    sysbus_create_varargs("exynos4210.pwm", EXYNOS4210_PWM_BASE_ADDR,

                          s->irq_table[exynos4210_get_irq(22, 0)],

                          s->irq_table[exynos4210_get_irq(22, 1)],

                          s->irq_table[exynos4210_get_irq(22, 2)],

                          s->irq_table[exynos4210_get_irq(22, 3)],

                          s->irq_table[exynos4210_get_irq(22, 4)],

                          NULL);

    /* RTC */

    sysbus_create_varargs("exynos4210.rtc", EXYNOS4210_RTC_BASE_ADDR,

                          s->irq_table[exynos4210_get_irq(23, 0)],

                          s->irq_table[exynos4210_get_irq(23, 1)],

                          NULL);

    /* Multi Core Timer */

    dev = qdev_create(NULL, "exynos4210.mct");

    qdev_init_nofail(dev);

    busdev = SYS_BUS_DEVICE(dev);

    for (n = 0; n < 4; n++) {

        /* Connect global timer interrupts to Combiner gpio_in */

        sysbus_connect_irq(busdev, n,

                s->irq_table[exynos4210_get_irq(1, 4 + n)]);

    }

    /* Connect local timer interrupts to Combiner gpio_in */

    sysbus_connect_irq(busdev, 4,

            s->irq_table[exynos4210_get_irq(51, 0)]);

    sysbus_connect_irq(busdev, 5,

            s->irq_table[exynos4210_get_irq(35, 3)]);

    sysbus_mmio_map(busdev, 0, EXYNOS4210_MCT_BASE_ADDR);

    /*** I2C ***/

    for (n = 0; n < EXYNOS4210_I2C_NUMBER; n++) {

        uint32_t addr = EXYNOS4210_I2C_BASE_ADDR + EXYNOS4210_I2C_SHIFT * n;

        qemu_irq i2c_irq;

        if (n < 8) {

            i2c_irq = s->irq_table[exynos4210_get_irq(EXYNOS4210_I2C_INTG, n)];

        } else {

            i2c_irq = s->irq_table[exynos4210_get_irq(EXYNOS4210_HDMI_INTG, 1)];

        }

        dev = qdev_create(NULL, "exynos4210.i2c");

        qdev_init_nofail(dev);

        busdev = SYS_BUS_DEVICE(dev);

        sysbus_connect_irq(busdev, 0, i2c_irq);

        sysbus_mmio_map(busdev, 0, addr);

        s->i2c_if[n] = (I2CBus *)qdev_get_child_bus(dev, "i2c");

    }

    /*** UARTs ***/

    exynos4210_uart_create(EXYNOS4210_UART0_BASE_ADDR,

                           EXYNOS4210_UART0_FIFO_SIZE, 0, NULL,

                  s->irq_table[exynos4210_get_irq(EXYNOS4210_UART_INT_GRP, 0)]);

    exynos4210_uart_create(EXYNOS4210_UART1_BASE_ADDR,

                           EXYNOS4210_UART1_FIFO_SIZE, 1, NULL,

                  s->irq_table[exynos4210_get_irq(EXYNOS4210_UART_INT_GRP, 1)]);

    exynos4210_uart_create(EXYNOS4210_UART2_BASE_ADDR,

                           EXYNOS4210_UART2_FIFO_SIZE, 2, NULL,

                  s->irq_table[exynos4210_get_irq(EXYNOS4210_UART_INT_GRP, 2)]);

    exynos4210_uart_create(EXYNOS4210_UART3_BASE_ADDR,

                           EXYNOS4210_UART3_FIFO_SIZE, 3, NULL,

                  s->irq_table[exynos4210_get_irq(EXYNOS4210_UART_INT_GRP, 3)]);

    /*** Display controller (FIMD) ***/

    sysbus_create_varargs("exynos4210.fimd", EXYNOS4210_FIMD0_BASE_ADDR,

            s->irq_table[exynos4210_get_irq(11, 0)],

            s->irq_table[exynos4210_get_irq(11, 1)],

            s->irq_table[exynos4210_get_irq(11, 2)],

            NULL);

    sysbus_create_simple(TYPE_EXYNOS4210_EHCI, EXYNOS4210_EHCI_BASE_ADDR,

            s->irq_table[exynos4210_get_irq(28, 3)]);

    return s;

}


void ff_put_h264_qpel8_mc22_msa(uint8_t *dst, const uint8_t *src,

                                ptrdiff_t stride)

{

    avc_luma_mid_8w_msa(src - (2 * stride) - 2, stride, dst, stride, 8);

}


static int fbdev_write_packet(AVFormatContext *h, AVPacket *pkt)

{

    FBDevContext *fbdev = h->priv_data;

    uint8_t *pin, *pout;

    enum AVPixelFormat fb_pix_fmt;

    int disp_height;

    int bytes_to_copy;

    AVCodecContext *codec_ctx = h->streams[fbdev->index]->codec;

    enum AVPixelFormat video_pix_fmt = codec_ctx->pix_fmt;

    int video_width = codec_ctx->width;

    int video_height = codec_ctx->height;

    int bytes_per_pixel = ((codec_ctx->bits_per_coded_sample + 7) >> 3);

    int src_line_size = video_width * bytes_per_pixel;

    int i;

    if (fbdev->index != pkt->stream_index)

        return 0;

    if (ioctl(fbdev->fd, FBIOGET_VSCREENINFO, &fbdev->varinfo) < 0)

        av_log(h, AV_LOG_WARNING,

               "Error refreshing variable info: %s\n", av_err2str(AVERROR(errno)));

    fb_pix_fmt = ff_get_pixfmt_from_fb_varinfo(&fbdev->varinfo);

    if (fb_pix_fmt != video_pix_fmt) {

        av_log(h, AV_LOG_ERROR, "Pixel format %s is not supported, use %s\n",

               av_get_pix_fmt_name(video_pix_fmt), av_get_pix_fmt_name(fb_pix_fmt));

        return AVERROR(EINVAL);

    }

    disp_height = FFMIN(fbdev->varinfo.yres, video_height);

    bytes_to_copy = FFMIN(fbdev->varinfo.xres, video_width) * bytes_per_pixel;

    pin  = pkt->data;

    pout = fbdev->data +

           bytes_per_pixel * fbdev->varinfo.xoffset +

           fbdev->varinfo.yoffset * fbdev->fixinfo.line_length;

    if (fbdev->xoffset) {

        if (fbdev->xoffset < 0) {

            if (-fbdev->xoffset >= video_width) //nothing to display

                return 0;

            bytes_to_copy += fbdev->xoffset * bytes_per_pixel;

            pin -= fbdev->xoffset * bytes_per_pixel;

        } else {

            int diff = (video_width + fbdev->xoffset) - fbdev->varinfo.xres;

            if (diff > 0) {

                if (diff >= video_width) //nothing to display

                    return 0;

                bytes_to_copy -= diff * bytes_per_pixel;

            }

            pout += bytes_per_pixel * fbdev->xoffset;

        }

    }

    if (fbdev->yoffset) {

        if (fbdev->yoffset < 0) {

            if (-fbdev->yoffset >= video_height) //nothing to display

                return 0;

            disp_height += fbdev->yoffset;

            pin -= fbdev->yoffset * src_line_size;

        } else {

            int diff = (video_height + fbdev->yoffset) - fbdev->varinfo.yres;

            if (diff > 0) {

                if (diff >= video_height) //nothing to display

                    return 0;

                disp_height -= diff;

            }

            pout += fbdev->yoffset * fbdev->fixinfo.line_length;

        }

    }

    for (i = 0; i < disp_height; i++) {

        memcpy(pout, pin, bytes_to_copy);

        pout += fbdev->fixinfo.line_length;

        pin  += src_line_size;

    }

    return 0;

}


static void mxf_read_pixel_layout(ByteIOContext *pb, MXFDescriptor *descriptor)

{

    int code, value, ofs = 0;

    char layout[16] = {};

    do {

        code = get_byte(pb);

        value = get_byte(pb);

        dprintf(NULL, "pixel layout: code %#x\n", code);

        if (ofs < 16) {

            layout[ofs++] = code;

            layout[ofs++] = value;

        }

    } while (code != 0); /* SMPTE 377M E.2.46 */

    ff_mxf_decode_pixel_layout(layout, &descriptor->pix_fmt);

}


static int xmv_read_header(AVFormatContext *s)

{

    XMVDemuxContext *xmv = s->priv_data;

    AVIOContext     *pb  = s->pb;

    AVStream        *vst = NULL;

    uint32_t file_version;

    uint32_t this_packet_size;

    uint16_t audio_track;

    int ret;

    avio_skip(pb, 4); /* Next packet size */

    this_packet_size = avio_rl32(pb);

    avio_skip(pb, 4); /* Max packet size */

    avio_skip(pb, 4); /* "xobX" */

    file_version = avio_rl32(pb);

    if ((file_version != 4) && (file_version != 2))

        avpriv_request_sample(s, "Uncommon version %d", file_version);

    /* Video track */

    vst = avformat_new_stream(s, NULL);

    if (!vst)

        return AVERROR(ENOMEM);

    avpriv_set_pts_info(vst, 32, 1, 1000);

    vst->codec->codec_type = AVMEDIA_TYPE_VIDEO;

    vst->codec->codec_id   = AV_CODEC_ID_WMV2;

    vst->codec->codec_tag  = MKBETAG('W', 'M', 'V', '2');

    vst->codec->width      = avio_rl32(pb);

    vst->codec->height     = avio_rl32(pb);

    vst->duration          = avio_rl32(pb);

    xmv->video.stream_index = vst->index;

    /* Audio tracks */

    xmv->audio_track_count = avio_rl16(pb);

    avio_skip(pb, 2); /* Unknown (padding?) */

    xmv->audio_tracks = av_malloc(xmv->audio_track_count * sizeof(XMVAudioTrack));

    if (!xmv->audio_tracks)

        return AVERROR(ENOMEM);

    xmv->audio = av_malloc(xmv->audio_track_count * sizeof(XMVAudioPacket));

    if (!xmv->audio)

        return AVERROR(ENOMEM);

    for (audio_track = 0; audio_track < xmv->audio_track_count; audio_track++) {

        XMVAudioTrack  *track  = &xmv->audio_tracks[audio_track];

        XMVAudioPacket *packet = &xmv->audio       [audio_track];

        AVStream *ast = NULL;

        track->compression     = avio_rl16(pb);

        track->channels        = avio_rl16(pb);

        track->sample_rate     = avio_rl32(pb);

        track->bits_per_sample = avio_rl16(pb);

        track->flags           = avio_rl16(pb);

        track->bit_rate      = track->bits_per_sample *

                               track->sample_rate *

                               track->channels;

        track->block_align   = 36 * track->channels;

        track->block_samples = 64;

        track->codec_id      = ff_wav_codec_get_id(track->compression,

                                                   track->bits_per_sample);

        packet->track        = track;

        packet->stream_index = -1;

        packet->frame_size  = 0;

        packet->block_count = 0;

        /* TODO: ADPCM'd 5.1 sound is encoded in three separate streams.

         *       Those need to be interleaved to a proper 5.1 stream. */

        if (track->flags & XMV_AUDIO_ADPCM51)

            av_log(s, AV_LOG_WARNING, "Unsupported 5.1 ADPCM audio stream "

                                      "(0x%04X)\n", track->flags);

        if (!track->channels || !track->sample_rate) {

            av_log(s, AV_LOG_ERROR, "Invalid parameters for audio track %d.\n",

                   audio_track);

            ret = AVERROR_INVALIDDATA;

            goto fail;

        }

        ast = avformat_new_stream(s, NULL);

        if (!ast)

            return AVERROR(ENOMEM);

        ast->codec->codec_type            = AVMEDIA_TYPE_AUDIO;

        ast->codec->codec_id              = track->codec_id;

        ast->codec->codec_tag             = track->compression;

        ast->codec->channels              = track->channels;

        ast->codec->sample_rate           = track->sample_rate;

        ast->codec->bits_per_coded_sample = track->bits_per_sample;

        ast->codec->bit_rate              = track->bit_rate;

        ast->codec->block_align           = 36 * track->channels;

        avpriv_set_pts_info(ast, 32, track->block_samples, track->sample_rate);

        packet->stream_index = ast->index;

        ast->duration = vst->duration;

    }

    /** Initialize the packet context */

    xmv->next_packet_offset = avio_tell(pb);

    xmv->next_packet_size   = this_packet_size - xmv->next_packet_offset;

    xmv->stream_count       = xmv->audio_track_count + 1;

    return 0;

fail:

    xmv_read_close(s);

    return ret;

}


int avfilter_default_query_formats(AVFilterContext *ctx)

{

    enum AVMediaType type = ctx->inputs [0] ? ctx->inputs [0]->type :

                            ctx->outputs[0] ? ctx->outputs[0]->type :

                            AVMEDIA_TYPE_VIDEO;

    avfilter_set_common_formats(ctx, avfilter_all_formats(type));

    return 0;

}


static void vhost_log_sync(MemoryListener *listener,

                          MemoryRegionSection *section)

{

    struct vhost_dev *dev = container_of(listener, struct vhost_dev,

                                         memory_listener);

    hwaddr start_addr = section->offset_within_address_space;

    hwaddr end_addr = start_addr + section->size;

    vhost_sync_dirty_bitmap(dev, section, start_addr, end_addr);

}


static void put_codebook_header(PutBitContext * pb, codebook_t * cb) {

    int i;

    int ordered = 0;

    put_bits(pb, 24, 0x564342); //magic

    put_bits(pb, 16, cb->ndimentions);

    put_bits(pb, 24, cb->nentries);

    for (i = 1; i < cb->nentries; i++) if (cb->entries[i].len < cb->entries[i-1].len) break;

    if (i == cb->nentries) ordered = 1;

    put_bits(pb, 1, ordered);

    if (ordered) {

        int len = cb->entries[0].len;

        put_bits(pb, 5, len);

        i = 0;

        while (i < cb->nentries) {

            int j;

            for (j = 0; j+i < cb->nentries; j++) if (cb->entries[j+i].len != len) break;

            put_bits(pb, ilog(cb->nentries - i), j);

            i += j;

            len++;

        }

    } else {

        int sparse = 0;

        for (i = 0; i < cb->nentries; i++) if (!cb->entries[i].len) break;

        if (i != cb->nentries) sparse = 1;

        put_bits(pb, 1, sparse);

        for (i = 0; i < cb->nentries; i++) {

            if (sparse) put_bits(pb, 1, !!cb->entries[i].len);

            if (cb->entries[i].len) put_bits(pb, 5, cb->entries[i].len - 1);

        }

    }

    put_bits(pb, 4, cb->lookup);

    if (cb->lookup) {

        int tmp = cb_lookup_vals(cb->lookup, cb->ndimentions, cb->nentries);

        int bits = ilog(cb->quantlist[0]);

        for (i = 1; i < tmp; i++) bits = FFMAX(bits, ilog(cb->quantlist[i]));

        put_float(pb, cb->min);

        put_float(pb, cb->delta);

        put_bits(pb, 4, bits - 1);

        put_bits(pb, 1, cb->seq_p);

        for (i = 0; i < tmp; i++) put_bits(pb, bits, cb->quantlist[i]);

    }

}


static int mig_save_device_dirty(QEMUFile *f, BlkMigDevState *bmds,

                                 int is_async)

{

    BlkMigBlock *blk;

    int64_t total_sectors = bmds->total_sectors;

    int64_t sector;

    int nr_sectors;

    int ret = -EIO;

    for (sector = bmds->cur_dirty; sector < bmds->total_sectors;) {

        blk_mig_lock();

        if (bmds_aio_inflight(bmds, sector)) {

            blk_mig_unlock();

            bdrv_drain_all();

        } else {

            blk_mig_unlock();

        }

        if (bdrv_get_dirty(bmds->bs, bmds->dirty_bitmap, sector)) {

            if (total_sectors - sector < BDRV_SECTORS_PER_DIRTY_CHUNK) {

                nr_sectors = total_sectors - sector;

            } else {

                nr_sectors = BDRV_SECTORS_PER_DIRTY_CHUNK;

            }

            blk = g_new(BlkMigBlock, 1);

            blk->buf = g_malloc(BLOCK_SIZE);

            blk->bmds = bmds;

            blk->sector = sector;

            blk->nr_sectors = nr_sectors;

            if (is_async) {

                blk->iov.iov_base = blk->buf;

                blk->iov.iov_len = nr_sectors * BDRV_SECTOR_SIZE;

                qemu_iovec_init_external(&blk->qiov, &blk->iov, 1);

                blk->aiocb = bdrv_aio_readv(bmds->bs, sector, &blk->qiov,

                                            nr_sectors, blk_mig_read_cb, blk);

                blk_mig_lock();

                block_mig_state.submitted++;

                bmds_set_aio_inflight(bmds, sector, nr_sectors, 1);

                blk_mig_unlock();

            } else {

                ret = bdrv_read(bmds->bs, sector, blk->buf, nr_sectors);

                if (ret < 0) {

                    goto error;

                }

                blk_send(f, blk);

                g_free(blk->buf);

                g_free(blk);

            }

            bdrv_reset_dirty(bmds->bs, sector, nr_sectors);

            break;

        }

        sector += BDRV_SECTORS_PER_DIRTY_CHUNK;

        bmds->cur_dirty = sector;

    }

    return (bmds->cur_dirty >= bmds->total_sectors);

error:

    DPRINTF("Error reading sector %" PRId64 "\n", sector);

    g_free(blk->buf);

    g_free(blk);

    return ret;

}


void qbus_free(BusState *bus)

{

    DeviceState *dev;

    while ((dev = QLIST_FIRST(&bus->children)) != NULL) {

        qdev_free(dev);

    }

    if (bus->parent) {

        QLIST_REMOVE(bus, sibling);

        bus->parent->num_child_bus--;

    }

    if (bus->qdev_allocated) {

        qemu_free(bus);

    }

}


static void decode_v4_vector(CinepakEncContext *s, AVPicture *sub_pict, int *v4_vector, strip_info *info)

{

    int i, x, y, entry_size = s->pix_fmt == AV_PIX_FMT_YUV420P ? 6 : 4;

    for(i = y = 0; y < 4; y += 2) {

        for(x = 0; x < 4; x += 2, i++) {

            sub_pict->data[0][x   +     y*sub_pict->linesize[0]] = info->v4_codebook[v4_vector[i]*entry_size];

            sub_pict->data[0][x+1 +     y*sub_pict->linesize[0]] = info->v4_codebook[v4_vector[i]*entry_size+1];

            sub_pict->data[0][x   + (y+1)*sub_pict->linesize[0]] = info->v4_codebook[v4_vector[i]*entry_size+2];

            sub_pict->data[0][x+1 + (y+1)*sub_pict->linesize[0]] = info->v4_codebook[v4_vector[i]*entry_size+3];

            if(s->pix_fmt == AV_PIX_FMT_YUV420P) {

                sub_pict->data[1][(x>>1) + (y>>1)*sub_pict->linesize[1]] = info->v4_codebook[v4_vector[i]*entry_size+4];

                sub_pict->data[2][(x>>1) + (y>>1)*sub_pict->linesize[2]] = info->v4_codebook[v4_vector[i]*entry_size+5];

            }

        }

    }

}


static const TPMDriverOps *tpm_driver_find_by_type(enum TpmType type)

{

    int i;

    for (i = 0; i < TPM_MAX_DRIVERS && be_drivers[i] != NULL; i++) {

        if (be_drivers[i]->type == type) {

            return be_drivers[i];

        }

    }

    return NULL;

}


static int fic_decode_block(FICContext *ctx, GetBitContext *gb,

                            uint8_t *dst, int stride, int16_t *block, int *is_p)

{

    int i, num_coeff;

    /* Is it a skip block? */

    if (get_bits1(gb)) {

        *is_p = 1;

        return 0;

    }

    memset(block, 0, sizeof(*block) * 64);

    num_coeff = get_bits(gb, 7);

    if (num_coeff > 64)

        return AVERROR_INVALIDDATA;

    for (i = 0; i < num_coeff; i++)

        block[ff_zigzag_direct[i]] = get_se_golomb(gb) *

                                     ctx->qmat[ff_zigzag_direct[i]];

    fic_idct_put(dst, stride, block);

    return 0;

}


static inline void RENAME(yuv2yuv1)(int16_t *lumSrc, int16_t *chrSrc,

				    uint8_t *dest, uint8_t *uDest, uint8_t *vDest, long dstW, long chrDstW)

{

#ifdef HAVE_MMX

	if(uDest != NULL)

	{

		asm volatile(

				YSCALEYUV2YV121

				:: "r" (chrSrc + chrDstW), "r" (uDest + chrDstW),

				"g" (-chrDstW)

				: "%"REG_a

			);

		asm volatile(

				YSCALEYUV2YV121

				:: "r" (chrSrc + 2048 + chrDstW), "r" (vDest + chrDstW),

				"g" (-chrDstW)

				: "%"REG_a

			);

	}

	asm volatile(

		YSCALEYUV2YV121

		:: "r" (lumSrc + dstW), "r" (dest + dstW),

		"g" (-dstW)

		: "%"REG_a

	);

#else

	int i;

	for(i=0; i<dstW; i++)

	{

		int val= lumSrc[i]>>7;

		if(val&256){

			if(val<0) val=0;

			else      val=255;

		}

		dest[i]= val;

	}

	if(uDest != NULL)

		for(i=0; i<chrDstW; i++)

		{

			int u=chrSrc[i]>>7;

			int v=chrSrc[i + 2048]>>7;

			if((u|v)&256){

				if(u<0)         u=0;

				else if (u>255) u=255;

				if(v<0)         v=0;

				else if (v>255) v=255;

			}

			uDest[i]= u;

			vDest[i]= v;

		}

#endif

}


static int xan_decode_frame_type0(AVCodecContext *avctx)

{

    XanContext *s = avctx->priv_data;

    uint8_t *ybuf, *prev_buf, *src = s->scratch_buffer;

    unsigned  chroma_off, corr_off;

    int cur, last;

    int i, j;

    int ret;

    chroma_off = bytestream2_get_le32(&s->gb);

    corr_off   = bytestream2_get_le32(&s->gb);

    if ((ret = xan_decode_chroma(avctx, chroma_off)) != 0)

        return ret;

    if (corr_off >= (s->gb.buffer_end - s->gb.buffer_start)) {

        av_log(avctx, AV_LOG_WARNING, "Ignoring invalid correction block position\n");

        corr_off = 0;

    }

    bytestream2_seek(&s->gb, 12, SEEK_SET);

    ret = xan_unpack_luma(s, src, s->buffer_size >> 1);

    if (ret) {

        av_log(avctx, AV_LOG_ERROR, "Luma decoding failed\n");

        return ret;

    }

    ybuf = s->y_buffer;

    last = *src++;

    ybuf[0] = last << 1;

    for (j = 1; j < avctx->width - 1; j += 2) {

        cur = (last + *src++) & 0x1F;

        ybuf[j]   = last + cur;

        ybuf[j+1] = cur << 1;

        last = cur;

    }

    ybuf[j]  = last << 1;

    prev_buf = ybuf;

    ybuf += avctx->width;

    for (i = 1; i < avctx->height; i++) {

        last = ((prev_buf[0] >> 1) + *src++) & 0x1F;

        ybuf[0] = last << 1;

        for (j = 1; j < avctx->width - 1; j += 2) {

            cur = ((prev_buf[j + 1] >> 1) + *src++) & 0x1F;

            ybuf[j]   = last + cur;

            ybuf[j+1] = cur << 1;

            last = cur;

        }

        ybuf[j] = last << 1;

        prev_buf = ybuf;

        ybuf += avctx->width;

    }

    if (corr_off) {

        int dec_size;

        bytestream2_seek(&s->gb, 8 + corr_off, SEEK_SET);

        dec_size = xan_unpack(s, s->scratch_buffer, s->buffer_size);

        if (dec_size < 0)

            dec_size = 0;

        for (i = 0; i < dec_size; i++)

            s->y_buffer[i*2+1] = (s->y_buffer[i*2+1] + (s->scratch_buffer[i] << 1)) & 0x3F;

    }

    src  = s->y_buffer;

    ybuf = s->pic.data[0];

    for (j = 0; j < avctx->height; j++) {

        for (i = 0; i < avctx->width; i++)

            ybuf[i] = (src[i] << 2) | (src[i] >> 3);

        src  += avctx->width;

        ybuf += s->pic.linesize[0];

    }

    return 0;

}


static int raw_pread(BlockDriverState *bs, int64_t offset,

                     uint8_t *buf, int count)

{

    BDRVRawState *s = bs->opaque;

    int size, ret, shift, sum;

    sum = 0;

    if (s->aligned_buf != NULL)  {

        if (offset & 0x1ff) {

            /* align offset on a 512 bytes boundary */

            shift = offset & 0x1ff;

            size = (shift + count + 0x1ff) & ~0x1ff;

            if (size > ALIGNED_BUFFER_SIZE)

                size = ALIGNED_BUFFER_SIZE;

            ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, size);

            if (ret < 0)

                return ret;

            size = 512 - shift;

            if (size > count)

                size = count;

            memcpy(buf, s->aligned_buf + shift, size);

            buf += size;

            offset += size;

            count -= size;

            sum += size;

            if (count == 0)

                return sum;

        }

        if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {

            /* read on aligned buffer */

            while (count) {

                size = (count + 0x1ff) & ~0x1ff;

                if (size > ALIGNED_BUFFER_SIZE)

                    size = ALIGNED_BUFFER_SIZE;

                ret = raw_pread_aligned(bs, offset, s->aligned_buf, size);

                if (ret < 0)

                    return ret;

                size = ret;

                if (size > count)

                    size = count;

                memcpy(buf, s->aligned_buf, size);

                buf += size;

                offset += size;

                count -= size;

                sum += size;

            }

            return sum;

        }

    }

    return raw_pread_aligned(bs, offset, buf, count) + sum;

}


static av_always_inline int normal_limit(uint8_t *p, ptrdiff_t stride,

                                         int E, int I)

{

    LOAD_PIXELS

    return simple_limit(p, stride, E) &&

           FFABS(p3 - p2) <= I &&

           FFABS(p2 - p1) <= I &&

           FFABS(p1 - p0) <= I &&

           FFABS(q3 - q2) <= I &&

           FFABS(q2 - q1) <= I &&

           FFABS(q1 - q0) <= I;

}


static int cmv_process_header(CmvContext *s, const uint8_t *buf, const uint8_t *buf_end)

{

    int pal_start, pal_count, i, ret;

    if(buf_end - buf < 16) {

        av_log(s->avctx, AV_LOG_WARNING, "truncated header\n");

        return AVERROR_INVALIDDATA;

    }

    s->width  = AV_RL16(&buf[4]);

    s->height = AV_RL16(&buf[6]);

    ret = ff_set_dimensions(s->avctx, s->width, s->height);

    if (ret < 0)

        return ret;

    s->avctx->time_base.num = 1;

    s->avctx->time_base.den = AV_RL16(&buf[10]);

    pal_start = AV_RL16(&buf[12]);

    pal_count = AV_RL16(&buf[14]);

    buf += 16;

    for (i=pal_start; i<pal_start+pal_count && i<AVPALETTE_COUNT && buf_end - buf >= 3; i++) {

        s->palette[i] = AV_RB24(buf);

        buf += 3;

    }

    return 0;

}


void avformat_free_context(AVFormatContext *s)

{

    int i;

    if (!s)

        return;

    av_opt_free(s);

    if (s->iformat && s->iformat->priv_class && s->priv_data)

        av_opt_free(s->priv_data);

    if (s->oformat && s->oformat->priv_class && s->priv_data)

        av_opt_free(s->priv_data);

    for (i = s->nb_streams - 1; i >= 0; i--) {

        ff_free_stream(s, s->streams[i]);

    }

    for (i = s->nb_programs - 1; i >= 0; i--) {

        av_dict_free(&s->programs[i]->metadata);

        av_freep(&s->programs[i]->stream_index);

        av_freep(&s->programs[i]);

    }

    av_freep(&s->programs);

    av_freep(&s->priv_data);

    while (s->nb_chapters--) {

        av_dict_free(&s->chapters[s->nb_chapters]->metadata);

        av_freep(&s->chapters[s->nb_chapters]);

    }

    av_freep(&s->chapters);

    av_dict_free(&s->metadata);

    av_freep(&s->streams);

    av_freep(&s->internal);

    av_free(s);

}


static void get_sdr(IPMIBmcSim *ibs,

                    uint8_t *cmd, unsigned int cmd_len,

                    uint8_t *rsp, unsigned int *rsp_len,

                    unsigned int max_rsp_len)

{

    unsigned int pos;

    uint16_t nextrec;

    struct ipmi_sdr_header *sdrh;

    IPMI_CHECK_CMD_LEN(8);

    if (cmd[6]) {

        IPMI_CHECK_RESERVATION(2, ibs->sdr.reservation);

    }

    pos = 0;

    if (sdr_find_entry(&ibs->sdr, cmd[4] | (cmd[5] << 8),

                       &pos, &nextrec)) {

        rsp[2] = IPMI_CC_REQ_ENTRY_NOT_PRESENT;

        return;

    }

    sdrh = (struct ipmi_sdr_header *) &ibs->sdr.sdr[pos];

    if (cmd[6] > ipmi_sdr_length(sdrh)) {

        rsp[2] = IPMI_CC_PARM_OUT_OF_RANGE;

        return;

    }

    IPMI_ADD_RSP_DATA(nextrec & 0xff);

    IPMI_ADD_RSP_DATA((nextrec >> 8) & 0xff);

    if (cmd[7] == 0xff) {

        cmd[7] = ipmi_sdr_length(sdrh) - cmd[6];

    }

    if ((cmd[7] + *rsp_len) > max_rsp_len) {

        rsp[2] = IPMI_CC_CANNOT_RETURN_REQ_NUM_BYTES;

        return;

    }

    memcpy(rsp + *rsp_len, ibs->sdr.sdr + pos + cmd[6], cmd[7]);

    *rsp_len += cmd[7];

}


static float get_band_cost_NONE_mips(struct AACEncContext *s,

                                     PutBitContext *pb, const float *in,

                                     const float *scaled, int size, int scale_idx,

                                     int cb, const float lambda, const float uplim,

                                     int *bits)

{

    av_assert0(0);

    return 0;

}


static int kvm_physical_sync_dirty_bitmap(MemoryRegionSection *section)

{

    KVMState *s = kvm_state;

    unsigned long size, allocated_size = 0;

    KVMDirtyLog d;

    KVMSlot *mem;

    int ret = 0;

    hwaddr start_addr = section->offset_within_address_space;

    hwaddr end_addr = start_addr + int128_get64(section->size);

    d.dirty_bitmap = NULL;

    while (start_addr < end_addr) {

        mem = kvm_lookup_overlapping_slot(s, start_addr, end_addr);

        if (mem == NULL) {

            break;

        }

        /* XXX bad kernel interface alert

         * For dirty bitmap, kernel allocates array of size aligned to

         * bits-per-long.  But for case when the kernel is 64bits and

         * the userspace is 32bits, userspace can't align to the same

         * bits-per-long, since sizeof(long) is different between kernel

         * and user space.  This way, userspace will provide buffer which

         * may be 4 bytes less than the kernel will use, resulting in

         * userspace memory corruption (which is not detectable by valgrind

         * too, in most cases).

         * So for now, let's align to 64 instead of HOST_LONG_BITS here, in

         * a hope that sizeof(long) wont become >8 any time soon.

         */

        size = ALIGN(((mem->memory_size) >> TARGET_PAGE_BITS),

                     /*HOST_LONG_BITS*/ 64) / 8;

        if (!d.dirty_bitmap) {

            d.dirty_bitmap = g_malloc(size);

        } else if (size > allocated_size) {

            d.dirty_bitmap = g_realloc(d.dirty_bitmap, size);

        }

        allocated_size = size;

        memset(d.dirty_bitmap, 0, allocated_size);

        d.slot = mem->slot;

        if (kvm_vm_ioctl(s, KVM_GET_DIRTY_LOG, &d) == -1) {

            DPRINTF("ioctl failed %d\n", errno);

            ret = -1;

            break;

        }

        kvm_get_dirty_pages_log_range(section, d.dirty_bitmap);

        start_addr = mem->start_addr + mem->memory_size;

    }

    g_free(d.dirty_bitmap);

    return ret;

}


av_cold void ff_h264_pred_init(H264PredContext *h, int codec_id,

                               const int bit_depth,

                               const int chroma_format_idc)

{

#undef FUNC

#undef FUNCC

#define FUNC(a, depth) a ## _ ## depth

#define FUNCC(a, depth) a ## _ ## depth ## _c

#define FUNCD(a) a ## _c

#define H264_PRED(depth) \

    if(codec_id != AV_CODEC_ID_RV40){\

        if(codec_id == AV_CODEC_ID_VP8) {\

            h->pred4x4[VERT_PRED       ]= FUNCD(pred4x4_vertical_vp8);\

            h->pred4x4[HOR_PRED        ]= FUNCD(pred4x4_horizontal_vp8);\

        } else {\

            h->pred4x4[VERT_PRED       ]= FUNCC(pred4x4_vertical          , depth);\

            h->pred4x4[HOR_PRED        ]= FUNCC(pred4x4_horizontal        , depth);\

        }\

        h->pred4x4[DC_PRED             ]= FUNCC(pred4x4_dc                , depth);\

        if(codec_id == AV_CODEC_ID_SVQ3)\

            h->pred4x4[DIAG_DOWN_LEFT_PRED ]= FUNCD(pred4x4_down_left_svq3);\

        else\

            h->pred4x4[DIAG_DOWN_LEFT_PRED ]= FUNCC(pred4x4_down_left     , depth);\

        h->pred4x4[DIAG_DOWN_RIGHT_PRED]= FUNCC(pred4x4_down_right        , depth);\

        h->pred4x4[VERT_RIGHT_PRED     ]= FUNCC(pred4x4_vertical_right    , depth);\

        h->pred4x4[HOR_DOWN_PRED       ]= FUNCC(pred4x4_horizontal_down   , depth);\

        if (codec_id == AV_CODEC_ID_VP8) {\

            h->pred4x4[VERT_LEFT_PRED  ]= FUNCD(pred4x4_vertical_left_vp8);\

        } else\

            h->pred4x4[VERT_LEFT_PRED  ]= FUNCC(pred4x4_vertical_left     , depth);\

        h->pred4x4[HOR_UP_PRED         ]= FUNCC(pred4x4_horizontal_up     , depth);\

        if(codec_id != AV_CODEC_ID_VP8) {\

            h->pred4x4[LEFT_DC_PRED    ]= FUNCC(pred4x4_left_dc           , depth);\

            h->pred4x4[TOP_DC_PRED     ]= FUNCC(pred4x4_top_dc            , depth);\

            h->pred4x4[DC_128_PRED     ]= FUNCC(pred4x4_128_dc            , depth);\

        } else {\

            h->pred4x4[TM_VP8_PRED     ]= FUNCD(pred4x4_tm_vp8);\

            h->pred4x4[DC_127_PRED     ]= FUNCC(pred4x4_127_dc            , depth);\

            h->pred4x4[DC_129_PRED     ]= FUNCC(pred4x4_129_dc            , depth);\

            h->pred4x4[VERT_VP8_PRED   ]= FUNCC(pred4x4_vertical          , depth);\

            h->pred4x4[HOR_VP8_PRED    ]= FUNCC(pred4x4_horizontal        , depth);\

        }\

    }else{\

        h->pred4x4[VERT_PRED           ]= FUNCC(pred4x4_vertical          , depth);\

        h->pred4x4[HOR_PRED            ]= FUNCC(pred4x4_horizontal        , depth);\

        h->pred4x4[DC_PRED             ]= FUNCC(pred4x4_dc                , depth);\

        h->pred4x4[DIAG_DOWN_LEFT_PRED ]= FUNCD(pred4x4_down_left_rv40);\

        h->pred4x4[DIAG_DOWN_RIGHT_PRED]= FUNCC(pred4x4_down_right        , depth);\

        h->pred4x4[VERT_RIGHT_PRED     ]= FUNCC(pred4x4_vertical_right    , depth);\

        h->pred4x4[HOR_DOWN_PRED       ]= FUNCC(pred4x4_horizontal_down   , depth);\

        h->pred4x4[VERT_LEFT_PRED      ]= FUNCD(pred4x4_vertical_left_rv40);\

        h->pred4x4[HOR_UP_PRED         ]= FUNCD(pred4x4_horizontal_up_rv40);\

        h->pred4x4[LEFT_DC_PRED        ]= FUNCC(pred4x4_left_dc           , depth);\

        h->pred4x4[TOP_DC_PRED         ]= FUNCC(pred4x4_top_dc            , depth);\

        h->pred4x4[DC_128_PRED         ]= FUNCC(pred4x4_128_dc            , depth);\

        h->pred4x4[DIAG_DOWN_LEFT_PRED_RV40_NODOWN]= FUNCD(pred4x4_down_left_rv40_nodown);\

        h->pred4x4[HOR_UP_PRED_RV40_NODOWN]= FUNCD(pred4x4_horizontal_up_rv40_nodown);\

        h->pred4x4[VERT_LEFT_PRED_RV40_NODOWN]= FUNCD(pred4x4_vertical_left_rv40_nodown);\

    }\

\

    h->pred8x8l[VERT_PRED           ]= FUNCC(pred8x8l_vertical            , depth);\

    h->pred8x8l[HOR_PRED            ]= FUNCC(pred8x8l_horizontal          , depth);\

    h->pred8x8l[DC_PRED             ]= FUNCC(pred8x8l_dc                  , depth);\

    h->pred8x8l[DIAG_DOWN_LEFT_PRED ]= FUNCC(pred8x8l_down_left           , depth);\

    h->pred8x8l[DIAG_DOWN_RIGHT_PRED]= FUNCC(pred8x8l_down_right          , depth);\

    h->pred8x8l[VERT_RIGHT_PRED     ]= FUNCC(pred8x8l_vertical_right      , depth);\

    h->pred8x8l[HOR_DOWN_PRED       ]= FUNCC(pred8x8l_horizontal_down     , depth);\

    h->pred8x8l[VERT_LEFT_PRED      ]= FUNCC(pred8x8l_vertical_left       , depth);\

    h->pred8x8l[HOR_UP_PRED         ]= FUNCC(pred8x8l_horizontal_up       , depth);\

    h->pred8x8l[LEFT_DC_PRED        ]= FUNCC(pred8x8l_left_dc             , depth);\

    h->pred8x8l[TOP_DC_PRED         ]= FUNCC(pred8x8l_top_dc              , depth);\

    h->pred8x8l[DC_128_PRED         ]= FUNCC(pred8x8l_128_dc              , depth);\

\

    if (chroma_format_idc <= 1) {\

        h->pred8x8[VERT_PRED8x8   ]= FUNCC(pred8x8_vertical               , depth);\

        h->pred8x8[HOR_PRED8x8    ]= FUNCC(pred8x8_horizontal             , depth);\

    } else {\

        h->pred8x8[VERT_PRED8x8   ]= FUNCC(pred8x16_vertical              , depth);\

        h->pred8x8[HOR_PRED8x8    ]= FUNCC(pred8x16_horizontal            , depth);\

    }\

    if (codec_id != AV_CODEC_ID_VP8) {\

        if (chroma_format_idc <= 1) {\

            h->pred8x8[PLANE_PRED8x8]= FUNCC(pred8x8_plane                , depth);\

        } else {\

            h->pred8x8[PLANE_PRED8x8]= FUNCC(pred8x16_plane               , depth);\

        }\

    } else\

        h->pred8x8[PLANE_PRED8x8]= FUNCD(pred8x8_tm_vp8);\

    if(codec_id != AV_CODEC_ID_RV40 && codec_id != AV_CODEC_ID_VP8){\

        if (chroma_format_idc <= 1) {\

            h->pred8x8[DC_PRED8x8     ]= FUNCC(pred8x8_dc                     , depth);\

            h->pred8x8[LEFT_DC_PRED8x8]= FUNCC(pred8x8_left_dc                , depth);\

            h->pred8x8[TOP_DC_PRED8x8 ]= FUNCC(pred8x8_top_dc                 , depth);\

            h->pred8x8[ALZHEIMER_DC_L0T_PRED8x8 ]= FUNC(pred8x8_mad_cow_dc_l0t, depth);\

            h->pred8x8[ALZHEIMER_DC_0LT_PRED8x8 ]= FUNC(pred8x8_mad_cow_dc_0lt, depth);\

            h->pred8x8[ALZHEIMER_DC_L00_PRED8x8 ]= FUNC(pred8x8_mad_cow_dc_l00, depth);\

            h->pred8x8[ALZHEIMER_DC_0L0_PRED8x8 ]= FUNC(pred8x8_mad_cow_dc_0l0, depth);\

        } else {\

            h->pred8x8[DC_PRED8x8     ]= FUNCC(pred8x16_dc                    , depth);\

            h->pred8x8[LEFT_DC_PRED8x8]= FUNCC(pred8x16_left_dc               , depth);\

            h->pred8x8[TOP_DC_PRED8x8 ]= FUNCC(pred8x16_top_dc                , depth);\

            h->pred8x8[ALZHEIMER_DC_L0T_PRED8x8 ]= FUNC(pred8x16_mad_cow_dc_l0t, depth);\

            h->pred8x8[ALZHEIMER_DC_0LT_PRED8x8 ]= FUNC(pred8x16_mad_cow_dc_0lt, depth);\

            h->pred8x8[ALZHEIMER_DC_L00_PRED8x8 ]= FUNC(pred8x16_mad_cow_dc_l00, depth);\

            h->pred8x8[ALZHEIMER_DC_0L0_PRED8x8 ]= FUNC(pred8x16_mad_cow_dc_0l0, depth);\

        }\

    }else{\

        h->pred8x8[DC_PRED8x8     ]= FUNCD(pred8x8_dc_rv40);\

        h->pred8x8[LEFT_DC_PRED8x8]= FUNCD(pred8x8_left_dc_rv40);\

        h->pred8x8[TOP_DC_PRED8x8 ]= FUNCD(pred8x8_top_dc_rv40);\

        if (codec_id == AV_CODEC_ID_VP8) {\

            h->pred8x8[DC_127_PRED8x8]= FUNCC(pred8x8_127_dc              , depth);\

            h->pred8x8[DC_129_PRED8x8]= FUNCC(pred8x8_129_dc              , depth);\

        }\

    }\

    if (chroma_format_idc <= 1) {\

        h->pred8x8[DC_128_PRED8x8 ]= FUNCC(pred8x8_128_dc                 , depth);\

    } else {\

        h->pred8x8[DC_128_PRED8x8 ]= FUNCC(pred8x16_128_dc                , depth);\

    }\

\

    h->pred16x16[DC_PRED8x8     ]= FUNCC(pred16x16_dc                     , depth);\

    h->pred16x16[VERT_PRED8x8   ]= FUNCC(pred16x16_vertical               , depth);\

    h->pred16x16[HOR_PRED8x8    ]= FUNCC(pred16x16_horizontal             , depth);\

    switch(codec_id){\

    case AV_CODEC_ID_SVQ3:\

       h->pred16x16[PLANE_PRED8x8  ]= FUNCD(pred16x16_plane_svq3);\

       break;\

    case AV_CODEC_ID_RV40:\

       h->pred16x16[PLANE_PRED8x8  ]= FUNCD(pred16x16_plane_rv40);\

       break;\

    case AV_CODEC_ID_VP8:\

       h->pred16x16[PLANE_PRED8x8  ]= FUNCD(pred16x16_tm_vp8);\

       h->pred16x16[DC_127_PRED8x8]= FUNCC(pred16x16_127_dc               , depth);\

       h->pred16x16[DC_129_PRED8x8]= FUNCC(pred16x16_129_dc               , depth);\

       break;\

    default:\

       h->pred16x16[PLANE_PRED8x8  ]= FUNCC(pred16x16_plane               , depth);\

       break;\

    }\

    h->pred16x16[LEFT_DC_PRED8x8]= FUNCC(pred16x16_left_dc                , depth);\

    h->pred16x16[TOP_DC_PRED8x8 ]= FUNCC(pred16x16_top_dc                 , depth);\

    h->pred16x16[DC_128_PRED8x8 ]= FUNCC(pred16x16_128_dc                 , depth);\

\

    /* special lossless h/v prediction for h264 */ \

    h->pred4x4_add  [VERT_PRED   ]= FUNCC(pred4x4_vertical_add            , depth);\

    h->pred4x4_add  [ HOR_PRED   ]= FUNCC(pred4x4_horizontal_add          , depth);\

    h->pred8x8l_add [VERT_PRED   ]= FUNCC(pred8x8l_vertical_add           , depth);\

    h->pred8x8l_add [ HOR_PRED   ]= FUNCC(pred8x8l_horizontal_add         , depth);\

    if (chroma_format_idc <= 1) {\

    h->pred8x8_add  [VERT_PRED8x8]= FUNCC(pred8x8_vertical_add            , depth);\

    h->pred8x8_add  [ HOR_PRED8x8]= FUNCC(pred8x8_horizontal_add          , depth);\

    } else {\

        h->pred8x8_add  [VERT_PRED8x8]= FUNCC(pred8x16_vertical_add            , depth);\

        h->pred8x8_add  [ HOR_PRED8x8]= FUNCC(pred8x16_horizontal_add          , depth);\

    }\

    h->pred16x16_add[VERT_PRED8x8]= FUNCC(pred16x16_vertical_add          , depth);\

    h->pred16x16_add[ HOR_PRED8x8]= FUNCC(pred16x16_horizontal_add        , depth);\

    switch (bit_depth) {

        case 9:

            H264_PRED(9)

            break;

        case 10:

            H264_PRED(10)

            break;

        default:

            H264_PRED(8)

            break;

    }

    if (ARCH_ARM) ff_h264_pred_init_arm(h, codec_id, bit_depth, chroma_format_idc);

    if (ARCH_X86) ff_h264_pred_init_x86(h, codec_id, bit_depth, chroma_format_idc);

}


sigterm_handler(int sig)

{

    received_sigterm = sig;

    received_nb_signals++;

    term_exit_sigsafe();

    if(received_nb_signals > 3)

        exit_program(123);

}


static void pci_idx(void)

{

    QVirtioPCIDevice *dev;

    QPCIBus *bus;

    QVirtQueuePCI *vqpci;

    QGuestAllocator *alloc;

    QVirtioBlkReq req;

    void *addr;

    uint64_t req_addr;

    uint64_t capacity;

    uint32_t features;

    uint32_t free_head;

    uint8_t status;

    char *data;

    bus = pci_test_start();

    alloc = pc_alloc_init();

    dev = virtio_blk_pci_init(bus, PCI_SLOT);

    qpci_msix_enable(dev->pdev);

    qvirtio_pci_set_msix_configuration_vector(dev, alloc, 0);

    /* MSI-X is enabled */

    addr = dev->addr + VIRTIO_PCI_CONFIG_OFF(true);

    capacity = qvirtio_config_readq(&qvirtio_pci, &dev->vdev,

                                                    (uint64_t)(uintptr_t)addr);

    g_assert_cmpint(capacity, ==, TEST_IMAGE_SIZE / 512);

    features = qvirtio_get_features(&qvirtio_pci, &dev->vdev);

    features = features & ~(QVIRTIO_F_BAD_FEATURE |

                            (1u << VIRTIO_RING_F_INDIRECT_DESC) |

                            (1u << VIRTIO_F_NOTIFY_ON_EMPTY) |

                            (1u << VIRTIO_BLK_F_SCSI));

    qvirtio_set_features(&qvirtio_pci, &dev->vdev, features);

    vqpci = (QVirtQueuePCI *)qvirtqueue_setup(&qvirtio_pci, &dev->vdev,

                                                                    alloc, 0);

    qvirtqueue_pci_msix_setup(dev, vqpci, alloc, 1);

    qvirtio_set_driver_ok(&qvirtio_pci, &dev->vdev);

    /* Write request */

    req.type = VIRTIO_BLK_T_OUT;

    req.ioprio = 1;

    req.sector = 0;

    req.data = g_malloc0(512);

    strcpy(req.data, "TEST");

    req_addr = virtio_blk_request(alloc, &req, 512);

    g_free(req.data);

    free_head = qvirtqueue_add(&vqpci->vq, req_addr, 16, false, true);

    qvirtqueue_add(&vqpci->vq, req_addr + 16, 512, false, true);

    qvirtqueue_add(&vqpci->vq, req_addr + 528, 1, true, false);

    qvirtqueue_kick(&qvirtio_pci, &dev->vdev, &vqpci->vq, free_head);

    qvirtio_wait_queue_isr(&qvirtio_pci, &dev->vdev, &vqpci->vq,

                           QVIRTIO_BLK_TIMEOUT_US);

    /* Write request */

    req.type = VIRTIO_BLK_T_OUT;

    req.ioprio = 1;

    req.sector = 1;

    req.data = g_malloc0(512);

    strcpy(req.data, "TEST");

    req_addr = virtio_blk_request(alloc, &req, 512);

    g_free(req.data);

    /* Notify after processing the third request */

    qvirtqueue_set_used_event(&vqpci->vq, 2);

    free_head = qvirtqueue_add(&vqpci->vq, req_addr, 16, false, true);

    qvirtqueue_add(&vqpci->vq, req_addr + 16, 512, false, true);

    qvirtqueue_add(&vqpci->vq, req_addr + 528, 1, true, false);

    qvirtqueue_kick(&qvirtio_pci, &dev->vdev, &vqpci->vq, free_head);

    /* No notification expected */

    status = qvirtio_wait_status_byte_no_isr(&qvirtio_pci, &dev->vdev,

                                             &vqpci->vq, req_addr + 528,

                                             QVIRTIO_BLK_TIMEOUT_US);

    g_assert_cmpint(status, ==, 0);

    guest_free(alloc, req_addr);

    /* Read request */

    req.type = VIRTIO_BLK_T_IN;

    req.ioprio = 1;

    req.sector = 1;

    req.data = g_malloc0(512);

    req_addr = virtio_blk_request(alloc, &req, 512);

    g_free(req.data);

    free_head = qvirtqueue_add(&vqpci->vq, req_addr, 16, false, true);

    qvirtqueue_add(&vqpci->vq, req_addr + 16, 512, true, true);

    qvirtqueue_add(&vqpci->vq, req_addr + 528, 1, true, false);

    qvirtqueue_kick(&qvirtio_pci, &dev->vdev, &vqpci->vq, free_head);

    qvirtio_wait_queue_isr(&qvirtio_pci, &dev->vdev, &vqpci->vq,

                           QVIRTIO_BLK_TIMEOUT_US);

    status = readb(req_addr + 528);

    g_assert_cmpint(status, ==, 0);

    data = g_malloc0(512);

    memread(req_addr + 16, data, 512);

    g_assert_cmpstr(data, ==, "TEST");

    g_free(data);

    guest_free(alloc, req_addr);

    /* End test */

    guest_free(alloc, vqpci->vq.desc);

    pc_alloc_uninit(alloc);

    qpci_msix_disable(dev->pdev);

    qvirtio_pci_device_disable(dev);

    g_free(dev);

    qpci_free_pc(bus);

    test_end();

}


static void ref405ep_init(MachineState *machine)

{

    ram_addr_t ram_size = machine->ram_size;

    const char *kernel_filename = machine->kernel_filename;

    const char *kernel_cmdline = machine->kernel_cmdline;

    const char *initrd_filename = machine->initrd_filename;

    char *filename;

    ppc4xx_bd_info_t bd;

    CPUPPCState *env;

    qemu_irq *pic;

    MemoryRegion *bios;

    MemoryRegion *sram = g_new(MemoryRegion, 1);

    ram_addr_t bdloc;

    MemoryRegion *ram_memories = g_malloc(2 * sizeof(*ram_memories));

    hwaddr ram_bases[2], ram_sizes[2];

    target_ulong sram_size;

    long bios_size;

    //int phy_addr = 0;

    //static int phy_addr = 1;

    target_ulong kernel_base, initrd_base;

    long kernel_size, initrd_size;

    int linux_boot;

    int fl_idx, fl_sectors, len;

    DriveInfo *dinfo;

    MemoryRegion *sysmem = get_system_memory();

    /* XXX: fix this */

    memory_region_allocate_system_memory(&ram_memories[0], NULL, "ef405ep.ram",

                                         0x08000000);

    ram_bases[0] = 0;

    ram_sizes[0] = 0x08000000;

    memory_region_init(&ram_memories[1], NULL, "ef405ep.ram1", 0);

    ram_bases[1] = 0x00000000;

    ram_sizes[1] = 0x00000000;

    ram_size = 128 * 1024 * 1024;

#ifdef DEBUG_BOARD_INIT

    printf("%s: register cpu\n", __func__);

#endif

    env = ppc405ep_init(sysmem, ram_memories, ram_bases, ram_sizes,

                        33333333, &pic, kernel_filename == NULL ? 0 : 1);

    /* allocate SRAM */

    sram_size = 512 * 1024;

    memory_region_init_ram(sram, NULL, "ef405ep.sram", sram_size, &error_abort);

    vmstate_register_ram_global(sram);

    memory_region_add_subregion(sysmem, 0xFFF00000, sram);

    /* allocate and load BIOS */

#ifdef DEBUG_BOARD_INIT

    printf("%s: register BIOS\n", __func__);

#endif

    fl_idx = 0;

#ifdef USE_FLASH_BIOS

    dinfo = drive_get(IF_PFLASH, 0, fl_idx);

    if (dinfo) {

        BlockBackend *blk = blk_by_legacy_dinfo(dinfo);

        bios_size = blk_getlength(blk);

        fl_sectors = (bios_size + 65535) >> 16;

#ifdef DEBUG_BOARD_INIT

        printf("Register parallel flash %d size %lx"

               " at addr %lx '%s' %d\n",

               fl_idx, bios_size, -bios_size,

               blk_name(blk), fl_sectors);

#endif

        pflash_cfi02_register((uint32_t)(-bios_size),

                              NULL, "ef405ep.bios", bios_size,

                              blk, 65536, fl_sectors, 1,

                              2, 0x0001, 0x22DA, 0x0000, 0x0000, 0x555, 0x2AA,

                              1);

        fl_idx++;

    } else

#endif

    {

#ifdef DEBUG_BOARD_INIT

        printf("Load BIOS from file\n");

#endif

        bios = g_new(MemoryRegion, 1);

        memory_region_init_ram(bios, NULL, "ef405ep.bios", BIOS_SIZE,

                               &error_abort);

        vmstate_register_ram_global(bios);

        if (bios_name == NULL)

            bios_name = BIOS_FILENAME;

        filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);

        if (filename) {

            bios_size = load_image(filename, memory_region_get_ram_ptr(bios));

            g_free(filename);

            if (bios_size < 0 || bios_size > BIOS_SIZE) {

                error_report("Could not load PowerPC BIOS '%s'", bios_name);

                exit(1);

            }

            bios_size = (bios_size + 0xfff) & ~0xfff;

            memory_region_add_subregion(sysmem, (uint32_t)(-bios_size), bios);

        } else if (!qtest_enabled() || kernel_filename != NULL) {

            error_report("Could not load PowerPC BIOS '%s'", bios_name);

            exit(1);

        } else {

            /* Avoid an uninitialized variable warning */

            bios_size = -1;

        }

        memory_region_set_readonly(bios, true);

    }

    /* Register FPGA */

#ifdef DEBUG_BOARD_INIT

    printf("%s: register FPGA\n", __func__);

#endif

    ref405ep_fpga_init(sysmem, 0xF0300000);

    /* Register NVRAM */

#ifdef DEBUG_BOARD_INIT

    printf("%s: register NVRAM\n", __func__);

#endif

    m48t59_init(NULL, 0xF0000000, 0, 8192, 1968, 8);

    /* Load kernel */

    linux_boot = (kernel_filename != NULL);

    if (linux_boot) {

#ifdef DEBUG_BOARD_INIT

        printf("%s: load kernel\n", __func__);

#endif

        memset(&bd, 0, sizeof(bd));

        bd.bi_memstart = 0x00000000;

        bd.bi_memsize = ram_size;

        bd.bi_flashstart = -bios_size;

        bd.bi_flashsize = -bios_size;

        bd.bi_flashoffset = 0;

        bd.bi_sramstart = 0xFFF00000;

        bd.bi_sramsize = sram_size;

        bd.bi_bootflags = 0;

        bd.bi_intfreq = 133333333;

        bd.bi_busfreq = 33333333;

        bd.bi_baudrate = 115200;

        bd.bi_s_version[0] = 'Q';

        bd.bi_s_version[1] = 'M';

        bd.bi_s_version[2] = 'U';

        bd.bi_s_version[3] = '\0';

        bd.bi_r_version[0] = 'Q';

        bd.bi_r_version[1] = 'E';

        bd.bi_r_version[2] = 'M';

        bd.bi_r_version[3] = 'U';

        bd.bi_r_version[4] = '\0';

        bd.bi_procfreq = 133333333;

        bd.bi_plb_busfreq = 33333333;

        bd.bi_pci_busfreq = 33333333;

        bd.bi_opbfreq = 33333333;

        bdloc = ppc405_set_bootinfo(env, &bd, 0x00000001);

        env->gpr[3] = bdloc;

        kernel_base = KERNEL_LOAD_ADDR;

        /* now we can load the kernel */

        kernel_size = load_image_targphys(kernel_filename, kernel_base,

                                          ram_size - kernel_base);

        if (kernel_size < 0) {

            fprintf(stderr, "qemu: could not load kernel '%s'\n",

                    kernel_filename);

            exit(1);

        }

        printf("Load kernel size %ld at " TARGET_FMT_lx,

               kernel_size, kernel_base);

        /* load initrd */

        if (initrd_filename) {

            initrd_base = INITRD_LOAD_ADDR;

            initrd_size = load_image_targphys(initrd_filename, initrd_base,

                                              ram_size - initrd_base);

            if (initrd_size < 0) {

                fprintf(stderr, "qemu: could not load initial ram disk '%s'\n",

                        initrd_filename);

                exit(1);

            }

        } else {

            initrd_base = 0;

            initrd_size = 0;

        }

        env->gpr[4] = initrd_base;

        env->gpr[5] = initrd_size;

        if (kernel_cmdline != NULL) {

            len = strlen(kernel_cmdline);

            bdloc -= ((len + 255) & ~255);

            cpu_physical_memory_write(bdloc, kernel_cmdline, len + 1);

            env->gpr[6] = bdloc;

            env->gpr[7] = bdloc + len;

        } else {

            env->gpr[6] = 0;

            env->gpr[7] = 0;

        }

        env->nip = KERNEL_LOAD_ADDR;

    } else {

        kernel_base = 0;

        kernel_size = 0;

        initrd_base = 0;

        initrd_size = 0;

        bdloc = 0;

    }

#ifdef DEBUG_BOARD_INIT

    printf("bdloc " RAM_ADDR_FMT "\n", bdloc);

    printf("%s: Done\n", __func__);

#endif

}


int bdrv_check(BlockDriverState *bs)

{

    if (bs->drv->bdrv_check == NULL) {

        return -ENOTSUP;

    }

    return bs->drv->bdrv_check(bs);

}


static always_inline void gen_op_arith_add(DisasContext *ctx, TCGv ret, TCGv arg1, TCGv arg2,

                                           int add_ca, int compute_ca, int compute_ov)

{

    TCGv t0, t1;

    if ((!compute_ca && !compute_ov) ||

        (!TCGV_EQUAL(ret,arg1) && !TCGV_EQUAL(ret, arg2)))  {

        t0 = ret;

        t0 = tcg_temp_local_new();

    }

    if (add_ca) {

        t1 = tcg_temp_local_new();

        tcg_gen_andi_tl(t1, cpu_xer, (1 << XER_CA));

        tcg_gen_shri_tl(t1, t1, XER_CA);

    }

    if (compute_ca && compute_ov) {

        /* Start with XER CA and OV disabled, the most likely case */

        tcg_gen_andi_tl(cpu_xer, cpu_xer, ~((1 << XER_CA) | (1 << XER_OV)));

    } else if (compute_ca) {

        /* Start with XER CA disabled, the most likely case */

        tcg_gen_andi_tl(cpu_xer, cpu_xer, ~(1 << XER_CA));

    } else if (compute_ov) {

        /* Start with XER OV disabled, the most likely case */

        tcg_gen_andi_tl(cpu_xer, cpu_xer, ~(1 << XER_OV));

    }

    tcg_gen_add_tl(t0, arg1, arg2);

    if (compute_ca) {

        gen_op_arith_compute_ca(ctx, t0, arg1, 0);

    }

    if (add_ca) {

        tcg_gen_add_tl(t0, t0, t1);

        gen_op_arith_compute_ca(ctx, t0, t1, 0);

        tcg_temp_free(t1);

    }

    if (compute_ov) {

        gen_op_arith_compute_ov(ctx, t0, arg1, arg2, 0);

    }

    if (unlikely(Rc(ctx->opcode) != 0))

        gen_set_Rc0(ctx, t0);

    if (!TCGV_EQUAL(t0, ret)) {

        tcg_gen_mov_tl(ret, t0);

        tcg_temp_free(t0);

    }

}


static void test_i440fx_pam(gconstpointer opaque)
{
    const TestData *s = opaque;
    QPCIBus *bus;
    QPCIDevice *dev;
    int i;
    static struct {
        uint32_t start;
        uint32_t end;
    } pam_area[] = {
        { 0, 0 },             /* Reserved */
        { 0xF0000, 0xFFFFF }, /* BIOS Area */
        { 0xC0000, 0xC3FFF }, /* Option ROM */
        { 0xC4000, 0xC7FFF }, /* Option ROM */
        { 0xC8000, 0xCBFFF }, /* Option ROM */
        { 0xCC000, 0xCFFFF }, /* Option ROM */
        { 0xD0000, 0xD3FFF }, /* Option ROM */
        { 0xD4000, 0xD7FFF }, /* Option ROM */
        { 0xD8000, 0xDBFFF }, /* Option ROM */
        { 0xDC000, 0xDFFFF }, /* Option ROM */
        { 0xE0000, 0xE3FFF }, /* BIOS Extension */
        { 0xE4000, 0xE7FFF }, /* BIOS Extension */
        { 0xE8000, 0xEBFFF }, /* BIOS Extension */
        { 0xEC000, 0xEFFFF }, /* BIOS Extension */
    };
    bus = test_start_get_bus(s);
    dev = qpci_device_find(bus, QPCI_DEVFN(0, 0));
    g_assert(dev != NULL);
    for (i = 0; i < ARRAY_SIZE(pam_area); i++) {
        if (pam_area[i].start == pam_area[i].end) {
            continue;
        }
        g_test_message("Checking area 0x%05x..0x%05x",
                       pam_area[i].start, pam_area[i].end);
        /* Switch to RE for the area */
        pam_set(dev, i, PAM_RE);
        /* Verify the RAM is all zeros */
        g_assert(verify_area(pam_area[i].start, pam_area[i].end, 0));
        /* Switch to WE for the area */
        pam_set(dev, i, PAM_RE | PAM_WE);
        /* Write out a non-zero mask to the full area */
        write_area(pam_area[i].start, pam_area[i].end, 0x42);
#ifndef BROKEN
        /* QEMU only supports a limited form of PAM */
        /* Switch to !RE for the area */
        pam_set(dev, i, PAM_WE);
        /* Verify the area is not our mask */
        g_assert(!verify_area(pam_area[i].start, pam_area[i].end, 0x42));
#endif
        /* Verify the area is our new mask */
        g_assert(verify_area(pam_area[i].start, pam_area[i].end, 0x42));
        /* Write out a new mask */
        write_area(pam_area[i].start, pam_area[i].end, 0x82);
#ifndef BROKEN
        /* QEMU only supports a limited form of PAM */
        /* Verify the area is not our mask */
        g_assert(!verify_area(pam_area[i].start, pam_area[i].end, 0x82));
        /* Switch to RE for the area */
        pam_set(dev, i, PAM_RE | PAM_WE);
#endif
        /* Verify the area is our new mask */
        g_assert(verify_area(pam_area[i].start, pam_area[i].end, 0x82));
        /* Reset area */
        pam_set(dev, i, 0);
        /* Verify the area is not our new mask */
        g_assert(!verify_area(pam_area[i].start, pam_area[i].end, 0x82));
    }
    qtest_end();
}


static uint64_t alloc_cluster_offset(BlockDriverState *bs,

                                     uint64_t offset,

                                     int n_start, int n_end,

                                     int *num)

{

    BDRVQcowState *s = bs->opaque;

    int l2_index, ret;

    uint64_t l2_offset, *l2_table, cluster_offset;

    int nb_available, nb_clusters, i = 0;

    uint64_t start_sect;

    ret = get_cluster_table(bs, offset, &l2_table, &l2_offset, &l2_index);

    if (ret == 0)

        return 0;

    nb_clusters = size_to_clusters(s, n_end << 9);

    if (nb_clusters > s->l2_size - l2_index)

            nb_clusters = s->l2_size - l2_index;

    cluster_offset = be64_to_cpu(l2_table[l2_index]);

    /* We keep all QCOW_OFLAG_COPIED clusters */

    if (cluster_offset & QCOW_OFLAG_COPIED) {

        nb_clusters = count_contiguous_clusters(nb_clusters, s->cluster_size,

                &l2_table[l2_index], 0);

        nb_available = nb_clusters << (s->cluster_bits - 9);

        if (nb_available > n_end)

            nb_available = n_end;

        cluster_offset &= ~QCOW_OFLAG_COPIED;

        goto out;

    }

    /* for the moment, multiple compressed clusters are not managed */

    if (cluster_offset & QCOW_OFLAG_COMPRESSED)

        nb_clusters = 1;

    /* how many available clusters ? */

    while (i < nb_clusters) {

        int j;

        i += count_contiguous_free_clusters(nb_clusters - i,

                &l2_table[l2_index + i]);

        cluster_offset = be64_to_cpu(l2_table[l2_index + i]);

        if ((cluster_offset & QCOW_OFLAG_COPIED) ||

                (cluster_offset & QCOW_OFLAG_COMPRESSED))

            break;

        j = count_contiguous_clusters(nb_clusters - i, s->cluster_size,

                &l2_table[l2_index + i], 0);

        if (j)

            free_any_clusters(bs, cluster_offset, j);

        i += j;

        if(be64_to_cpu(l2_table[l2_index + i]))

            break;

    }

    nb_clusters = i;

    /* allocate a new cluster */

    cluster_offset = alloc_clusters(bs, nb_clusters * s->cluster_size);

    /* we must initialize the cluster content which won't be

       written */

    nb_available = nb_clusters << (s->cluster_bits - 9);

    if (nb_available > n_end)

        nb_available = n_end;

    /* copy content of unmodified sectors */

    start_sect = (offset & ~(s->cluster_size - 1)) >> 9;

    if (n_start) {

        ret = copy_sectors(bs, start_sect, cluster_offset, 0, n_start);

        if (ret < 0)

            return 0;

    }

    if (nb_available & (s->cluster_sectors - 1)) {

        uint64_t end = nb_available & ~(uint64_t)(s->cluster_sectors - 1);

        ret = copy_sectors(bs, start_sect + end,

                           cluster_offset + (end << 9),

                           nb_available - end,

                           s->cluster_sectors);

        if (ret < 0)

            return 0;

    }

    /* update L2 table */

    for (i = 0; i < nb_clusters; i++)

        l2_table[l2_index + i] = cpu_to_be64((cluster_offset +

                                             (i << s->cluster_bits)) |

                                             QCOW_OFLAG_COPIED);

    if (bdrv_pwrite(s->hd,

                    l2_offset + l2_index * sizeof(uint64_t),

                    l2_table + l2_index,

                    nb_clusters * sizeof(uint64_t)) !=

                    nb_clusters * sizeof(uint64_t))

        return 0;

out:

    *num = nb_available - n_start;

    return cluster_offset;

}


void bdrv_io_limits_enable(BlockDriverState *bs)

{

    assert(!bs->io_limits_enabled);

    throttle_init(&bs->throttle_state,

                  bdrv_get_aio_context(bs),

                  QEMU_CLOCK_VIRTUAL,

                  bdrv_throttle_read_timer_cb,

                  bdrv_throttle_write_timer_cb,

                  bs);

    bs->io_limits_enabled = true;

}


static int tta_read_packet(AVFormatContext *s, AVPacket *pkt)

{

    TTAContext *c = s->priv_data;

    AVStream *st = s->streams[0];

    int size, ret;

    // FIXME!

    if (c->currentframe > c->totalframes)

        return -1;

    size = st->index_entries[c->currentframe].size;

    ret = av_get_packet(s->pb, pkt, size);

    pkt->dts = st->index_entries[c->currentframe++].timestamp;

    return ret;

}


static void stream_seek(VideoState *is, int64_t pos, int rel)

{

    is->seek_pos = pos;

    is->seek_req = 1;

    is->seek_flags = rel < 0 ? AVSEEK_FLAG_BACKWARD : 0;

}


void ram_control_before_iterate(QEMUFile *f, uint64_t flags)

{

    int ret = 0;

    if (f->ops->before_ram_iterate) {

        ret = f->ops->before_ram_iterate(f, f->opaque, flags);

        if (ret < 0) {

            qemu_file_set_error(f, ret);

        }

    }

}


static void spapr_tce_reset(DeviceState *dev)

{

    sPAPRTCETable *tcet = SPAPR_TCE_TABLE(dev);

    size_t table_size = tcet->nb_table * sizeof(uint64_t);

    memset(tcet->table, 0, table_size);

}


static int mjpeg_decode_app(MJpegDecodeContext *s)

{

    int len, id, i;

    len = get_bits(&s->gb, 16);

    if (len < 5)

        return AVERROR_INVALIDDATA;

    if (8 * len > get_bits_left(&s->gb))

        return AVERROR_INVALIDDATA;

    id   = get_bits_long(&s->gb, 32);

    id   = av_be2ne32(id);

    len -= 6;

    if (s->avctx->debug & FF_DEBUG_STARTCODE)

        av_log(s->avctx, AV_LOG_DEBUG, "APPx %8X\n", id);

    /* Buggy AVID, it puts EOI only at every 10th frame. */

    /* Also, this fourcc is used by non-avid files too, it holds some

       information, but it's always present in AVID-created files. */

    if (id == AV_RL32("AVI1")) {

        /* structure:

            4bytes      AVI1

            1bytes      polarity

            1bytes      always zero

            4bytes      field_size

            4bytes      field_size_less_padding

        */

            s->buggy_avid = 1;

        i = get_bits(&s->gb, 8); len--;

        av_log(s->avctx, AV_LOG_DEBUG, "polarity %d\n", i);

#if 0

        skip_bits(&s->gb, 8);

        skip_bits(&s->gb, 32);

        skip_bits(&s->gb, 32);

        len -= 10;

#endif

        goto out;

    }

//    len -= 2;

    if (id == AV_RL32("JFIF")) {

        int t_w, t_h, v1, v2;

        skip_bits(&s->gb, 8); /* the trailing zero-byte */

        v1 = get_bits(&s->gb, 8);

        v2 = get_bits(&s->gb, 8);

        skip_bits(&s->gb, 8);

        s->avctx->sample_aspect_ratio.num = get_bits(&s->gb, 16);

        s->avctx->sample_aspect_ratio.den = get_bits(&s->gb, 16);

        if (s->avctx->debug & FF_DEBUG_PICT_INFO)

            av_log(s->avctx, AV_LOG_INFO,

                   "mjpeg: JFIF header found (version: %x.%x) SAR=%d/%d\n",

                   v1, v2,

                   s->avctx->sample_aspect_ratio.num,

                   s->avctx->sample_aspect_ratio.den);

        t_w = get_bits(&s->gb, 8);

        t_h = get_bits(&s->gb, 8);

        if (t_w && t_h) {

            /* skip thumbnail */

            if (len -10 - (t_w * t_h * 3) > 0)

                len -= t_w * t_h * 3;

        }

        len -= 10;

        goto out;

    }

    if (id == AV_RL32("Adob") && (get_bits(&s->gb, 8) == 'e')) {

        if (s->avctx->debug & FF_DEBUG_PICT_INFO)

            av_log(s->avctx, AV_LOG_INFO, "mjpeg: Adobe header found\n");

        skip_bits(&s->gb, 16); /* version */

        skip_bits(&s->gb, 16); /* flags0 */

        skip_bits(&s->gb, 16); /* flags1 */

        skip_bits(&s->gb,  8); /* transform */

        len -= 7;

        goto out;

    }

    if (id == AV_RL32("LJIF")) {

        if (s->avctx->debug & FF_DEBUG_PICT_INFO)

            av_log(s->avctx, AV_LOG_INFO,

                   "Pegasus lossless jpeg header found\n");

        skip_bits(&s->gb, 16); /* version ? */

        skip_bits(&s->gb, 16); /* unknwon always 0? */

        skip_bits(&s->gb, 16); /* unknwon always 0? */

        skip_bits(&s->gb, 16); /* unknwon always 0? */

        switch (get_bits(&s->gb, 8)) {

        case 1:

            s->rgb         = 1;

            s->pegasus_rct = 0;

            break;

        case 2:

            s->rgb         = 1;

            s->pegasus_rct = 1;

            break;

        default:

            av_log(s->avctx, AV_LOG_ERROR, "unknown colorspace\n");

        }

        len -= 9;

        goto out;

    }

    /* Apple MJPEG-A */

    if ((s->start_code == APP1) && (len > (0x28 - 8))) {

        id   = get_bits_long(&s->gb, 32);

        id   = av_be2ne32(id);

        len -= 4;

        /* Apple MJPEG-A */

        if (id == AV_RL32("mjpg")) {

#if 0

            skip_bits(&s->gb, 32); /* field size */

            skip_bits(&s->gb, 32); /* pad field size */

            skip_bits(&s->gb, 32); /* next off */

            skip_bits(&s->gb, 32); /* quant off */

            skip_bits(&s->gb, 32); /* huff off */

            skip_bits(&s->gb, 32); /* image off */

            skip_bits(&s->gb, 32); /* scan off */

            skip_bits(&s->gb, 32); /* data off */

#endif

            if (s->avctx->debug & FF_DEBUG_PICT_INFO)

                av_log(s->avctx, AV_LOG_INFO, "mjpeg: Apple MJPEG-A header found\n");

        }

    }

out:

    /* slow but needed for extreme adobe jpegs */

    if (len < 0)

        av_log(s->avctx, AV_LOG_ERROR,

               "mjpeg: error, decode_app parser read over the end\n");

    while (--len > 0)

        skip_bits(&s->gb, 8);

    return 0;

}


static int draw_text(AVFilterContext *ctx, AVFilterBufferRef *picref,

                     int width, int height)

{

    DrawTextContext *dtext = ctx->priv;

    uint32_t code = 0, prev_code = 0;

    int x = 0, y = 0, i = 0, ret;

    int text_height;

    char *text = dtext->text;

    uint8_t *p;

    int str_w = 0, len;

    int y_min = 32000, y_max = -32000;

    FT_Vector delta;

    Glyph *glyph = NULL, *prev_glyph = NULL;

    Glyph dummy = { 0 };

    time_t now = time(0);

    struct tm ltime;

    uint8_t *buf = dtext->expanded_text;

    int buf_size = dtext->expanded_text_size;

    if(dtext->basetime != AV_NOPTS_VALUE)

        now= picref->pts*av_q2d(ctx->inputs[0]->time_base) + dtext->basetime/1000000;

    if (!buf) {

        buf_size = 2*strlen(dtext->text)+1;

        buf = av_malloc(buf_size);

    }

#if HAVE_LOCALTIME_R

    localtime_r(&now, &ltime);

#else

    if(strchr(dtext->text, '%'))

        ltime= *localtime(&now);

#endif

    do {

        *buf = 1;

        if (strftime(buf, buf_size, dtext->text, &ltime) != 0 || *buf == 0)

            break;

        buf_size *= 2;

    } while ((buf = av_realloc(buf, buf_size)));

    if (!buf)

        return AVERROR(ENOMEM);

    text = dtext->expanded_text = buf;

    dtext->expanded_text_size = buf_size;

    if ((len = strlen(text)) > dtext->nb_positions) {

        if (!(dtext->positions =

              av_realloc(dtext->positions, len*sizeof(*dtext->positions))))

            return AVERROR(ENOMEM);

        dtext->nb_positions = len;

    }

    x = dtext->x;

    y = dtext->y;

    /* load and cache glyphs */

    for (i = 0, p = text; *p; i++) {

        GET_UTF8(code, *p++, continue;);

        /* get glyph */

        dummy.code = code;

        glyph = av_tree_find(dtext->glyphs, &dummy, glyph_cmp, NULL);

        if (!glyph)

            load_glyph(ctx, &glyph, code);

        y_min = FFMIN(glyph->bbox.yMin, y_min);

        y_max = FFMAX(glyph->bbox.yMax, y_max);

    }

    text_height = y_max - y_min;

    /* compute and save position for each glyph */

    glyph = NULL;

    for (i = 0, p = text; *p; i++) {

        GET_UTF8(code, *p++, continue;);

        /* skip the \n in the sequence \r\n */

        if (prev_code == '\r' && code == '\n')

            continue;

        prev_code = code;

        if (is_newline(code)) {

            str_w = FFMAX(str_w, x - dtext->x);

            y += text_height;

            x = dtext->x;

            continue;

        }

        /* get glyph */

        prev_glyph = glyph;

        dummy.code = code;

        glyph = av_tree_find(dtext->glyphs, &dummy, glyph_cmp, NULL);

        /* kerning */

        if (dtext->use_kerning && prev_glyph && glyph->code) {

            FT_Get_Kerning(dtext->face, prev_glyph->code, glyph->code,

                           ft_kerning_default, &delta);

            x += delta.x >> 6;

        }

        if (x + glyph->bbox.xMax >= width) {

            str_w = FFMAX(str_w, x - dtext->x);

            y += text_height;

            x = dtext->x;

        }

        /* save position */

        dtext->positions[i].x = x + glyph->bitmap_left;

        dtext->positions[i].y = y - glyph->bitmap_top + y_max;

        if (code == '\t') x  = (x / dtext->tabsize + 1)*dtext->tabsize;

        else              x += glyph->advance;

    }

    str_w = FFMIN(width - dtext->x - 1, FFMAX(str_w, x - dtext->x));

    y     = FFMIN(y + text_height, height - 1);

    /* draw box */

    if (dtext->draw_box)

        drawbox(picref, dtext->x, dtext->y, str_w, y-dtext->y,

                dtext->box_line, dtext->pixel_step, dtext->boxcolor_rgba,

                dtext->hsub, dtext->vsub, dtext->is_packed_rgb, dtext->rgba_map);

    if (dtext->shadowx || dtext->shadowy) {

        if ((ret = draw_glyphs(dtext, picref, width, height, dtext->shadowcolor_rgba,

                               dtext->shadowcolor, dtext->shadowx, dtext->shadowy)) < 0)

            return ret;

    }

    if ((ret = draw_glyphs(dtext, picref, width, height, dtext->fontcolor_rgba,

                           dtext->fontcolor, 0, 0)) < 0)

        return ret;

    return 0;

}


void OPPROTO op_subfme_64 (void)

{

    T0 = ~T0 + xer_ca - 1;

    if (likely((uint64_t)T0 != (uint64_t)-1))

        xer_ca = 1;

    RETURN();

}


void qmp_block_set_io_throttle(const char *device, int64_t bps, int64_t bps_rd,

                               int64_t bps_wr, int64_t iops, int64_t iops_rd,

                               int64_t iops_wr, Error **errp)

{

    ThrottleConfig cfg;

    BlockDriverState *bs;

    bs = bdrv_find(device);

    if (!bs) {

        error_set(errp, QERR_DEVICE_NOT_FOUND, device);

        return;

    }

    memset(&cfg, 0, sizeof(cfg));

    cfg.buckets[THROTTLE_BPS_TOTAL].avg = bps;

    cfg.buckets[THROTTLE_BPS_READ].avg  = bps_rd;

    cfg.buckets[THROTTLE_BPS_WRITE].avg = bps_wr;

    cfg.buckets[THROTTLE_OPS_TOTAL].avg = iops;

    cfg.buckets[THROTTLE_OPS_READ].avg  = iops_rd;

    cfg.buckets[THROTTLE_OPS_WRITE].avg = iops_wr;

    cfg.buckets[THROTTLE_BPS_TOTAL].max = 0;

    cfg.buckets[THROTTLE_BPS_READ].max  = 0;

    cfg.buckets[THROTTLE_BPS_WRITE].max = 0;

    cfg.buckets[THROTTLE_OPS_TOTAL].max = 0;

    cfg.buckets[THROTTLE_OPS_READ].max  = 0;

    cfg.buckets[THROTTLE_OPS_WRITE].max = 0;

    cfg.op_size = 0;

    if (!check_throttle_config(&cfg, errp)) {

        return;

    }

    if (!bs->io_limits_enabled && throttle_enabled(&cfg)) {

        bdrv_io_limits_enable(bs);

    } else if (bs->io_limits_enabled && !throttle_enabled(&cfg)) {

        bdrv_io_limits_disable(bs);

    }

    if (bs->io_limits_enabled) {

        bdrv_set_io_limits(bs, &cfg);

    }

}


static inline void dxt3_block_internal(uint8_t *dst, ptrdiff_t stride,

                                       const uint8_t *block)

{

    int x, y;

    uint32_t colors[4];

    uint16_t color0 = AV_RL16(block +  8);

    uint16_t color1 = AV_RL16(block + 10);

    uint32_t code   = AV_RL32(block + 12);

    extract_color(colors, color0, color1, 1, 0);

    for (y = 0; y < 4; y++) {

        const uint16_t alpha_code = AV_RL16(block + 2 * y);

        uint8_t alpha_values[4];

        alpha_values[0] = ((alpha_code >>  0) & 0x0F) * 17;

        alpha_values[1] = ((alpha_code >>  4) & 0x0F) * 17;

        alpha_values[2] = ((alpha_code >>  8) & 0x0F) * 17;

        alpha_values[3] = ((alpha_code >> 12) & 0x0F) * 17;

        for (x = 0; x < 4; x++) {

            uint8_t alpha = alpha_values[x];

            uint32_t pixel = colors[code & 3] | (alpha << 24);

            code >>= 2;

            AV_WL32(dst + x * 4, pixel);

        }

        dst += stride;

    }

}


void tcg_func_start(TCGContext *s)

{

    tcg_pool_reset(s);

    s->nb_temps = s->nb_globals;

    /* No temps have been previously allocated for size or locality.  */

    memset(s->free_temps, 0, sizeof(s->free_temps));

    s->nb_labels = 0;

    s->current_frame_offset = s->frame_start;

#ifdef CONFIG_DEBUG_TCG

    s->goto_tb_issue_mask = 0;

#endif

    s->gen_op_buf[0].next = 1;

    s->gen_op_buf[0].prev = 0;

    s->gen_next_op_idx = 1;

}


static int find_unused_picture(MpegEncContext *s, int shared)

{

    int i;

    if (shared) {

        for (i = 0; i < MAX_PICTURE_COUNT; i++) {

            if (s->picture[i].f.data[0] == NULL)

                return i;

        }

    } else {

        for (i = 0; i < MAX_PICTURE_COUNT; i++) {

            if (pic_is_unused(s, &s->picture[i]))

                return i;

        }

    }

    av_log(s->avctx, AV_LOG_FATAL,

           "Internal error, picture buffer overflow\n");

    /* We could return -1, but the codec would crash trying to draw into a

     * non-existing frame anyway. This is safer than waiting for a random crash.

     * Also the return of this is never useful, an encoder must only allocate

     * as much as allowed in the specification. This has no relationship to how

     * much libavcodec could allocate (and MAX_PICTURE_COUNT is always large

     * enough for such valid streams).

     * Plus, a decoder has to check stream validity and remove frames if too

     * many reference frames are around. Waiting for "OOM" is not correct at

     * all. Similarly, missing reference frames have to be replaced by

     * interpolated/MC frames, anything else is a bug in the codec ...

     */

    abort();

    return -1;

}


static int xvid_encode_frame(AVCodecContext *avctx, AVPacket *pkt,

                             const AVFrame *picture, int *got_packet)

{

    int xerr, i, ret, user_packet = !!pkt->data;

    struct xvid_context *x = avctx->priv_data;

    AVFrame *p             = avctx->coded_frame;

    int mb_width  = (avctx->width  + 15) / 16;

    int mb_height = (avctx->height + 15) / 16;

    char *tmp;

    xvid_enc_frame_t xvid_enc_frame = { 0 };

    xvid_enc_stats_t xvid_enc_stats = { 0 };

    if ((ret = ff_alloc_packet2(avctx, pkt, mb_width*mb_height*MAX_MB_BYTES + FF_MIN_BUFFER_SIZE)) < 0)

        return ret;

    /* Start setting up the frame */

    xvid_enc_frame.version = XVID_VERSION;

    xvid_enc_stats.version = XVID_VERSION;

    /* Let Xvid know where to put the frame. */

    xvid_enc_frame.bitstream = pkt->data;

    xvid_enc_frame.length    = pkt->size;

    /* Initialize input image fields */

    if (avctx->pix_fmt != AV_PIX_FMT_YUV420P) {

        av_log(avctx, AV_LOG_ERROR,

               "Xvid: Color spaces other than 420P not supported\n");

        return AVERROR(EINVAL);

    }

    xvid_enc_frame.input.csp = XVID_CSP_PLANAR; /* YUV420P */

    for (i = 0; i < 4; i++) {

        xvid_enc_frame.input.plane[i]  = picture->data[i];

        xvid_enc_frame.input.stride[i] = picture->linesize[i];

    }

    /* Encoder Flags */

    xvid_enc_frame.vop_flags = x->vop_flags;

    xvid_enc_frame.vol_flags = x->vol_flags;

    xvid_enc_frame.motion    = x->me_flags;

    xvid_enc_frame.type      =

        picture->pict_type == AV_PICTURE_TYPE_I ? XVID_TYPE_IVOP :

        picture->pict_type == AV_PICTURE_TYPE_P ? XVID_TYPE_PVOP :

        picture->pict_type == AV_PICTURE_TYPE_B ? XVID_TYPE_BVOP :

                                                  XVID_TYPE_AUTO;

    /* Pixel aspect ratio setting */

    if (avctx->sample_aspect_ratio.num < 0 || avctx->sample_aspect_ratio.num > 255 ||

        avctx->sample_aspect_ratio.den < 0 || avctx->sample_aspect_ratio.den > 255) {

        av_log(avctx, AV_LOG_WARNING,

               "Invalid pixel aspect ratio %i/%i, limit is 255/255 reducing\n",

               avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den);

        av_reduce(&avctx->sample_aspect_ratio.num, &avctx->sample_aspect_ratio.den,

                   avctx->sample_aspect_ratio.num,  avctx->sample_aspect_ratio.den, 255);

    }

    xvid_enc_frame.par        = XVID_PAR_EXT;

    xvid_enc_frame.par_width  = avctx->sample_aspect_ratio.num;

    xvid_enc_frame.par_height = avctx->sample_aspect_ratio.den;

    /* Quant Setting */

    if (x->qscale)

        xvid_enc_frame.quant = picture->quality / FF_QP2LAMBDA;

    else

        xvid_enc_frame.quant = 0;

    /* Matrices */

    xvid_enc_frame.quant_intra_matrix = x->intra_matrix;

    xvid_enc_frame.quant_inter_matrix = x->inter_matrix;

    /* Encode */

    xerr = xvid_encore(x->encoder_handle, XVID_ENC_ENCODE,

                       &xvid_enc_frame, &xvid_enc_stats);

    /* Two-pass log buffer swapping */

    avctx->stats_out = NULL;

    if (x->twopassbuffer) {

        tmp                  = x->old_twopassbuffer;

        x->old_twopassbuffer = x->twopassbuffer;

        x->twopassbuffer     = tmp;

        x->twopassbuffer[0]  = 0;

        if (x->old_twopassbuffer[0] != 0) {

            avctx->stats_out = x->old_twopassbuffer;

        }

    }

    if (xerr > 0) {

        *got_packet = 1;

        p->quality = xvid_enc_stats.quant * FF_QP2LAMBDA;

        if (xvid_enc_stats.type == XVID_TYPE_PVOP)

            p->pict_type = AV_PICTURE_TYPE_P;

        else if (xvid_enc_stats.type == XVID_TYPE_BVOP)

            p->pict_type = AV_PICTURE_TYPE_B;

        else if (xvid_enc_stats.type == XVID_TYPE_SVOP)

            p->pict_type = AV_PICTURE_TYPE_S;

        else

            p->pict_type = AV_PICTURE_TYPE_I;

        if (xvid_enc_frame.out_flags & XVID_KEYFRAME) {

            p->key_frame = 1;

            pkt->flags  |= AV_PKT_FLAG_KEY;

            if (x->quicktime_format)

                return xvid_strip_vol_header(avctx, pkt,

                                             xvid_enc_stats.hlength, xerr);

        } else

            p->key_frame = 0;

        pkt->size = xerr;

        return 0;

    } else {

        if (!user_packet)

            av_free_packet(pkt);

        if (!xerr)

            return 0;

        av_log(avctx, AV_LOG_ERROR,

               "Xvid: Encoding Error Occurred: %i\n", xerr);

        return AVERROR_EXTERNAL;

    }

}


static void fdctrl_write_data (fdctrl_t *fdctrl, uint32_t value)

{

    fdrive_t *cur_drv;

    int pos;

    /* Reset mode */

    if (!(fdctrl->dor & FD_DOR_nRESET)) {

        FLOPPY_DPRINTF("Floppy controller in RESET state !\n");

        return;

    }

    if (!(fdctrl->msr & FD_MSR_RQM) || (fdctrl->msr & FD_MSR_DIO)) {

        FLOPPY_ERROR("controller not ready for writing\n");

        return;

    }

    fdctrl->dsr &= ~FD_DSR_PWRDOWN;

    /* Is it write command time ? */

    if (fdctrl->msr & FD_MSR_NONDMA) {

        /* FIFO data write */

        fdctrl->fifo[fdctrl->data_pos++] = value;

        if (fdctrl->data_pos % FD_SECTOR_LEN == (FD_SECTOR_LEN - 1) ||

            fdctrl->data_pos == fdctrl->data_len) {

            cur_drv = get_cur_drv(fdctrl);

            if (bdrv_write(cur_drv->bs, fd_sector(cur_drv), fdctrl->fifo, 1) < 0) {

                FLOPPY_ERROR("writing sector %d\n", fd_sector(cur_drv));

                return;

            }

            if (!fdctrl_seek_to_next_sect(fdctrl, cur_drv)) {

                FLOPPY_DPRINTF("error seeking to next sector %d\n",

                               fd_sector(cur_drv));

                return;

            }

        }

        /* Switch from transfer mode to status mode

         * then from status mode to command mode

         */

        if (fdctrl->data_pos == fdctrl->data_len)

            fdctrl_stop_transfer(fdctrl, FD_SR0_SEEK, 0x00, 0x00);

        return;

    }

    if (fdctrl->data_pos == 0) {

        /* Command */

        pos = command_to_handler[value & 0xff];

        FLOPPY_DPRINTF("%s command\n", handlers[pos].name);

        fdctrl->data_len = handlers[pos].parameters + 1;

    }

    FLOPPY_DPRINTF("%s: %02x\n", __func__, value);

    fdctrl->fifo[fdctrl->data_pos++] = value;

    if (fdctrl->data_pos == fdctrl->data_len) {

        /* We now have all parameters

         * and will be able to treat the command

         */

        if (fdctrl->data_state & FD_STATE_FORMAT) {

            fdctrl_format_sector(fdctrl);

            return;

        }

        pos = command_to_handler[fdctrl->fifo[0] & 0xff];

        FLOPPY_DPRINTF("treat %s command\n", handlers[pos].name);

        (*handlers[pos].handler)(fdctrl, handlers[pos].direction);

    }

}


void ff_avg_h264_qpel16_mc32_msa(uint8_t *dst, const uint8_t *src,

                                 ptrdiff_t stride)

{

    avc_luma_midh_qrt_and_aver_dst_16w_msa(src - (2 * stride) - 2,

                                           stride, dst, stride, 16, 1);

}


static int vhdx_create_new_region_table(BlockDriverState *bs,

                                        uint64_t image_size,

                                        uint32_t block_size,

                                        uint32_t sector_size,

                                        uint32_t log_size,

                                        bool use_zero_blocks,

                                        VHDXImageType type,

                                        uint64_t *metadata_offset)

{

    int ret = 0;

    uint32_t offset = 0;

    void *buffer = NULL;

    uint64_t bat_file_offset;

    uint32_t bat_length;

    BDRVVHDXState *s = NULL;

    VHDXRegionTableHeader *region_table;

    VHDXRegionTableEntry *rt_bat;

    VHDXRegionTableEntry *rt_metadata;

    assert(metadata_offset != NULL);

    /* Populate enough of the BDRVVHDXState to be able to use the

     * pre-existing BAT calculation, translation, and update functions */

    s = g_malloc0(sizeof(BDRVVHDXState));

    s->chunk_ratio = (VHDX_MAX_SECTORS_PER_BLOCK) *

                     (uint64_t) sector_size / (uint64_t) block_size;

    s->sectors_per_block = block_size / sector_size;

    s->virtual_disk_size = image_size;

    s->block_size = block_size;

    s->logical_sector_size = sector_size;

    vhdx_set_shift_bits(s);

    vhdx_calc_bat_entries(s);

    /* At this point the VHDX state is populated enough for creation */

    /* a single buffer is used so we can calculate the checksum over the

     * entire 64KB block */

    buffer = g_malloc0(VHDX_HEADER_BLOCK_SIZE);

    region_table = buffer;

    offset += sizeof(VHDXRegionTableHeader);

    rt_bat = buffer + offset;

    offset += sizeof(VHDXRegionTableEntry);

    rt_metadata  = buffer + offset;

    region_table->signature = VHDX_REGION_SIGNATURE;

    region_table->entry_count = 2;   /* BAT and Metadata */

    rt_bat->guid        = bat_guid;

    rt_bat->length      = ROUND_UP(s->bat_entries * sizeof(VHDXBatEntry), MiB);

    rt_bat->file_offset = ROUND_UP(VHDX_HEADER_SECTION_END + log_size, MiB);

    s->bat_offset = rt_bat->file_offset;

    rt_metadata->guid        = metadata_guid;

    rt_metadata->file_offset = ROUND_UP(rt_bat->file_offset + rt_bat->length,

                                        MiB);

    rt_metadata->length      = 1 * MiB; /* min size, and more than enough */

    *metadata_offset = rt_metadata->file_offset;

    bat_file_offset = rt_bat->file_offset;

    bat_length = rt_bat->length;

    vhdx_region_header_le_export(region_table);

    vhdx_region_entry_le_export(rt_bat);

    vhdx_region_entry_le_export(rt_metadata);

    vhdx_update_checksum(buffer, VHDX_HEADER_BLOCK_SIZE,

                         offsetof(VHDXRegionTableHeader, checksum));

    /* The region table gives us the data we need to create the BAT,

     * so do that now */

    ret = vhdx_create_bat(bs, s, image_size, type, use_zero_blocks,

                          bat_file_offset, bat_length);

    if (ret < 0) {

        goto exit;

    }

    /* Now write out the region headers to disk */

    ret = bdrv_pwrite(bs, VHDX_REGION_TABLE_OFFSET, buffer,

                      VHDX_HEADER_BLOCK_SIZE);

    if (ret < 0) {

        goto exit;

    }

    ret = bdrv_pwrite(bs, VHDX_REGION_TABLE2_OFFSET, buffer,

                      VHDX_HEADER_BLOCK_SIZE);

    if (ret < 0) {

        goto exit;

    }

exit:

    g_free(s);

    g_free(buffer);

    return ret;

}


iscsi_unmap_cb(struct iscsi_context *iscsi, int status,

                     void *command_data, void *opaque)

{

    IscsiAIOCB *acb = opaque;

    if (acb->canceled != 0) {

        qemu_aio_release(acb);

        scsi_free_scsi_task(acb->task);

        acb->task = NULL;

        return;

    }

    acb->status = 0;

    if (status < 0) {

        error_report("Failed to unmap data on iSCSI lun. %s",

                     iscsi_get_error(iscsi));

        acb->status = -EIO;

    }

    iscsi_schedule_bh(acb);

    scsi_free_scsi_task(acb->task);

    acb->task = NULL;

}


static void gen_wsr_prid(DisasContext *dc, uint32_t sr, TCGv_i32 v)

{

}