static int ppce500_load_device_tree(MachineState *machine,

                                    PPCE500Params *params,

                                    hwaddr addr,

                                    hwaddr initrd_base,

                                    hwaddr initrd_size,

                                    hwaddr kernel_base,

                                    hwaddr kernel_size,

                                    bool dry_run)

{

    CPUPPCState *env = first_cpu->env_ptr;

    int ret = -1;

    uint64_t mem_reg_property[] = { 0, cpu_to_be64(machine->ram_size) };

    int fdt_size;

    void *fdt;

    uint8_t hypercall[16];

    uint32_t clock_freq = 400000000;

    uint32_t tb_freq = 400000000;

    int i;

    char compatible_sb[] = "fsl,mpc8544-immr\0simple-bus";

    char soc[128];

    char mpic[128];

    uint32_t mpic_ph;

    uint32_t msi_ph;

    char gutil[128];

    char pci[128];

    char msi[128];

    uint32_t *pci_map = NULL;

    int len;

    uint32_t pci_ranges[14] =

        {

            0x2000000, 0x0, params->pci_mmio_bus_base,

            params->pci_mmio_base >> 32, params->pci_mmio_base,

            0x0, 0x20000000,

            0x1000000, 0x0, 0x0,

            params->pci_pio_base >> 32, params->pci_pio_base,

            0x0, 0x10000,

        };

    QemuOpts *machine_opts = qemu_get_machine_opts();

    const char *dtb_file = qemu_opt_get(machine_opts, "dtb");

    const char *toplevel_compat = qemu_opt_get(machine_opts, "dt_compatible");

    if (dtb_file) {

        char *filename;

        filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, dtb_file);

        if (!filename) {

            goto out;

        }

        fdt = load_device_tree(filename, &fdt_size);

        if (!fdt) {

            goto out;

        }

        goto done;

    }

    fdt = create_device_tree(&fdt_size);

    if (fdt == NULL) {

        goto out;

    }

    /* Manipulate device tree in memory. */

    qemu_fdt_setprop_cell(fdt, "/", "#address-cells", 2);

    qemu_fdt_setprop_cell(fdt, "/", "#size-cells", 2);

    qemu_fdt_add_subnode(fdt, "/memory");

    qemu_fdt_setprop_string(fdt, "/memory", "device_type", "memory");

    qemu_fdt_setprop(fdt, "/memory", "reg", mem_reg_property,

                     sizeof(mem_reg_property));

    qemu_fdt_add_subnode(fdt, "/chosen");

    if (initrd_size) {

        ret = qemu_fdt_setprop_cell(fdt, "/chosen", "linux,initrd-start",

                                    initrd_base);

        if (ret < 0) {

            fprintf(stderr, "couldn't set /chosen/linux,initrd-start\n");

        }

        ret = qemu_fdt_setprop_cell(fdt, "/chosen", "linux,initrd-end",

                                    (initrd_base + initrd_size));

        if (ret < 0) {

            fprintf(stderr, "couldn't set /chosen/linux,initrd-end\n");

        }

    }

    if (kernel_base != -1ULL) {

        qemu_fdt_setprop_cells(fdt, "/chosen", "qemu,boot-kernel",

                                     kernel_base >> 32, kernel_base,

                                     kernel_size >> 32, kernel_size);

    }

    ret = qemu_fdt_setprop_string(fdt, "/chosen", "bootargs",

                                      machine->kernel_cmdline);

    if (ret < 0)

        fprintf(stderr, "couldn't set /chosen/bootargs\n");

    if (kvm_enabled()) {

        /* Read out host's frequencies */

        clock_freq = kvmppc_get_clockfreq();

        tb_freq = kvmppc_get_tbfreq();

        /* indicate KVM hypercall interface */

        qemu_fdt_add_subnode(fdt, "/hypervisor");

        qemu_fdt_setprop_string(fdt, "/hypervisor", "compatible",

                                "linux,kvm");

        kvmppc_get_hypercall(env, hypercall, sizeof(hypercall));

        qemu_fdt_setprop(fdt, "/hypervisor", "hcall-instructions",

                         hypercall, sizeof(hypercall));

        /* if KVM supports the idle hcall, set property indicating this */

        if (kvmppc_get_hasidle(env)) {

            qemu_fdt_setprop(fdt, "/hypervisor", "has-idle", NULL, 0);

        }

    }

    /* Create CPU nodes */

    qemu_fdt_add_subnode(fdt, "/cpus");

    qemu_fdt_setprop_cell(fdt, "/cpus", "#address-cells", 1);

    qemu_fdt_setprop_cell(fdt, "/cpus", "#size-cells", 0);

    /* We need to generate the cpu nodes in reverse order, so Linux can pick

       the first node as boot node and be happy */

    for (i = smp_cpus - 1; i >= 0; i--) {

        CPUState *cpu;

        PowerPCCPU *pcpu;

        char cpu_name[128];

        uint64_t cpu_release_addr = params->spin_base + (i * 0x20);

        cpu = qemu_get_cpu(i);

        if (cpu == NULL) {

            continue;

        }

        env = cpu->env_ptr;

        pcpu = POWERPC_CPU(cpu);

        snprintf(cpu_name, sizeof(cpu_name), "/cpus/PowerPC,8544@%x",

                 ppc_get_vcpu_dt_id(pcpu));

        qemu_fdt_add_subnode(fdt, cpu_name);

        qemu_fdt_setprop_cell(fdt, cpu_name, "clock-frequency", clock_freq);

        qemu_fdt_setprop_cell(fdt, cpu_name, "timebase-frequency", tb_freq);

        qemu_fdt_setprop_string(fdt, cpu_name, "device_type", "cpu");

        qemu_fdt_setprop_cell(fdt, cpu_name, "reg",

                              ppc_get_vcpu_dt_id(pcpu));

        qemu_fdt_setprop_cell(fdt, cpu_name, "d-cache-line-size",

                              env->dcache_line_size);

        qemu_fdt_setprop_cell(fdt, cpu_name, "i-cache-line-size",

                              env->icache_line_size);

        qemu_fdt_setprop_cell(fdt, cpu_name, "d-cache-size", 0x8000);

        qemu_fdt_setprop_cell(fdt, cpu_name, "i-cache-size", 0x8000);

        qemu_fdt_setprop_cell(fdt, cpu_name, "bus-frequency", 0);

        if (cpu->cpu_index) {

            qemu_fdt_setprop_string(fdt, cpu_name, "status", "disabled");

            qemu_fdt_setprop_string(fdt, cpu_name, "enable-method",

                                    "spin-table");

            qemu_fdt_setprop_u64(fdt, cpu_name, "cpu-release-addr",

                                 cpu_release_addr);

        } else {

            qemu_fdt_setprop_string(fdt, cpu_name, "status", "okay");

        }

    }

    qemu_fdt_add_subnode(fdt, "/aliases");

    /* XXX These should go into their respective devices' code */

    snprintf(soc, sizeof(soc), "/soc@%"PRIx64, params->ccsrbar_base);

    qemu_fdt_add_subnode(fdt, soc);

    qemu_fdt_setprop_string(fdt, soc, "device_type", "soc");

    qemu_fdt_setprop(fdt, soc, "compatible", compatible_sb,

                     sizeof(compatible_sb));

    qemu_fdt_setprop_cell(fdt, soc, "#address-cells", 1);

    qemu_fdt_setprop_cell(fdt, soc, "#size-cells", 1);

    qemu_fdt_setprop_cells(fdt, soc, "ranges", 0x0,

                           params->ccsrbar_base >> 32, params->ccsrbar_base,

                           MPC8544_CCSRBAR_SIZE);

    /* XXX should contain a reasonable value */

    qemu_fdt_setprop_cell(fdt, soc, "bus-frequency", 0);

    snprintf(mpic, sizeof(mpic), "%s/pic@%llx", soc, MPC8544_MPIC_REGS_OFFSET);

    qemu_fdt_add_subnode(fdt, mpic);

    qemu_fdt_setprop_string(fdt, mpic, "device_type", "open-pic");

    qemu_fdt_setprop_string(fdt, mpic, "compatible", "fsl,mpic");

    qemu_fdt_setprop_cells(fdt, mpic, "reg", MPC8544_MPIC_REGS_OFFSET,

                           0x40000);

    qemu_fdt_setprop_cell(fdt, mpic, "#address-cells", 0);

    qemu_fdt_setprop_cell(fdt, mpic, "#interrupt-cells", 2);

    mpic_ph = qemu_fdt_alloc_phandle(fdt);

    qemu_fdt_setprop_cell(fdt, mpic, "phandle", mpic_ph);

    qemu_fdt_setprop_cell(fdt, mpic, "linux,phandle", mpic_ph);

    qemu_fdt_setprop(fdt, mpic, "interrupt-controller", NULL, 0);

    /*

     * We have to generate ser1 first, because Linux takes the first

     * device it finds in the dt as serial output device. And we generate

     * devices in reverse order to the dt.

     */

    if (serial_hds[1]) {

        dt_serial_create(fdt, MPC8544_SERIAL1_REGS_OFFSET,

                         soc, mpic, "serial1", 1, false);

    }

    if (serial_hds[0]) {

        dt_serial_create(fdt, MPC8544_SERIAL0_REGS_OFFSET,

                         soc, mpic, "serial0", 0, true);

    }

    snprintf(gutil, sizeof(gutil), "%s/global-utilities@%llx", soc,

             MPC8544_UTIL_OFFSET);

    qemu_fdt_add_subnode(fdt, gutil);

    qemu_fdt_setprop_string(fdt, gutil, "compatible", "fsl,mpc8544-guts");

    qemu_fdt_setprop_cells(fdt, gutil, "reg", MPC8544_UTIL_OFFSET, 0x1000);

    qemu_fdt_setprop(fdt, gutil, "fsl,has-rstcr", NULL, 0);

    snprintf(msi, sizeof(msi), "/%s/msi@%llx", soc, MPC8544_MSI_REGS_OFFSET);

    qemu_fdt_add_subnode(fdt, msi);

    qemu_fdt_setprop_string(fdt, msi, "compatible", "fsl,mpic-msi");

    qemu_fdt_setprop_cells(fdt, msi, "reg", MPC8544_MSI_REGS_OFFSET, 0x200);

    msi_ph = qemu_fdt_alloc_phandle(fdt);

    qemu_fdt_setprop_cells(fdt, msi, "msi-available-ranges", 0x0, 0x100);

    qemu_fdt_setprop_phandle(fdt, msi, "interrupt-parent", mpic);

    qemu_fdt_setprop_cells(fdt, msi, "interrupts",

        0xe0, 0x0,

        0xe1, 0x0,

        0xe2, 0x0,

        0xe3, 0x0,

        0xe4, 0x0,

        0xe5, 0x0,

        0xe6, 0x0,

        0xe7, 0x0);

    qemu_fdt_setprop_cell(fdt, msi, "phandle", msi_ph);

    qemu_fdt_setprop_cell(fdt, msi, "linux,phandle", msi_ph);

    snprintf(pci, sizeof(pci), "/pci@%llx",

             params->ccsrbar_base + MPC8544_PCI_REGS_OFFSET);

    qemu_fdt_add_subnode(fdt, pci);

    qemu_fdt_setprop_cell(fdt, pci, "cell-index", 0);

    qemu_fdt_setprop_string(fdt, pci, "compatible", "fsl,mpc8540-pci");

    qemu_fdt_setprop_string(fdt, pci, "device_type", "pci");

    qemu_fdt_setprop_cells(fdt, pci, "interrupt-map-mask", 0xf800, 0x0,

                           0x0, 0x7);

    pci_map = pci_map_create(fdt, qemu_fdt_get_phandle(fdt, mpic),

                             params->pci_first_slot, params->pci_nr_slots,

                             &len);

    qemu_fdt_setprop(fdt, pci, "interrupt-map", pci_map, len);

    qemu_fdt_setprop_phandle(fdt, pci, "interrupt-parent", mpic);

    qemu_fdt_setprop_cells(fdt, pci, "interrupts", 24, 2);

    qemu_fdt_setprop_cells(fdt, pci, "bus-range", 0, 255);

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

        pci_ranges[i] = cpu_to_be32(pci_ranges[i]);

    }

    qemu_fdt_setprop_cell(fdt, pci, "fsl,msi", msi_ph);

    qemu_fdt_setprop(fdt, pci, "ranges", pci_ranges, sizeof(pci_ranges));

    qemu_fdt_setprop_cells(fdt, pci, "reg",

                           (params->ccsrbar_base + MPC8544_PCI_REGS_OFFSET) >> 32,

                           (params->ccsrbar_base + MPC8544_PCI_REGS_OFFSET),

                           0, 0x1000);

    qemu_fdt_setprop_cell(fdt, pci, "clock-frequency", 66666666);

    qemu_fdt_setprop_cell(fdt, pci, "#interrupt-cells", 1);

    qemu_fdt_setprop_cell(fdt, pci, "#size-cells", 2);

    qemu_fdt_setprop_cell(fdt, pci, "#address-cells", 3);

    qemu_fdt_setprop_string(fdt, "/aliases", "pci0", pci);

    if (params->has_mpc8xxx_gpio) {

        create_dt_mpc8xxx_gpio(fdt, soc, mpic);

    }

    if (params->has_platform_bus) {

        platform_bus_create_devtree(params, fdt, mpic);

    }

    params->fixup_devtree(params, fdt);

    if (toplevel_compat) {

        qemu_fdt_setprop(fdt, "/", "compatible", toplevel_compat,

                         strlen(toplevel_compat) + 1);

    }

done:

    if (!dry_run) {

        qemu_fdt_dumpdtb(fdt, fdt_size);

        cpu_physical_memory_write(addr, fdt, fdt_size);

    }

    ret = fdt_size;

out:

    g_free(pci_map);

    return ret;

}


pvscsi_on_cmd_setup_rings(PVSCSIState *s)

{

    PVSCSICmdDescSetupRings *rc =

        (PVSCSICmdDescSetupRings *) s->curr_cmd_data;

    trace_pvscsi_on_cmd_arrived("PVSCSI_CMD_SETUP_RINGS");

    pvscsi_dbg_dump_tx_rings_config(rc);

    pvscsi_ring_init_data(&s->rings, rc);

    s->rings_info_valid = TRUE;

    return PVSCSI_COMMAND_PROCESSING_SUCCEEDED;

}


void ff_snow_vertical_compose97i_mmx(IDWTELEM *b0, IDWTELEM *b1, IDWTELEM *b2, IDWTELEM *b3, IDWTELEM *b4, IDWTELEM *b5, int width){

    long i = width;

    while(i & 15)

    {

        i--;

        b4[i] -= (W_DM*(b3[i] + b5[i])+W_DO)>>W_DS;

        b3[i] -= (W_CM*(b2[i] + b4[i])+W_CO)>>W_CS;

        b2[i] += (W_BM*(b1[i] + b3[i])+4*b2[i]+W_BO)>>W_BS;

        b1[i] += (W_AM*(b0[i] + b2[i])+W_AO)>>W_AS;

    }

    i+=i;

    asm volatile(

        "jmp 2f                                      \n\t"

        "1:                                          \n\t"

        snow_vertical_compose_mmx_load("%4","mm0","mm2","mm4","mm6")

        snow_vertical_compose_mmx_add("%6","mm0","mm2","mm4","mm6")

        snow_vertical_compose_mmx_move("mm0","mm2","mm4","mm6","mm1","mm3","mm5","mm7")

        snow_vertical_compose_sra("1","mm0","mm2","mm4","mm6")

        snow_vertical_compose_r2r_add("mm1","mm3","mm5","mm7","mm0","mm2","mm4","mm6")

        "pcmpeqw %%mm1, %%mm1                        \n\t"

        "psllw $15, %%mm1                            \n\t"

        "psrlw $14, %%mm1                            \n\t"

        snow_vertical_compose_r2r_add("mm1","mm1","mm1","mm1","mm0","mm2","mm4","mm6")

        snow_vertical_compose_sra("2","mm0","mm2","mm4","mm6")

        snow_vertical_compose_mmx_load("%5","mm1","mm3","mm5","mm7")

        snow_vertical_compose_r2r_sub("mm0","mm2","mm4","mm6","mm1","mm3","mm5","mm7")

        snow_vertical_compose_mmx_store("%5","mm1","mm3","mm5","mm7")

        snow_vertical_compose_mmx_load("%4","mm0","mm2","mm4","mm6")

        snow_vertical_compose_mmx_add("%3","mm1","mm3","mm5","mm7")

        snow_vertical_compose_r2r_sub("mm1","mm3","mm5","mm7","mm0","mm2","mm4","mm6")

        snow_vertical_compose_mmx_store("%4","mm0","mm2","mm4","mm6")

        "pcmpeqw %%mm7, %%mm7                        \n\t"

        "pcmpeqw %%mm5, %%mm5                        \n\t"

        "psllw $15, %%mm7                            \n\t"

        "psrlw $13, %%mm5                            \n\t"

        "paddw %%mm7, %%mm5                          \n\t"

        snow_vertical_compose_r2r_add("mm5","mm5","mm5","mm5","mm0","mm2","mm4","mm6")

        "movq   (%2,%%"REG_d"), %%mm1         \n\t"

        "movq  8(%2,%%"REG_d"), %%mm3         \n\t"

        "paddw %%mm7, %%mm1                          \n\t"

        "paddw %%mm7, %%mm3                          \n\t"

        "pavgw %%mm1, %%mm0                          \n\t"

        "pavgw %%mm3, %%mm2                          \n\t"

        "movq 16(%2,%%"REG_d"), %%mm1         \n\t"

        "movq 24(%2,%%"REG_d"), %%mm3         \n\t"

        "paddw %%mm7, %%mm1                          \n\t"

        "paddw %%mm7, %%mm3                          \n\t"

        "pavgw %%mm1, %%mm4                          \n\t"

        "pavgw %%mm3, %%mm6                          \n\t"

        snow_vertical_compose_r2r_sub("mm7","mm7","mm7","mm7","mm0","mm2","mm4","mm6")

        snow_vertical_compose_sra("1","mm0","mm2","mm4","mm6")

        snow_vertical_compose_mmx_add("%3","mm0","mm2","mm4","mm6")

        snow_vertical_compose_sra("2","mm0","mm2","mm4","mm6")

        snow_vertical_compose_mmx_add("%3","mm0","mm2","mm4","mm6")

        snow_vertical_compose_mmx_store("%3","mm0","mm2","mm4","mm6")

        snow_vertical_compose_mmx_add("%1","mm0","mm2","mm4","mm6")

        snow_vertical_compose_mmx_move("mm0","mm2","mm4","mm6","mm1","mm3","mm5","mm7")

        snow_vertical_compose_sra("1","mm0","mm2","mm4","mm6")

        snow_vertical_compose_r2r_add("mm1","mm3","mm5","mm7","mm0","mm2","mm4","mm6")

        snow_vertical_compose_mmx_add("%2","mm0","mm2","mm4","mm6")

        snow_vertical_compose_mmx_store("%2","mm0","mm2","mm4","mm6")

        "2:                                          \n\t"

        "sub $32, %%"REG_d"                          \n\t"

        "jge 1b                                      \n\t"

        :"+d"(i)

        :"r"(b0),"r"(b1),"r"(b2),"r"(b3),"r"(b4),"r"(b5));

}


static int parse_add_fd(QemuOpts *opts, void *opaque)

{

    int fd, dupfd, flags;

    int64_t fdset_id;

    const char *fd_opaque = NULL;

    fd = qemu_opt_get_number(opts, "fd", -1);

    fdset_id = qemu_opt_get_number(opts, "set", -1);

    fd_opaque = qemu_opt_get(opts, "opaque");

    if (fd < 0) {

        qerror_report(ERROR_CLASS_GENERIC_ERROR,

                      "fd option is required and must be non-negative");

        return -1;

    }

    if (fd <= STDERR_FILENO) {

        qerror_report(ERROR_CLASS_GENERIC_ERROR,

                      "fd cannot be a standard I/O stream");

        return -1;

    }

    /*

     * All fds inherited across exec() necessarily have FD_CLOEXEC

     * clear, while qemu sets FD_CLOEXEC on all other fds used internally.

     */

    flags = fcntl(fd, F_GETFD);

    if (flags == -1 || (flags & FD_CLOEXEC)) {

        qerror_report(ERROR_CLASS_GENERIC_ERROR,

                      "fd is not valid or already in use");

        return -1;

    }

    if (fdset_id < 0) {

        qerror_report(ERROR_CLASS_GENERIC_ERROR,

                      "set option is required and must be non-negative");

        return -1;

    }

#ifdef F_DUPFD_CLOEXEC

    dupfd = fcntl(fd, F_DUPFD_CLOEXEC, 0);

#else

    dupfd = dup(fd);

    if (dupfd != -1) {

        qemu_set_cloexec(dupfd);

    }

#endif

    if (dupfd == -1) {

        qerror_report(ERROR_CLASS_GENERIC_ERROR,

                      "Error duplicating fd: %s", strerror(errno));

        return -1;

    }

    /* add the duplicate fd, and optionally the opaque string, to the fd set */

    monitor_fdset_add_fd(dupfd, true, fdset_id, fd_opaque ? true : false,

                         fd_opaque, NULL);

    return 0;

}


void av_thread_message_flush(AVThreadMessageQueue *mq)

{

#if HAVE_THREADS

    int used, off;

    void *free_func = mq->free_func;

    pthread_mutex_lock(&mq->lock);

    used = av_fifo_size(mq->fifo);

    if (free_func)

        for (off = 0; off < used; off += mq->elsize)

            av_fifo_generic_peek_at(mq->fifo, mq, off, mq->elsize, free_func_wrap);

    av_fifo_drain(mq->fifo, used);

    pthread_cond_broadcast(&mq->cond);

    pthread_mutex_unlock(&mq->lock);

#endif /* HAVE_THREADS */

}


int av_open_input_stream(AVFormatContext **ic_ptr,

                         AVIOContext *pb, const char *filename,

                         AVInputFormat *fmt, AVFormatParameters *ap)

{

    int err;

    AVDictionary *opts;

    AVFormatContext *ic;

    AVFormatParameters default_ap;

    if(!ap){

        ap=&default_ap;

        memset(ap, 0, sizeof(default_ap));

    }

    opts = convert_format_parameters(ap);

    if(!ap->prealloced_context)

        ic = avformat_alloc_context();

    else

        ic = *ic_ptr;

    if (!ic) {

        err = AVERROR(ENOMEM);

        goto fail;

    }

    if (pb && fmt && fmt->flags & AVFMT_NOFILE)

        av_log(ic, AV_LOG_WARNING, "Custom AVIOContext makes no sense and "

                                   "will be ignored with AVFMT_NOFILE format.\n");

    else

        ic->pb = pb;

    err = avformat_open_input(&ic, filename, fmt, &opts);

    ic->pb = ic->pb ? ic->pb : pb; // don't leak custom pb if it wasn't set above

    *ic_ptr = ic;

fail:

    av_dict_free(&opts);

    return err;

}


void hmp_info_local_apic(Monitor *mon, const QDict *qdict)

{

    x86_cpu_dump_local_apic_state(mon_get_cpu(), (FILE *)mon, monitor_fprintf,

                                  CPU_DUMP_FPU);

}


void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)

{

    if (!mon)

        return;

    if (mon->mc && !mon->mc->print_enabled) {

        qemu_error_new(QERR_UNDEFINED_ERROR);

    } else {

        char buf[4096];

        vsnprintf(buf, sizeof(buf), fmt, ap);

        monitor_puts(mon, buf);

    }

}


static void piix4_acpi_system_hot_add_init(MemoryRegion *parent,

                                           PCIBus *bus, PIIX4PMState *s)

{

    memory_region_init_io(&s->io_gpe, OBJECT(s), &piix4_gpe_ops, s,

                          "acpi-gpe0", GPE_LEN);

    memory_region_add_subregion(parent, GPE_BASE, &s->io_gpe);

    acpi_pcihp_init(OBJECT(s), &s->acpi_pci_hotplug, bus, parent,

                    s->use_acpi_pci_hotplug);

    s->cpu_hotplug_legacy = true;

    object_property_add_bool(OBJECT(s), "cpu-hotplug-legacy",

                             piix4_get_cpu_hotplug_legacy,

                             piix4_set_cpu_hotplug_legacy,

                             NULL);

    legacy_acpi_cpu_hotplug_init(parent, OBJECT(s), &s->gpe_cpu,

                                 PIIX4_CPU_HOTPLUG_IO_BASE);

    if (s->acpi_memory_hotplug.is_enabled) {

        acpi_memory_hotplug_init(parent, OBJECT(s), &s->acpi_memory_hotplug);

    }

}


long do_sigreturn(CPUX86State *env)

{

    struct sigframe *frame;

    abi_ulong frame_addr = env->regs[R_ESP] - 8;

    target_sigset_t target_set;

    sigset_t set;

    int eax, i;

#if defined(DEBUG_SIGNAL)

    fprintf(stderr, "do_sigreturn\n");

#endif

    if (!lock_user_struct(VERIFY_READ, frame, frame_addr, 1))

        goto badframe;

    /* set blocked signals */

    if (__get_user(target_set.sig[0], &frame->sc.oldmask))

        goto badframe;

    for(i = 1; i < TARGET_NSIG_WORDS; i++) {

        if (__get_user(target_set.sig[i], &frame->extramask[i - 1]))

            goto badframe;

    }

    target_to_host_sigset_internal(&set, &target_set);

    sigprocmask(SIG_SETMASK, &set, NULL);

    /* restore registers */

    if (restore_sigcontext(env, &frame->sc, &eax))

        goto badframe;

    unlock_user_struct(frame, frame_addr, 0);

    return eax;

badframe:

    unlock_user_struct(frame, frame_addr, 0);

    force_sig(TARGET_SIGSEGV);

    return 0;

}


static ssize_t vc_sendv_compat(VLANClientState *vc, const struct iovec *iov,

                               int iovcnt)

{

    uint8_t buffer[4096];

    size_t offset = 0;

    int i;

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

        size_t len;

        len = MIN(sizeof(buffer) - offset, iov[i].iov_len);

        memcpy(buffer + offset, iov[i].iov_base, len);

        offset += len;

    }

    vc->receive(vc->opaque, buffer, offset);

    return offset;

}


void do_blockdev_backup(BlockdevBackup *backup, BlockJobTxn *txn, Error **errp)

{

    BlockDriverState *bs;

    BlockDriverState *target_bs;

    Error *local_err = NULL;

    AioContext *aio_context;

    if (!backup->has_speed) {

        backup->speed = 0;

    }

    if (!backup->has_on_source_error) {

        backup->on_source_error = BLOCKDEV_ON_ERROR_REPORT;

    }

    if (!backup->has_on_target_error) {

        backup->on_target_error = BLOCKDEV_ON_ERROR_REPORT;

    }

    if (!backup->has_job_id) {

        backup->job_id = NULL;

    }

    bs = qmp_get_root_bs(backup->device, errp);

    if (!bs) {

        return;

    }

    aio_context = bdrv_get_aio_context(bs);

    aio_context_acquire(aio_context);

    target_bs = bdrv_lookup_bs(backup->target, backup->target, errp);

    if (!target_bs) {

        goto out;

    }

    if (bdrv_get_aio_context(target_bs) != aio_context) {

        if (!bdrv_has_blk(target_bs)) {

            /* The target BDS is not attached, we can safely move it to another

             * AioContext. */

            bdrv_set_aio_context(target_bs, aio_context);

        } else {

            error_setg(errp, "Target is attached to a different thread from "

                             "source.");

            goto out;

        }

    }

    backup_start(backup->job_id, bs, target_bs, backup->speed, backup->sync,

                 NULL, backup->on_source_error, backup->on_target_error,

                 block_job_cb, bs, txn, &local_err);

    if (local_err != NULL) {

        error_propagate(errp, local_err);

    }

out:

    aio_context_release(aio_context);

}


static void input_visitor_test_add(const char *testpath,

                                   TestInputVisitorData *data,

                                   void (*test_func)(TestInputVisitorData *data, const void *user_data))

{

    g_test_add(testpath, TestInputVisitorData, data, NULL, test_func,

               visitor_input_teardown);

}


void *block_job_create(const BlockJobType *job_type, BlockDriverState *bs,

                       BlockDriverCompletionFunc *cb, void *opaque,

                       Error **errp)

{

    BlockJob *job;

    if (bs->job || bdrv_in_use(bs)) {

        error_set(errp, QERR_DEVICE_IN_USE, bdrv_get_device_name(bs));

        return NULL;

    }

    bdrv_set_in_use(bs, 1);

    job = g_malloc0(job_type->instance_size);

    job->job_type      = job_type;

    job->bs            = bs;

    job->cb            = cb;

    job->opaque        = opaque;

    bs->job = job;

    return job;

}


int bdrv_is_snapshot(BlockDriverState *bs)

{

    return !!(bs->open_flags & BDRV_O_SNAPSHOT);

}


static void nvdimm_init_fit_buffer(NvdimmFitBuffer *fit_buf)

{

    qemu_mutex_init(&fit_buf->lock);

    fit_buf->fit = g_array_new(false, true /* clear */, 1);

}


static void test_cipher(const void *opaque)

{

    const QCryptoCipherTestData *data = opaque;

    QCryptoCipher *cipher;

    Error *err = NULL;

    uint8_t *key, *iv, *ciphertext, *plaintext, *outtext;

    size_t nkey, niv, nciphertext, nplaintext;

    char *outtexthex;

    g_test_message("foo");

    nkey = unhex_string(data->key, &key);

    niv = unhex_string(data->iv, &iv);

    nciphertext = unhex_string(data->ciphertext, &ciphertext);

    nplaintext = unhex_string(data->plaintext, &plaintext);

    g_assert(nciphertext == nplaintext);

    outtext = g_new0(uint8_t, nciphertext);

    cipher = qcrypto_cipher_new(

        data->alg, data->mode,

        key, nkey,

        &err);

    g_assert(cipher != NULL);

    g_assert(err == NULL);

    if (iv) {

        g_assert(qcrypto_cipher_setiv(cipher,

                                      iv, niv,

                                      &err) == 0);

        g_assert(err == NULL);

    }

    g_assert(qcrypto_cipher_encrypt(cipher,

                                    plaintext,

                                    outtext,

                                    nplaintext,

                                    &err) == 0);

    g_assert(err == NULL);

    outtexthex = hex_string(outtext, nciphertext);

    g_assert_cmpstr(outtexthex, ==, data->ciphertext);

    g_free(outtext);

    g_free(outtexthex);

    g_free(key);

    g_free(iv);

    g_free(ciphertext);

    g_free(plaintext);

    qcrypto_cipher_free(cipher);

}


static uint64_t pmsav5_insn_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)

{

    return simple_mpu_ap_bits(env->cp15.c5_insn);

}


static av_cold int libgsm_encode_init(AVCodecContext *avctx) {

    if (avctx->channels > 1) {

        av_log(avctx, AV_LOG_ERROR, "Mono required for GSM, got %d channels\n",

               avctx->channels);

        return -1;

    if (avctx->sample_rate != 8000) {

        av_log(avctx, AV_LOG_ERROR, "Sample rate 8000Hz required for GSM, got %dHz\n",

               avctx->sample_rate);

        if (avctx->strict_std_compliance > FF_COMPLIANCE_UNOFFICIAL)

            return -1;

    if (avctx->bit_rate != 13000 /* Official */ &&

        avctx->bit_rate != 13200 /* Very common */ &&

        avctx->bit_rate != 0 /* Unknown; a.o. mov does not set bitrate when decoding */ ) {

        av_log(avctx, AV_LOG_ERROR, "Bitrate 13000bps required for GSM, got %dbps\n",

               avctx->bit_rate);

        if (avctx->strict_std_compliance > FF_COMPLIANCE_UNOFFICIAL)

            return -1;

    avctx->priv_data = gsm_create();

    switch(avctx->codec_id) {

    case CODEC_ID_GSM:

        avctx->frame_size = GSM_FRAME_SIZE;

        avctx->block_align = GSM_BLOCK_SIZE;

        break;

    case CODEC_ID_GSM_MS: {

        int one = 1;

        gsm_option(avctx->priv_data, GSM_OPT_WAV49, &one);

        avctx->frame_size = 2*GSM_FRAME_SIZE;

        avctx->block_align = GSM_MS_BLOCK_SIZE;

    avctx->coded_frame= avcodec_alloc_frame();

    return 0;


static void avc_wgt_4x2_msa(uint8_t *data,

                            int32_t stride,

                            int32_t log2_denom,

                            int32_t src_weight,

                            int32_t offset_in)

{

    uint32_t data0, data1;

    v16u8 zero = { 0 };

    v16u8 src0, src1;

    v4i32 res0, res1;

    v8i16 temp0, temp1;

    v16u8 vec0, vec1;

    v8i16 wgt, denom, offset;

    offset_in <<= (log2_denom);

    if (log2_denom) {

        offset_in += (1 << (log2_denom - 1));

    }

    wgt = __msa_fill_h(src_weight);

    offset = __msa_fill_h(offset_in);

    denom = __msa_fill_h(log2_denom);

    data0 = LOAD_WORD(data);

    data1 = LOAD_WORD(data + stride);

    src0 = (v16u8) __msa_fill_w(data0);

    src1 = (v16u8) __msa_fill_w(data1);

    ILVR_B_2VECS_UB(src0, src1, zero, zero, vec0, vec1);

    temp0 = wgt * (v8i16) vec0;

    temp1 = wgt * (v8i16) vec1;

    temp0 = __msa_adds_s_h(temp0, offset);

    temp1 = __msa_adds_s_h(temp1, offset);

    temp0 = __msa_maxi_s_h(temp0, 0);

    temp1 = __msa_maxi_s_h(temp1, 0);

    temp0 = __msa_srl_h(temp0, denom);

    temp1 = __msa_srl_h(temp1, denom);

    temp0 = (v8i16) __msa_sat_u_h((v8u16) temp0, 7);

    temp1 = (v8i16) __msa_sat_u_h((v8u16) temp1, 7);

    res0 = (v4i32) __msa_pckev_b((v16i8) temp0, (v16i8) temp0);

    res1 = (v4i32) __msa_pckev_b((v16i8) temp1, (v16i8) temp1);

    data0 = __msa_copy_u_w(res0, 0);

    data1 = __msa_copy_u_w(res1, 0);

    STORE_WORD(data, data0);

    data += stride;

    STORE_WORD(data, data1);

}


static int quorum_open(BlockDriverState *bs, QDict *options, int flags,

                       Error **errp)

{

    BDRVQuorumState *s = bs->opaque;

    Error *local_err = NULL;

    QemuOpts *opts;

    bool *opened;

    QDict *sub = NULL;

    QList *list = NULL;

    const QListEntry *lentry;

    int i;

    int ret = 0;

    qdict_flatten(options);

    qdict_extract_subqdict(options, &sub, "children.");

    qdict_array_split(sub, &list);

    if (qdict_size(sub)) {

        error_setg(&local_err, "Invalid option children.%s",

                   qdict_first(sub)->key);

        ret = -EINVAL;

        goto exit;

    }

    /* count how many different children are present */

    s->num_children = qlist_size(list);

    if (s->num_children < 2) {

        error_setg(&local_err,

                   "Number of provided children must be greater than 1");

        ret = -EINVAL;

        goto exit;

    }

    opts = qemu_opts_create(&quorum_runtime_opts, NULL, 0, &error_abort);

    qemu_opts_absorb_qdict(opts, options, &local_err);

    if (local_err) {

        ret = -EINVAL;

        goto exit;

    }

    s->threshold = qemu_opt_get_number(opts, QUORUM_OPT_VOTE_THRESHOLD, 0);

    /* and validate it against s->num_children */

    ret = quorum_valid_threshold(s->threshold, s->num_children, &local_err);

    if (ret < 0) {

        goto exit;

    }

    /* is the driver in blkverify mode */

    if (qemu_opt_get_bool(opts, QUORUM_OPT_BLKVERIFY, false) &&

        s->num_children == 2 && s->threshold == 2) {

        s->is_blkverify = true;

    } else if (qemu_opt_get_bool(opts, QUORUM_OPT_BLKVERIFY, false)) {

        fprintf(stderr, "blkverify mode is set by setting blkverify=on "

                "and using two files with vote_threshold=2\n");

    }

    s->rewrite_corrupted = qemu_opt_get_bool(opts, QUORUM_OPT_REWRITE, false);

    if (s->rewrite_corrupted && s->is_blkverify) {

        error_setg(&local_err,

                   "rewrite-corrupted=on cannot be used with blkverify=on");

        ret = -EINVAL;

        goto exit;

    }

    /* allocate the children BlockDriverState array */

    s->bs = g_new0(BlockDriverState *, s->num_children);

    opened = g_new0(bool, s->num_children);

    for (i = 0, lentry = qlist_first(list); lentry;

         lentry = qlist_next(lentry), i++) {

        QDict *d;

        QString *string;

        switch (qobject_type(lentry->value))

        {

            /* List of options */

            case QTYPE_QDICT:

                d = qobject_to_qdict(lentry->value);

                QINCREF(d);

                ret = bdrv_open(&s->bs[i], NULL, NULL, d, flags, NULL,

                                &local_err);

                break;

            /* QMP reference */

            case QTYPE_QSTRING:

                string = qobject_to_qstring(lentry->value);

                ret = bdrv_open(&s->bs[i], NULL, qstring_get_str(string), NULL,

                                flags, NULL, &local_err);

                break;

            default:

                error_setg(&local_err, "Specification of child block device %i "

                           "is invalid", i);

                ret = -EINVAL;

        }

        if (ret < 0) {

            goto close_exit;

        }

        opened[i] = true;

    }

    g_free(opened);

    goto exit;

close_exit:

    /* cleanup on error */

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

        if (!opened[i]) {

            continue;

        }

        bdrv_unref(s->bs[i]);

    }

    g_free(s->bs);

    g_free(opened);

exit:

    /* propagate error */

    if (local_err) {

        error_propagate(errp, local_err);

    }

    QDECREF(list);

    QDECREF(sub);

    return ret;

}


void ff_imdct_calc_3dn2(MDCTContext *s, FFTSample *output,

                        const FFTSample *input, FFTSample *tmp)

{

    long n8, n4, n2, n;

    x86_reg k;

    const uint16_t *revtab = s->fft.revtab;

    const FFTSample *tcos = s->tcos;

    const FFTSample *tsin = s->tsin;

    const FFTSample *in1, *in2;

    FFTComplex *z = (FFTComplex *)tmp;

    n = 1 << s->nbits;

    n2 = n >> 1;

    n4 = n >> 2;

    n8 = n >> 3;

    /* pre rotation */

    in1 = input;

    in2 = input + n2 - 1;

    for(k = 0; k < n4; k++) {

        // FIXME a single block is faster, but gcc 2.95 and 3.4.x on 32bit can't compile it

        asm volatile(

            "movd       %0, %%mm0 \n\t"

            "movd       %2, %%mm1 \n\t"

            "punpckldq  %1, %%mm0 \n\t"

            "punpckldq  %3, %%mm1 \n\t"

            "movq    %%mm0, %%mm2 \n\t"

            "pfmul   %%mm1, %%mm0 \n\t"

            "pswapd  %%mm1, %%mm1 \n\t"

            "pfmul   %%mm1, %%mm2 \n\t"

            "pfpnacc %%mm2, %%mm0 \n\t"

            ::"m"(in2[-2*k]), "m"(in1[2*k]),

              "m"(tcos[k]), "m"(tsin[k])

        );

        asm volatile(

            "movq    %%mm0, %0    \n\t"

            :"=m"(z[revtab[k]])

        );

    }

    ff_fft_calc(&s->fft, z);

    /* post rotation + reordering */

    for(k = 0; k < n4; k++) {

        asm volatile(

            "movq       %0, %%mm0 \n\t"

            "movd       %1, %%mm1 \n\t"

            "punpckldq  %2, %%mm1 \n\t"

            "movq    %%mm0, %%mm2 \n\t"

            "pfmul   %%mm1, %%mm0 \n\t"

            "pswapd  %%mm1, %%mm1 \n\t"

            "pfmul   %%mm1, %%mm2 \n\t"

            "pfpnacc %%mm2, %%mm0 \n\t"

            "movq    %%mm0, %0    \n\t"

            :"+m"(z[k])

            :"m"(tcos[k]), "m"(tsin[k])

        );

    }

    k = n-8;

    asm volatile("movd %0, %%mm7" ::"r"(1<<31));

    asm volatile(

        "1: \n\t"

        "movq    (%4,%0), %%mm0 \n\t" // z[n8+k]

        "neg %0 \n\t"

        "pswapd -8(%4,%0), %%mm1 \n\t" // z[n8-1-k]

        "movq      %%mm0, %%mm2 \n\t"

        "pxor      %%mm7, %%mm2 \n\t"

        "punpckldq %%mm1, %%mm2 \n\t"

        "pswapd    %%mm2, %%mm3 \n\t"

        "punpckhdq %%mm1, %%mm0 \n\t"

        "pswapd    %%mm0, %%mm4 \n\t"

        "pxor      %%mm7, %%mm0 \n\t"

        "pxor      %%mm7, %%mm4 \n\t"

        "movq      %%mm3, -8(%3,%0) \n\t" // output[n-2-2*k] = { z[n8-1-k].im, -z[n8+k].re }

        "movq      %%mm4, -8(%2,%0) \n\t" // output[n2-2-2*k]= { -z[n8-1-k].re, z[n8+k].im }

        "neg %0 \n\t"

        "movq      %%mm0, (%1,%0) \n\t"   // output[2*k]     = { -z[n8+k].im, z[n8-1-k].re }

        "movq      %%mm2, (%2,%0) \n\t"   // output[n2+2*k]  = { -z[n8+k].re, z[n8-1-k].im }

        "sub $8, %0 \n\t"

        "jge 1b \n\t"

        :"+r"(k)

        :"r"(output), "r"(output+n2), "r"(output+n), "r"(z+n8)

        :"memory"

    );

    asm volatile("femms");

}


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

                                ptrdiff_t stride)

{

    avc_luma_vt_qrt_8w_msa(src - (stride * 2), stride, dst, stride, 8, 0);

}


int attribute_align_arg avcodec_open(AVCodecContext *avctx, AVCodec *codec)

{

    int ret = 0;

    /* If there is a user-supplied mutex locking routine, call it. */

    if (ff_lockmgr_cb) {

        if ((*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))

            return -1;

    }

    entangled_thread_counter++;

    if(entangled_thread_counter != 1){

        av_log(avctx, AV_LOG_ERROR, "insufficient thread locking around avcodec_open/close()\n");

        ret = -1;

        goto end;

    }

    if(avctx->codec || !codec) {

        ret = AVERROR(EINVAL);

        goto end;

    }

    if (codec->priv_data_size > 0) {

      if(!avctx->priv_data){

        avctx->priv_data = av_mallocz(codec->priv_data_size);

        if (!avctx->priv_data) {

            ret = AVERROR(ENOMEM);

            goto end;

        }

        if(codec->priv_class){ //this can be droped once all user apps use   avcodec_get_context_defaults3()

            *(AVClass**)avctx->priv_data= codec->priv_class;

            av_opt_set_defaults(avctx->priv_data);

        }

      }

    } else {

        avctx->priv_data = NULL;

    }

    if(avctx->coded_width && avctx->coded_height)

        avcodec_set_dimensions(avctx, avctx->coded_width, avctx->coded_height);

    else if(avctx->width && avctx->height)

        avcodec_set_dimensions(avctx, avctx->width, avctx->height);

    if ((avctx->coded_width || avctx->coded_height || avctx->width || avctx->height)

        && (  av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx) < 0

           || av_image_check_size(avctx->width,       avctx->height,       0, avctx) < 0)) {

        av_log(avctx, AV_LOG_WARNING, "ignoring invalid width/height values\n");

        avcodec_set_dimensions(avctx, 0, 0);

    }

    /* if the decoder init function was already called previously,

       free the already allocated subtitle_header before overwriting it */

    if (codec->decode)

        av_freep(&avctx->subtitle_header);

#define SANE_NB_CHANNELS 128U

    if (avctx->channels > SANE_NB_CHANNELS) {

        ret = AVERROR(EINVAL);

        goto free_and_end;

    }

    avctx->codec = codec;

    if ((avctx->codec_type == AVMEDIA_TYPE_UNKNOWN || avctx->codec_type == codec->type) &&

        avctx->codec_id == CODEC_ID_NONE) {

        avctx->codec_type = codec->type;

        avctx->codec_id   = codec->id;

    }

    if (avctx->codec_id != codec->id || (avctx->codec_type != codec->type

                           && avctx->codec_type != AVMEDIA_TYPE_ATTACHMENT)) {

        av_log(avctx, AV_LOG_ERROR, "codec type or id mismatches\n");

        ret = AVERROR(EINVAL);

        goto free_and_end;

    }

    avctx->frame_number = 0;

    if (HAVE_THREADS && !avctx->thread_opaque) {

        ret = ff_thread_init(avctx);

        if (ret < 0) {

            goto free_and_end;

        }

    }

    if (avctx->codec->max_lowres < avctx->lowres) {

        av_log(avctx, AV_LOG_ERROR, "The maximum value for lowres supported by the decoder is %d\n",

               avctx->codec->max_lowres);

        ret = AVERROR(EINVAL);

        goto free_and_end;

    }

    if (avctx->codec->sample_fmts && avctx->codec->encode) {

        int i;

        for (i = 0; avctx->codec->sample_fmts[i] != AV_SAMPLE_FMT_NONE; i++)

            if (avctx->sample_fmt == avctx->codec->sample_fmts[i])

                break;

        if (avctx->codec->sample_fmts[i] == AV_SAMPLE_FMT_NONE) {

            av_log(avctx, AV_LOG_ERROR, "Specified sample_fmt is not supported.\n");

            ret = AVERROR(EINVAL);

            goto free_and_end;

        }

    }

    if(avctx->codec->init && !(avctx->active_thread_type&FF_THREAD_FRAME)){

        ret = avctx->codec->init(avctx);

        if (ret < 0) {

            goto free_and_end;

        }

    }

end:

    entangled_thread_counter--;

    /* Release any user-supplied mutex. */

    if (ff_lockmgr_cb) {

        (*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE);

    }

    return ret;

free_and_end:

    av_freep(&avctx->priv_data);

    avctx->codec= NULL;

    goto end;

}


static int synth_superframe(AVCodecContext *ctx, AVFrame *frame,

                            int *got_frame_ptr)

{

    WMAVoiceContext *s = ctx->priv_data;

    GetBitContext *gb = &s->gb, s_gb;

    int n, res, n_samples = 480;

    double lsps[MAX_FRAMES][MAX_LSPS];

    const double *mean_lsf = s->lsps == 16 ?

        wmavoice_mean_lsf16[s->lsp_def_mode] : wmavoice_mean_lsf10[s->lsp_def_mode];

    float excitation[MAX_SIGNAL_HISTORY + MAX_SFRAMESIZE + 12];

    float synth[MAX_LSPS + MAX_SFRAMESIZE];

    float *samples;

    memcpy(synth,      s->synth_history,

           s->lsps             * sizeof(*synth));

    memcpy(excitation, s->excitation_history,

           s->history_nsamples * sizeof(*excitation));

    if (s->sframe_cache_size > 0) {

        gb = &s_gb;

        init_get_bits(gb, s->sframe_cache, s->sframe_cache_size);

        s->sframe_cache_size = 0;

    }

    if ((res = check_bits_for_superframe(gb, s)) == 1) {

        *got_frame_ptr = 0;

        return 1;

    } else if (res < 0)

        return res;

    /* First bit is speech/music bit, it differentiates between WMAVoice

     * speech samples (the actual codec) and WMAVoice music samples, which

     * are really WMAPro-in-WMAVoice-superframes. I've never seen those in

     * the wild yet. */

    if (!get_bits1(gb)) {

        avpriv_request_sample(ctx, "WMAPro-in-WMAVoice");

        return AVERROR_PATCHWELCOME;

    }

    /* (optional) nr. of samples in superframe; always <= 480 and >= 0 */

    if (get_bits1(gb)) {

        if ((n_samples = get_bits(gb, 12)) > 480) {

            av_log(ctx, AV_LOG_ERROR,

                   "Superframe encodes >480 samples (%d), not allowed\n",

                   n_samples);

            return AVERROR_INVALIDDATA;

        }

    }

    /* Parse LSPs, if global for the superframe (can also be per-frame). */

    if (s->has_residual_lsps) {

        double prev_lsps[MAX_LSPS], a1[MAX_LSPS * 2], a2[MAX_LSPS * 2];

        for (n = 0; n < s->lsps; n++)

            prev_lsps[n] = s->prev_lsps[n] - mean_lsf[n];

        if (s->lsps == 10) {

            dequant_lsp10r(gb, lsps[2], prev_lsps, a1, a2, s->lsp_q_mode);

        } else /* s->lsps == 16 */

            dequant_lsp16r(gb, lsps[2], prev_lsps, a1, a2, s->lsp_q_mode);

        for (n = 0; n < s->lsps; n++) {

            lsps[0][n]  = mean_lsf[n] + (a1[n]           - a2[n * 2]);

            lsps[1][n]  = mean_lsf[n] + (a1[s->lsps + n] - a2[n * 2 + 1]);

            lsps[2][n] += mean_lsf[n];

        }

        for (n = 0; n < 3; n++)

            stabilize_lsps(lsps[n], s->lsps);

    }

    /* get output buffer */

    frame->nb_samples = 480;

    if ((res = ff_get_buffer(ctx, frame, 0)) < 0)

        return res;

    frame->nb_samples = n_samples;

    samples = (float *)frame->data[0];

    /* Parse frames, optionally preceded by per-frame (independent) LSPs. */

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

        if (!s->has_residual_lsps) {

            int m;

            if (s->lsps == 10) {

                dequant_lsp10i(gb, lsps[n]);

            } else /* s->lsps == 16 */

                dequant_lsp16i(gb, lsps[n]);

            for (m = 0; m < s->lsps; m++)

                lsps[n][m] += mean_lsf[m];

            stabilize_lsps(lsps[n], s->lsps);

        }

        if ((res = synth_frame(ctx, gb, n,

                               &samples[n * MAX_FRAMESIZE],

                               lsps[n], n == 0 ? s->prev_lsps : lsps[n - 1],

                               &excitation[s->history_nsamples + n * MAX_FRAMESIZE],

                               &synth[s->lsps + n * MAX_FRAMESIZE]))) {

            *got_frame_ptr = 0;

            return res;

        }

    }

    /* Statistics? FIXME - we don't check for length, a slight overrun

     * will be caught by internal buffer padding, and anything else

     * will be skipped, not read. */

    if (get_bits1(gb)) {

        res = get_bits(gb, 4);

        skip_bits(gb, 10 * (res + 1));

    }

    *got_frame_ptr = 1;

    /* Update history */

    memcpy(s->prev_lsps,           lsps[2],

           s->lsps             * sizeof(*s->prev_lsps));

    memcpy(s->synth_history,      &synth[MAX_SFRAMESIZE],

           s->lsps             * sizeof(*synth));

    memcpy(s->excitation_history, &excitation[MAX_SFRAMESIZE],

           s->history_nsamples * sizeof(*excitation));

    if (s->do_apf)

        memmove(s->zero_exc_pf,       &s->zero_exc_pf[MAX_SFRAMESIZE],

                s->history_nsamples * sizeof(*s->zero_exc_pf));

    return 0;

}


static void virtual_css_bridge_class_init(ObjectClass *klass, void *data)

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    SysBusDeviceClass *k = SYS_BUS_DEVICE_CLASS(klass);

    k->init = virtual_css_bridge_init;

    dc->no_user = 1;

}


static void free_picture(MpegEncContext *s, Picture *pic){

    int i;

    if(pic->data[0] && pic->type!=FF_BUFFER_TYPE_SHARED){

        free_frame_buffer(s, pic);

    }

    av_freep(&pic->mb_var);

    av_freep(&pic->mc_mb_var);

    av_freep(&pic->mb_mean);

    av_freep(&pic->mbskip_table);

    av_freep(&pic->qscale_table);

    av_freep(&pic->mb_type_base);

    av_freep(&pic->dct_coeff);

    av_freep(&pic->pan_scan);

    pic->mb_type= NULL;

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

        av_freep(&pic->motion_val_base[i]);

        av_freep(&pic->ref_index[i]);

    }

    if(pic->type == FF_BUFFER_TYPE_SHARED){

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

            pic->base[i]=

            pic->data[i]= NULL;

        }

        pic->type= 0;

    }

}


static void tracked_request_begin(BdrvTrackedRequest *req,

                                  BlockDriverState *bs,

                                  int64_t sector_num,

                                  int nb_sectors, bool is_write)

{

    *req = (BdrvTrackedRequest){

        .bs = bs,

        .sector_num = sector_num,

        .nb_sectors = nb_sectors,

        .is_write = is_write,

    };

    qemu_co_queue_init(&req->wait_queue);

    QLIST_INSERT_HEAD(&bs->tracked_requests, req, list);

}


static int mov_read_close(AVFormatContext *s)

{

    int i;

    MOVContext *mov = s->priv_data;

    for(i=0; i<mov->total_streams; i++)

        mov_free_stream_context(mov->streams[i]);

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

        av_free(s->streams[i]);

    return 0;

}


static int aac_decode_frame(AVCodecContext *avccontext, void *data,

                            int *data_size, AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    AACContext *ac = avccontext->priv_data;

    ChannelElement *che = NULL, *che_prev = NULL;

    GetBitContext gb;

    enum RawDataBlockType elem_type, elem_type_prev = TYPE_END;

    int err, elem_id, data_size_tmp;

    int buf_consumed;

    int samples = 1024, multiplier;

    int buf_offset;

    init_get_bits(&gb, buf, buf_size * 8);

    if (show_bits(&gb, 12) == 0xfff) {

        if (parse_adts_frame_header(ac, &gb) < 0) {

            av_log(avccontext, AV_LOG_ERROR, "Error decoding AAC frame header.\n");

            return -1;

        }

        if (ac->m4ac.sampling_index > 12) {

            av_log(ac->avccontext, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->m4ac.sampling_index);

            return -1;

        }

    }

    // parse

    while ((elem_type = get_bits(&gb, 3)) != TYPE_END) {

        elem_id = get_bits(&gb, 4);

        if (elem_type < TYPE_DSE && !(che=get_che(ac, elem_type, elem_id))) {

            av_log(ac->avccontext, AV_LOG_ERROR, "channel element %d.%d is not allocated\n", elem_type, elem_id);

            return -1;

        }

        switch (elem_type) {

        case TYPE_SCE:

            err = decode_ics(ac, &che->ch[0], &gb, 0, 0);

            break;

        case TYPE_CPE:

            err = decode_cpe(ac, &gb, che);

            break;

        case TYPE_CCE:

            err = decode_cce(ac, &gb, che);

            break;

        case TYPE_LFE:

            err = decode_ics(ac, &che->ch[0], &gb, 0, 0);

            break;

        case TYPE_DSE:

            err = skip_data_stream_element(ac, &gb);

            break;

        case TYPE_PCE: {

            enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];

            memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));

            if ((err = decode_pce(ac, new_che_pos, &gb)))

                break;

            if (ac->output_configured > OC_TRIAL_PCE)

                av_log(avccontext, AV_LOG_ERROR,

                       "Not evaluating a further program_config_element as this construct is dubious at best.\n");

            else

                err = output_configure(ac, ac->che_pos, new_che_pos, 0, OC_TRIAL_PCE);

            break;

        }

        case TYPE_FIL:

            if (elem_id == 15)

                elem_id += get_bits(&gb, 8) - 1;

            if (get_bits_left(&gb) < 8 * elem_id) {

                    av_log(avccontext, AV_LOG_ERROR, overread_err);

                    return -1;

            }

            while (elem_id > 0)

                elem_id -= decode_extension_payload(ac, &gb, elem_id, che_prev, elem_type_prev);

            err = 0; /* FIXME */

            break;

        default:

            err = -1; /* should not happen, but keeps compiler happy */

            break;

        }

        che_prev       = che;

        elem_type_prev = elem_type;

        if (err)

            return err;

        if (get_bits_left(&gb) < 3) {

            av_log(avccontext, AV_LOG_ERROR, overread_err);

            return -1;

        }

    }

    spectral_to_sample(ac);

    multiplier = (ac->m4ac.sbr == 1) ? ac->m4ac.ext_sample_rate > ac->m4ac.sample_rate : 0;

    samples <<= multiplier;

    if (ac->output_configured < OC_LOCKED) {

        avccontext->sample_rate = ac->m4ac.sample_rate << multiplier;

        avccontext->frame_size = samples;

    }

    data_size_tmp = samples * avccontext->channels * sizeof(int16_t);

    if (*data_size < data_size_tmp) {

        av_log(avccontext, AV_LOG_ERROR,

               "Output buffer too small (%d) or trying to output too many samples (%d) for this frame.\n",

               *data_size, data_size_tmp);

        return -1;

    }

    *data_size = data_size_tmp;

    ac->dsp.float_to_int16_interleave(data, (const float **)ac->output_data, samples, avccontext->channels);

    if (ac->output_configured)

        ac->output_configured = OC_LOCKED;

    buf_consumed = (get_bits_count(&gb) + 7) >> 3;

    for (buf_offset = buf_consumed; buf_offset < buf_size; buf_offset++)

        if (buf[buf_offset])

            break;

    return buf_size > buf_offset ? buf_consumed : buf_size;

}


static inline void dv_guess_qnos(EncBlockInfo* blks, int* qnos)

{

    int size[5];

    int i, j, k, a, prev, a2;

    EncBlockInfo* b;

    size[4]= 1<<24;

    do {

       b = blks;

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

          if (!qnos[i])

              continue;

          qnos[i]--;

          size[i] = 0;

          for (j=0; j<6; j++, b++) {

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

                if (b->area_q[a] != dv_quant_shifts[qnos[i] + dv_quant_offset[b->cno]][a]) {

                    b->bit_size[a] = 1; // 4 areas 4 bits for EOB :)

                    b->area_q[a]++;

                    prev= b->prev[a];

                    for (k= b->next[prev] ; k<mb_area_start[a+1]; k= b->next[k]) {

                       b->mb[k] >>= 1;

                       if (b->mb[k]) {

                           b->bit_size[a] += dv_rl2vlc_size(k - prev - 1, b->mb[k]);

                           prev= k;

                       } else {

                           if(b->next[k] >= mb_area_start[a+1] && b->next[k]<64){

                                for(a2=a+1; b->next[k] >= mb_area_start[a2+1]; a2++);

                                assert(a2<4);

                                assert(b->mb[b->next[k]]);

                                b->bit_size[a2] += dv_rl2vlc_size(b->next[k] - prev - 1, b->mb[b->next[k]])

                                                  -dv_rl2vlc_size(b->next[k] -    k - 1, b->mb[b->next[k]]);

                           }

                           b->next[prev] = b->next[k];

                       }

                    }

                    b->prev[a+1]= prev;

                }

                size[i] += b->bit_size[a];

             }

          }

          if(vs_total_ac_bits >= size[0] + size[1] + size[2] + size[3] + size[4])

                return;

       }

    } while (qnos[0]|qnos[1]|qnos[2]|qnos[3]|qnos[4]);

    for(a=2; a==2 || vs_total_ac_bits < size[0]; a+=a){

        b = blks;

        size[0] = 5*6*4; //EOB

        for (j=0; j<6*5; j++, b++) {

            prev= b->prev[0];

            for (k= b->next[prev]; k<64; k= b->next[k]) {

                if(b->mb[k] < a && b->mb[k] > -a){

                    b->next[prev] = b->next[k];

                }else{

                    size[0] += dv_rl2vlc_size(k - prev - 1, b->mb[k]);

                    prev= k;

                }

            }

        }

    }

}


static av_cold int hnm_decode_init(AVCodecContext *avctx)

{

    Hnm4VideoContext *hnm = avctx->priv_data;

    if (avctx->extradata_size < 1) {

        av_log(avctx, AV_LOG_ERROR,

               "Extradata missing, decoder requires version number\n");

        return AVERROR_INVALIDDATA;

    }

    hnm->version   = avctx->extradata[0];

    avctx->pix_fmt = AV_PIX_FMT_PAL8;

    hnm->width     = avctx->width;

    hnm->height    = avctx->height;

    hnm->buffer1   = av_mallocz(avctx->width * avctx->height);

    hnm->buffer2   = av_mallocz(avctx->width * avctx->height);

    hnm->processed = av_mallocz(avctx->width * avctx->height);

    if (!hnm->buffer1 || !hnm->buffer2 || !hnm->processed) {

        av_log(avctx, AV_LOG_ERROR, "av_mallocz() failed\n");

        av_freep(&hnm->buffer1);

        av_freep(&hnm->buffer2);

        av_freep(&hnm->processed);

        return AVERROR(ENOMEM);

    }

    hnm->current  = hnm->buffer1;

    hnm->previous = hnm->buffer2;

    return 0;

}


static int coroutine_fn bdrv_aligned_preadv(BlockDriverState *bs,

    BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,

    int64_t align, QEMUIOVector *qiov, int flags)

{

    BlockDriver *drv = bs->drv;

    int ret;

    int64_t sector_num = offset >> BDRV_SECTOR_BITS;

    unsigned int nb_sectors = bytes >> BDRV_SECTOR_BITS;

    assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);

    assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);

    /* Handle Copy on Read and associated serialisation */

    if (flags & BDRV_REQ_COPY_ON_READ) {

        /* If we touch the same cluster it counts as an overlap.  This

         * guarantees that allocating writes will be serialized and not race

         * with each other for the same cluster.  For example, in copy-on-read

         * it ensures that the CoR read and write operations are atomic and

         * guest writes cannot interleave between them. */

        mark_request_serialising(req, bdrv_get_cluster_size(bs));

    }

    wait_serialising_requests(req);

    if (flags & BDRV_REQ_COPY_ON_READ) {

        int pnum;

        ret = bdrv_is_allocated(bs, sector_num, nb_sectors, &pnum);

        if (ret < 0) {

            goto out;

        }

        if (!ret || pnum != nb_sectors) {

            ret = bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors, qiov);

            goto out;

        }

    }

    /* Forward the request to the BlockDriver */

    if (!(bs->zero_beyond_eof && bs->growable)) {

        ret = drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);

    } else {

        /* Read zeros after EOF of growable BDSes */

        int64_t len, total_sectors, max_nb_sectors;

        len = bdrv_getlength(bs);

        if (len < 0) {

            ret = len;

            goto out;

        }

        total_sectors = DIV_ROUND_UP(len, BDRV_SECTOR_SIZE);

        max_nb_sectors = ROUND_UP(MAX(0, total_sectors - sector_num),

                                  align >> BDRV_SECTOR_BITS);

        if (max_nb_sectors > 0) {

            ret = drv->bdrv_co_readv(bs, sector_num,

                                     MIN(nb_sectors, max_nb_sectors), qiov);

        } else {

            ret = 0;

        }

        /* Reading beyond end of file is supposed to produce zeroes */

        if (ret == 0 && total_sectors < sector_num + nb_sectors) {

            uint64_t offset = MAX(0, total_sectors - sector_num);

            uint64_t bytes = (sector_num + nb_sectors - offset) *

                              BDRV_SECTOR_SIZE;

            qemu_iovec_memset(qiov, offset * BDRV_SECTOR_SIZE, 0, bytes);

        }

    }

out:

    return ret;

}


static uint16_t nvme_identify_ns(NvmeCtrl *n, NvmeIdentify *c)

{

    NvmeNamespace *ns;

    uint32_t nsid = le32_to_cpu(c->nsid);

    uint64_t prp1 = le64_to_cpu(c->prp1);

    uint64_t prp2 = le64_to_cpu(c->prp2);

    if (nsid == 0 || nsid > n->num_namespaces) {

        return NVME_INVALID_NSID | NVME_DNR;

    }

    ns = &n->namespaces[nsid - 1];

    return nvme_dma_read_prp(n, (uint8_t *)&ns->id_ns, sizeof(ns->id_ns),

        prp1, prp2);

}


void dpy_gfx_replace_surface(QemuConsole *con,
                             DisplaySurface *surface)
{
    DisplayState *s = con->ds;
    DisplaySurface *old_surface = con->surface;
    DisplayChangeListener *dcl;
    con->surface = surface;
    QLIST_FOREACH(dcl, &s->listeners, next) {
        if (con != (dcl->con ? dcl->con : active_console)) {
            continue;
        }
        if (dcl->ops->dpy_gfx_switch) {
            dcl->ops->dpy_gfx_switch(dcl, surface);
        }
    }
    qemu_free_displaysurface(old_surface);
}


static int tqi_decode_frame(AVCodecContext *avctx,

                            void *data, int *data_size,

                            AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    const uint8_t *buf_end = buf+buf_size;

    TqiContext *t = avctx->priv_data;

    MpegEncContext *s = &t->s;

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

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

    tqi_calculate_qtable(s, buf[4]);

    buf += 8;

    if (t->frame.data[0])

        avctx->release_buffer(avctx, &t->frame);

    if (s->avctx->width!=s->width || s->avctx->height!=s->height)

        avcodec_set_dimensions(s->avctx, s->width, s->height);

    if(avctx->get_buffer(avctx, &t->frame) < 0) {

        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");

        return -1;

    }

    av_fast_malloc(&t->bitstream_buf, &t->bitstream_buf_size, (buf_end-buf) + FF_INPUT_BUFFER_PADDING_SIZE);

    if (!t->bitstream_buf)

        return AVERROR(ENOMEM);

    s->dsp.bswap_buf(t->bitstream_buf, (const uint32_t*)buf, (buf_end-buf)/4);

    init_get_bits(&s->gb, t->bitstream_buf, 8*(buf_end-buf));

    s->last_dc[0] = s->last_dc[1] = s->last_dc[2] = 0;

    for (s->mb_y=0; s->mb_y<(avctx->height+15)/16; s->mb_y++)

    for (s->mb_x=0; s->mb_x<(avctx->width+15)/16; s->mb_x++)

    {

        if(tqi_decode_mb(s, t->block) < 0)

            break;

        tqi_idct_put(t, t->block);

    }

    *data_size = sizeof(AVFrame);

    *(AVFrame*)data = t->frame;

    return buf_size;

}


static void patch_call(VAPICROMState *s, X86CPU *cpu, target_ulong ip,

                       uint32_t target)

{

    uint32_t offset;

    offset = cpu_to_le32(target - ip - 5);

    patch_byte(cpu, ip, 0xe8); /* call near */

    cpu_memory_rw_debug(CPU(cpu), ip + 1, (void *)&offset, sizeof(offset), 1);

}


static void sbr_dequant(SpectralBandReplication *sbr, int id_aac)

{

    int k, e;

    int ch;

    if (id_aac == TYPE_CPE && sbr->bs_coupling) {

        float alpha      = sbr->data[0].bs_amp_res ?  1.0f :  0.5f;

        float pan_offset = sbr->data[0].bs_amp_res ? 12.0f : 24.0f;

        for (e = 1; e <= sbr->data[0].bs_num_env; e++) {

            for (k = 0; k < sbr->n[sbr->data[0].bs_freq_res[e]]; k++) {

                float temp1 = exp2f(sbr->data[0].env_facs[e][k] * alpha + 7.0f);

                float temp2 = exp2f((pan_offset - sbr->data[1].env_facs[e][k]) * alpha);

                float fac   = temp1 / (1.0f + temp2);

                sbr->data[0].env_facs[e][k] = fac;

                sbr->data[1].env_facs[e][k] = fac * temp2;

            }

        }

        for (e = 1; e <= sbr->data[0].bs_num_noise; e++) {

            for (k = 0; k < sbr->n_q; k++) {

                float temp1 = exp2f(NOISE_FLOOR_OFFSET - sbr->data[0].noise_facs[e][k] + 1);

                float temp2 = exp2f(12 - sbr->data[1].noise_facs[e][k]);

                float fac   = temp1 / (1.0f + temp2);

                sbr->data[0].noise_facs[e][k] = fac;

                sbr->data[1].noise_facs[e][k] = fac * temp2;

            }

        }

    } else { // SCE or one non-coupled CPE

        for (ch = 0; ch < (id_aac == TYPE_CPE) + 1; ch++) {

            float alpha = sbr->data[ch].bs_amp_res ? 1.0f : 0.5f;

            for (e = 1; e <= sbr->data[ch].bs_num_env; e++)

                for (k = 0; k < sbr->n[sbr->data[ch].bs_freq_res[e]]; k++)

                    sbr->data[ch].env_facs[e][k] =

                        exp2f(alpha * sbr->data[ch].env_facs[e][k] + 6.0f);

            for (e = 1; e <= sbr->data[ch].bs_num_noise; e++)

                for (k = 0; k < sbr->n_q; k++)

                    sbr->data[ch].noise_facs[e][k] =

                        exp2f(NOISE_FLOOR_OFFSET - sbr->data[ch].noise_facs[e][k]);

        }

    }

}


static inline int16_t logadd(int16_t a, int16_t b)

{

    int16_t c = a - b;

    uint8_t address = FFMIN((ABS(c) >> 1), 255);

    return ((c >= 0) ? (a + latab[address]) : (b + latab[address]));

}


static void range_merge(Range *range1, Range *range2)

{

    if (range1->end < range2->end) {

        range1->end = range2->end;

    }

    if (range1->begin > range2->begin) {

        range1->begin = range2->begin;

    }

}


static int write_manifest(AVFormatContext *s, int final)

{

    DASHContext *c = s->priv_data;

    AVIOContext *out;

    char temp_filename[1024];

    int ret, i;

    AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);

    snprintf(temp_filename, sizeof(temp_filename), "%s.tmp", s->filename);

    ret = avio_open2(&out, temp_filename, AVIO_FLAG_WRITE, &s->interrupt_callback, NULL);

    if (ret < 0) {

        av_log(s, AV_LOG_ERROR, "Unable to open %s for writing\n", temp_filename);

        return ret;

    }

    avio_printf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");

    avio_printf(out, "<MPD xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"

                "\txmlns=\"urn:mpeg:dash:schema:mpd:2011\"\n"

                "\txmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"

                "\txsi:schemaLocation=\"urn:mpeg:DASH:schema:MPD:2011 http://standards.iso.org/ittf/PubliclyAvailableStandards/MPEG-DASH_schema_files/DASH-MPD.xsd\"\n"

                "\tprofiles=\"urn:mpeg:dash:profile:isoff-live:2011\"\n"

                "\ttype=\"%s\"\n", final ? "static" : "dynamic");

    if (final) {

        avio_printf(out, "\tmediaPresentationDuration=\"");

        write_time(out, c->total_duration);

        avio_printf(out, "\"\n");

    } else {

        int update_period = c->last_duration / AV_TIME_BASE;

        if (c->use_template && !c->use_timeline)

            update_period = 500;

        avio_printf(out, "\tminimumUpdatePeriod=\"PT%dS\"\n", update_period);

        avio_printf(out, "\tsuggestedPresentationDelay=\"PT%dS\"\n", c->last_duration / AV_TIME_BASE);

        if (!c->availability_start_time[0] && s->nb_streams > 0 && c->streams[0].nb_segments > 0) {

            time_t t = time(NULL);

            struct tm *ptm, tmbuf;

            ptm = gmtime_r(&t, &tmbuf);

            if (ptm) {

                if (!strftime(c->availability_start_time, sizeof(c->availability_start_time),

                              "%Y-%m-%dT%H:%M:%S", ptm))

                    c->availability_start_time[0] = '\0';

            }

        }

        if (c->availability_start_time[0])

            avio_printf(out, "\tavailabilityStartTime=\"%s\"\n", c->availability_start_time);

        if (c->window_size && c->use_template) {

            avio_printf(out, "\ttimeShiftBufferDepth=\"");

            write_time(out, c->last_duration * c->window_size);

            avio_printf(out, "\"\n");

        }

    }

    avio_printf(out, "\tminBufferTime=\"");

    write_time(out, c->last_duration);

    avio_printf(out, "\">\n");

    avio_printf(out, "\t<ProgramInformation>\n");

    if (title) {

        char *escaped = xmlescape(title->value);

        avio_printf(out, "\t\t<Title>%s</Title>\n", escaped);

        av_free(escaped);

    }

    avio_printf(out, "\t</ProgramInformation>\n");

    if (c->window_size && s->nb_streams > 0 && c->streams[0].nb_segments > 0 && !c->use_template) {

        OutputStream *os = &c->streams[0];

        int start_index = FFMAX(os->nb_segments - c->window_size, 0);

        int64_t start_time = av_rescale_q(os->segments[start_index]->time, s->streams[0]->time_base, AV_TIME_BASE_Q);

        avio_printf(out, "\t<Period start=\"");

        write_time(out, start_time);

        avio_printf(out, "\">\n");

    } else {

        avio_printf(out, "\t<Period start=\"PT0.0S\">\n");

    }

    if (c->has_video) {

        avio_printf(out, "\t\t<AdaptationSet id=\"video\" segmentAlignment=\"true\" bitstreamSwitching=\"true\">\n");

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

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

            OutputStream *os = &c->streams[i];

            if (s->streams[i]->codec->codec_type != AVMEDIA_TYPE_VIDEO)

                continue;

            avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"video/mp4\" codecs=\"%s\"%s width=\"%d\" height=\"%d\">\n", i, os->codec_str, os->bandwidth_str, st->codec->width, st->codec->height);

            output_segment_list(&c->streams[i], out, c);

            avio_printf(out, "\t\t\t</Representation>\n");

        }

        avio_printf(out, "\t\t</AdaptationSet>\n");

    }

    if (c->has_audio) {

        avio_printf(out, "\t\t<AdaptationSet id=\"audio\" segmentAlignment=\"true\" bitstreamSwitching=\"true\">\n");

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

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

            OutputStream *os = &c->streams[i];

            if (s->streams[i]->codec->codec_type != AVMEDIA_TYPE_AUDIO)

                continue;

            avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"audio/mp4\" codecs=\"%s\"%s audioSamplingRate=\"%d\">\n", i, os->codec_str, os->bandwidth_str, st->codec->sample_rate);

            avio_printf(out, "\t\t\t\t<AudioChannelConfiguration schemeIdUri=\"urn:mpeg:dash:23003:3:audio_channel_configuration:2011\" value=\"%d\" />\n", st->codec->channels);

            output_segment_list(&c->streams[i], out, c);

            avio_printf(out, "\t\t\t</Representation>\n");

        }

        avio_printf(out, "\t\t</AdaptationSet>\n");

    }

    avio_printf(out, "\t</Period>\n");

    avio_printf(out, "</MPD>\n");

    avio_flush(out);

    avio_close(out);

    return ff_rename(temp_filename, s->filename, s);

}


static int get_scale_factor(H264SliceContext *sl,

                            int poc, int poc1, int i)

{

    int poc0 = sl->ref_list[0][i].poc;

    int td = av_clip_int8(poc1 - poc0);

    if (td == 0 || sl->ref_list[0][i].parent->long_ref) {

        return 256;

    } else {

        int tb = av_clip_int8(poc - poc0);

        int tx = (16384 + (FFABS(td) >> 1)) / td;

        return av_clip_intp2((tb * tx + 32) >> 6, 10);

    }

}


static int ppc_hash64_pte_prot(CPUPPCState *env,

                               ppc_slb_t *slb, ppc_hash_pte64_t pte)

{

    unsigned pp, key;

    /* Some pp bit combinations have undefined behaviour, so default

     * to no access in those cases */

    int prot = 0;

    key = !!(msr_pr ? (slb->vsid & SLB_VSID_KP)

             : (slb->vsid & SLB_VSID_KS));

    pp = (pte.pte1 & HPTE64_R_PP) | ((pte.pte1 & HPTE64_R_PP0) >> 61);

    if (key == 0) {

        switch (pp) {

        case 0x0:

        case 0x1:

        case 0x2:

            prot = PAGE_READ | PAGE_WRITE;

            break;

        case 0x3:

        case 0x6:

            prot = PAGE_READ;

            break;

        }

    } else {

        switch (pp) {

        case 0x0:

        case 0x6:

            prot = 0;

            break;

        case 0x1:

        case 0x3:

            prot = PAGE_READ;

            break;

        case 0x2:

            prot = PAGE_READ | PAGE_WRITE;

            break;

        }

    }

    /* No execute if either noexec or guarded bits set */

    if (!(pte.pte1 & HPTE64_R_N) || (pte.pte1 & HPTE64_R_G)) {

        prot |= PAGE_EXEC;

    }

    return prot;

}


static int get_video_frame(VideoState *is, AVFrame *frame, int64_t *pts, AVPacket *pkt)

{

    int got_picture, i;

    if (packet_queue_get(&is->videoq, pkt, 1) < 0)

        return -1;

    if (pkt->data == flush_pkt.data) {

        avcodec_flush_buffers(is->video_st->codec);

        SDL_LockMutex(is->pictq_mutex);

        // Make sure there are no long delay timers (ideally we should just flush the que but thats harder)

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

            is->pictq[i].skip = 1;

        }

        while (is->pictq_size && !is->videoq.abort_request) {

            SDL_CondWait(is->pictq_cond, is->pictq_mutex);

        }

        is->video_current_pos = -1;

        is->frame_last_pts = AV_NOPTS_VALUE;

        is->frame_last_duration = 0;

        is->frame_timer = (double)av_gettime() / 1000000.0;

        is->frame_last_dropped_pts = AV_NOPTS_VALUE;

        SDL_UnlockMutex(is->pictq_mutex);

        return 0;

    }

    avcodec_decode_video2(is->video_st->codec, frame, &got_picture, pkt);

    if (got_picture) {

        int ret = 1;

        if (decoder_reorder_pts == -1) {

            *pts = av_frame_get_best_effort_timestamp(frame);

        } else if (decoder_reorder_pts) {

            *pts = frame->pkt_pts;

        } else {

            *pts = frame->pkt_dts;

        }

        if (*pts == AV_NOPTS_VALUE) {

            *pts = 0;

        }

        if (((is->av_sync_type == AV_SYNC_AUDIO_MASTER && is->audio_st) || is->av_sync_type == AV_SYNC_EXTERNAL_CLOCK) &&

             (framedrop>0 || (framedrop && is->audio_st))) {

            SDL_LockMutex(is->pictq_mutex);

            if (is->frame_last_pts != AV_NOPTS_VALUE && *pts) {

                double clockdiff = get_video_clock(is) - get_master_clock(is);

                double dpts = av_q2d(is->video_st->time_base) * *pts;

                double ptsdiff = dpts - is->frame_last_pts;

                if (fabs(clockdiff) < AV_NOSYNC_THRESHOLD &&

                     ptsdiff > 0 && ptsdiff < AV_NOSYNC_THRESHOLD &&

                     clockdiff + ptsdiff - is->frame_last_filter_delay < 0) {

                    is->frame_last_dropped_pos = pkt->pos;

                    is->frame_last_dropped_pts = dpts;

                    is->frame_drops_early++;

                    ret = 0;

                }

            }

            SDL_UnlockMutex(is->pictq_mutex);

        }

        return ret;

    }

    return 0;

}


static void omap_sysctl_write8(void *opaque, target_phys_addr_t addr,

                uint32_t value)

{

    struct omap_sysctl_s *s = (struct omap_sysctl_s *) opaque;

    int pad_offset, byte_offset;

    int prev_value;

    switch (addr) {

    case 0x030 ... 0x140:	/* CONTROL_PADCONF - only used in the POP */

        pad_offset = (addr - 0x30) >> 2;

        byte_offset = (addr - 0x30) & (4 - 1);

        prev_value = s->padconf[pad_offset];

        prev_value &= ~(0xff << (byte_offset * 8));

        prev_value |= ((value & 0x1f1f1f1f) << (byte_offset * 8)) & 0x1f1f1f1f;

        s->padconf[pad_offset] = prev_value;

        break;

    default:

        OMAP_BAD_REG(addr);

        break;

    }

}


static void l2tpv3_update_fd_handler(NetL2TPV3State *s)

{

    qemu_set_fd_handler2(s->fd,

                         s->read_poll ? l2tpv3_can_send : NULL,

                         s->read_poll ? net_l2tpv3_send     : NULL,

                         s->write_poll ? l2tpv3_writable : NULL,

                         s);

}


void bdrv_set_boot_sector(BlockDriverState *bs, const uint8_t *data, int size)

{

    bs->boot_sector_enabled = 1;

    if (size > 512)

        size = 512;

    memcpy(bs->boot_sector_data, data, size);

    memset(bs->boot_sector_data + size, 0, 512 - size);

}


void helper_sysexit(CPUX86State *env, int dflag)

{

    int cpl;

    cpl = env->hflags & HF_CPL_MASK;

    if (env->sysenter_cs == 0 || cpl != 0) {

        raise_exception_err(env, EXCP0D_GPF, 0);

    }

    cpu_x86_set_cpl(env, 3);

#ifdef TARGET_X86_64

    if (dflag == 2) {

        cpu_x86_load_seg_cache(env, R_CS, ((env->sysenter_cs + 32) & 0xfffc) |

                               3, 0, 0xffffffff,

                               DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |

                               DESC_S_MASK | (3 << DESC_DPL_SHIFT) |

                               DESC_CS_MASK | DESC_R_MASK | DESC_A_MASK |

                               DESC_L_MASK);

        cpu_x86_load_seg_cache(env, R_SS, ((env->sysenter_cs + 40) & 0xfffc) |

                               3, 0, 0xffffffff,

                               DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |

                               DESC_S_MASK | (3 << DESC_DPL_SHIFT) |

                               DESC_W_MASK | DESC_A_MASK);

    } else

#endif

    {

        cpu_x86_load_seg_cache(env, R_CS, ((env->sysenter_cs + 16) & 0xfffc) |

                               3, 0, 0xffffffff,

                               DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |

                               DESC_S_MASK | (3 << DESC_DPL_SHIFT) |

                               DESC_CS_MASK | DESC_R_MASK | DESC_A_MASK);

        cpu_x86_load_seg_cache(env, R_SS, ((env->sysenter_cs + 24) & 0xfffc) |

                               3, 0, 0xffffffff,

                               DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |

                               DESC_S_MASK | (3 << DESC_DPL_SHIFT) |

                               DESC_W_MASK | DESC_A_MASK);

    }

    env->regs[R_ESP] = env->regs[R_ECX];

    env->eip = env->regs[R_EDX];

}


static int slirp_guestfwd(SlirpState *s, const char *config_str,

                          int legacy_format)

{

    struct in_addr server = { .s_addr = 0 };

    struct GuestFwd *fwd;

    const char *p;

    char buf[128];

    char *end;

    int port;

    p = config_str;

    if (legacy_format) {

        if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {

            goto fail_syntax;

        }

    } else {

        if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {

            goto fail_syntax;

        }

        if (strcmp(buf, "tcp") && buf[0] != '\0') {

            goto fail_syntax;

        }

        if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {

            goto fail_syntax;

        }

        if (buf[0] != '\0' && !inet_aton(buf, &server)) {

            goto fail_syntax;

        }

        if (get_str_sep(buf, sizeof(buf), &p, '-') < 0) {

            goto fail_syntax;

        }

    }

    port = strtol(buf, &end, 10);

    if (*end != '\0' || port < 1 || port > 65535) {

        goto fail_syntax;

    }

    fwd = qemu_malloc(sizeof(struct GuestFwd));

    snprintf(buf, sizeof(buf), "guestfwd.tcp:%d", port);

    fwd->hd = qemu_chr_open(buf, p, NULL);

    if (!fwd->hd) {

        error_report("could not open guest forwarding device '%s'", buf);

        qemu_free(fwd);

        return -1;

    }

    if (slirp_add_exec(s->slirp, 3, fwd->hd, &server, port) < 0) {

        error_report("conflicting/invalid host:port in guest forwarding "

                     "rule '%s'", config_str);

        qemu_free(fwd);

        return -1;

    }

    fwd->server = server;

    fwd->port = port;

    fwd->slirp = s->slirp;

    qemu_chr_add_handlers(fwd->hd, guestfwd_can_read, guestfwd_read,

                          NULL, fwd);

    return 0;

 fail_syntax:

    error_report("invalid guest forwarding rule '%s'", config_str);

    return -1;

}


BlockAIOCB *laio_submit(BlockDriverState *bs, LinuxAioState *s, int fd,

        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,

        BlockCompletionFunc *cb, void *opaque, int type)

{

    struct qemu_laiocb *laiocb;

    struct iocb *iocbs;

    off_t offset = sector_num * 512;

    laiocb = qemu_aio_get(&laio_aiocb_info, bs, cb, opaque);

    laiocb->nbytes = nb_sectors * 512;

    laiocb->ctx = s;

    laiocb->ret = -EINPROGRESS;

    laiocb->is_read = (type == QEMU_AIO_READ);

    laiocb->qiov = qiov;

    iocbs = &laiocb->iocb;

    switch (type) {

    case QEMU_AIO_WRITE:

        io_prep_pwritev(iocbs, fd, qiov->iov, qiov->niov, offset);

	break;

    case QEMU_AIO_READ:

        io_prep_preadv(iocbs, fd, qiov->iov, qiov->niov, offset);

	break;

    /* Currently Linux kernel does not support other operations */

    default:

        fprintf(stderr, "%s: invalid AIO request type 0x%x.\n",

                        __func__, type);

        goto out_free_aiocb;

    }

    io_set_eventfd(&laiocb->iocb, event_notifier_get_fd(&s->e));

    QSIMPLEQ_INSERT_TAIL(&s->io_q.pending, laiocb, next);

    s->io_q.n++;

    if (!s->io_q.blocked &&

        (!s->io_q.plugged || s->io_q.n >= MAX_QUEUED_IO)) {

        ioq_submit(s);

    }

    return &laiocb->common;

out_free_aiocb:

    qemu_aio_unref(laiocb);

    return NULL;

}


static int X264_frame(AVCodecContext *ctx, uint8_t *buf,

                      int bufsize, void *data)

{

    X264Context *x4 = ctx->priv_data;

    AVFrame *frame = data;

    x264_nal_t *nal;

    int nnal, i;

    x264_picture_t pic_out;

    x4->pic.img.i_csp   = X264_CSP_I420;

    x4->pic.img.i_plane = 3;

    if (frame) {

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

            x4->pic.img.plane[i]    = frame->data[i];

            x4->pic.img.i_stride[i] = frame->linesize[i];

        }

        x4->pic.i_pts  = frame->pts;

        x4->pic.i_type = X264_TYPE_AUTO;

    }

    if (x264_encoder_encode(x4->enc, &nal, &nnal, frame? &x4->pic: NULL, &pic_out) < 0)

        return -1;

    bufsize = encode_nals(ctx, buf, bufsize, nal, nnal, 0);

    if (bufsize < 0)

        return -1;

    /* FIXME: dts */

    x4->out_pic.pts = pic_out.i_pts;

    switch (pic_out.i_type) {

    case X264_TYPE_IDR:

    case X264_TYPE_I:

        x4->out_pic.pict_type = FF_I_TYPE;

        break;

    case X264_TYPE_P:

        x4->out_pic.pict_type = FF_P_TYPE;

        break;

    case X264_TYPE_B:

    case X264_TYPE_BREF:

        x4->out_pic.pict_type = FF_B_TYPE;

        break;

    }

    x4->out_pic.key_frame = pic_out.i_type == X264_TYPE_IDR;

    x4->out_pic.quality   = (pic_out.i_qpplus1 - 1) * FF_QP2LAMBDA;

    return bufsize;

}


static void v9fs_rename(void *opaque)

{

    int32_t fid;

    ssize_t err = 0;

    size_t offset = 7;

    V9fsString name;

    int32_t newdirfid;

    V9fsFidState *fidp;

    V9fsPDU *pdu = opaque;

    V9fsState *s = pdu->s;

    pdu_unmarshal(pdu, offset, "dds", &fid, &newdirfid, &name);

    fidp = get_fid(pdu, fid);

    if (fidp == NULL) {

        err = -ENOENT;

        goto out_nofid;

    }

    BUG_ON(fidp->fid_type != P9_FID_NONE);

    /* if fs driver is not path based, return EOPNOTSUPP */

    if (!(pdu->s->ctx.export_flags & V9FS_PATHNAME_FSCONTEXT)) {

        err = -EOPNOTSUPP;

        goto out;

    }

    v9fs_path_write_lock(s);

    err = v9fs_complete_rename(pdu, fidp, newdirfid, &name);

    v9fs_path_unlock(s);

    if (!err) {

        err = offset;

    }

out:

    put_fid(pdu, fidp);

out_nofid:

    complete_pdu(s, pdu, err);

    v9fs_string_free(&name);

}


static int coroutine_fn cow_co_is_allocated(BlockDriverState *bs,

        int64_t sector_num, int nb_sectors, int *num_same)

{

    int64_t bitnum = sector_num + sizeof(struct cow_header_v2) * 8;

    uint64_t offset = (bitnum / 8) & -BDRV_SECTOR_SIZE;

    bool first = true;

    int changed = 0, same = 0;

    do {

        int ret;

        uint8_t bitmap[BDRV_SECTOR_SIZE];

        bitnum &= BITS_PER_BITMAP_SECTOR - 1;

        int sector_bits = MIN(nb_sectors, BITS_PER_BITMAP_SECTOR - bitnum);

        ret = bdrv_pread(bs->file, offset, &bitmap, sizeof(bitmap));

        if (ret < 0) {

            return ret;

        }

        if (first) {

            changed = cow_test_bit(bitnum, bitmap);

            first = false;

        }

        same += cow_find_streak(bitmap, changed, bitnum, nb_sectors);

        bitnum += sector_bits;

        nb_sectors -= sector_bits;

        offset += BDRV_SECTOR_SIZE;

    } while (nb_sectors);

    *num_same = same;

    return changed;

}


void os_setup_post(void)

{

    int fd = 0;

    if (daemonize) {

        uint8_t status = 0;

        ssize_t len;

    again1:

        len = write(daemon_pipe, &status, 1);

        if (len == -1 && (errno == EINTR)) {

            goto again1;

        }

        if (len != 1) {

            exit(1);

        }

        if (chdir("/")) {

            perror("not able to chdir to /");

            exit(1);

        }

        TFR(fd = qemu_open("/dev/null", O_RDWR));

        if (fd == -1) {

            exit(1);

        }

    }

    change_root();

    change_process_uid();

    if (daemonize) {

        dup2(fd, 0);

        dup2(fd, 1);

        dup2(fd, 2);

        close(fd);

    }

}


void cpu_loop(CPUS390XState *env)

{

    CPUState *cs = CPU(s390_env_get_cpu(env));

    int trapnr, n, sig;

    target_siginfo_t info;

    target_ulong addr;

    while (1) {

        cpu_exec_start(cs);

        trapnr = cpu_s390x_exec(cs);

        cpu_exec_end(cs);

        switch (trapnr) {

        case EXCP_INTERRUPT:

            /* Just indicate that signals should be handled asap.  */

            break;

        case EXCP_SVC:

            n = env->int_svc_code;

            if (!n) {

                /* syscalls > 255 */

                n = env->regs[1];

            }

            env->psw.addr += env->int_svc_ilen;

            env->regs[2] = do_syscall(env, n, env->regs[2], env->regs[3],

                                      env->regs[4], env->regs[5],

                                      env->regs[6], env->regs[7], 0, 0);

            break;

        case EXCP_DEBUG:

            sig = gdb_handlesig(cs, TARGET_SIGTRAP);

            if (sig) {

                n = TARGET_TRAP_BRKPT;

                goto do_signal_pc;

            }

            break;

        case EXCP_PGM:

            n = env->int_pgm_code;

            switch (n) {

            case PGM_OPERATION:

            case PGM_PRIVILEGED:

                sig = TARGET_SIGILL;

                n = TARGET_ILL_ILLOPC;

                goto do_signal_pc;

            case PGM_PROTECTION:

            case PGM_ADDRESSING:

                sig = TARGET_SIGSEGV;

                /* XXX: check env->error_code */

                n = TARGET_SEGV_MAPERR;

                addr = env->__excp_addr;

                goto do_signal;

            case PGM_EXECUTE:

            case PGM_SPECIFICATION:

            case PGM_SPECIAL_OP:

            case PGM_OPERAND:

            do_sigill_opn:

                sig = TARGET_SIGILL;

                n = TARGET_ILL_ILLOPN;

                goto do_signal_pc;

            case PGM_FIXPT_OVERFLOW:

                sig = TARGET_SIGFPE;

                n = TARGET_FPE_INTOVF;

                goto do_signal_pc;

            case PGM_FIXPT_DIVIDE:

                sig = TARGET_SIGFPE;

                n = TARGET_FPE_INTDIV;

                goto do_signal_pc;

            case PGM_DATA:

                n = (env->fpc >> 8) & 0xff;

                if (n == 0xff) {

                    /* compare-and-trap */

                    goto do_sigill_opn;

                } else {

                    /* An IEEE exception, simulated or otherwise.  */

                    if (n & 0x80) {

                        n = TARGET_FPE_FLTINV;

                    } else if (n & 0x40) {

                        n = TARGET_FPE_FLTDIV;

                    } else if (n & 0x20) {

                        n = TARGET_FPE_FLTOVF;

                    } else if (n & 0x10) {

                        n = TARGET_FPE_FLTUND;

                    } else if (n & 0x08) {

                        n = TARGET_FPE_FLTRES;

                    } else {

                        /* ??? Quantum exception; BFP, DFP error.  */

                        goto do_sigill_opn;

                    }

                    sig = TARGET_SIGFPE;

                    goto do_signal_pc;

                }

            default:

                fprintf(stderr, "Unhandled program exception: %#x\n", n);

                cpu_dump_state(cs, stderr, fprintf, 0);

                exit(EXIT_FAILURE);

            }

            break;

        do_signal_pc:

            addr = env->psw.addr;

        do_signal:

            info.si_signo = sig;

            info.si_errno = 0;

            info.si_code = n;

            info._sifields._sigfault._addr = addr;

            queue_signal(env, info.si_signo, &info);

            break;

        default:

            fprintf(stderr, "Unhandled trap: 0x%x\n", trapnr);

            cpu_dump_state(cs, stderr, fprintf, 0);

            exit(EXIT_FAILURE);

        }

        process_pending_signals (env);

    }

}


Object *object_resolve_path_component(Object *parent, const gchar *part)

{

    ObjectProperty *prop = object_property_find(parent, part, NULL);

    if (prop == NULL) {

        return NULL;

    }

    if (object_property_is_link(prop)) {

        LinkProperty *lprop = prop->opaque;

        return *lprop->child;

    } else if (object_property_is_child(prop)) {

        return prop->opaque;

    } else {

        return NULL;

    }

}


static void *virtio_scsi_load_request(QEMUFile *f, SCSIRequest *sreq)

{

    SCSIBus *bus = sreq->bus;

    VirtIOSCSI *s = container_of(bus, VirtIOSCSI, bus);

    VirtIOSCSICommon *vs = VIRTIO_SCSI_COMMON(s);

    VirtIOSCSIReq *req;

    uint32_t n;

    req = g_malloc(sizeof(*req));

    qemu_get_be32s(f, &n);

    assert(n < vs->conf.num_queues);

    qemu_get_buffer(f, (unsigned char *)&req->elem, sizeof(req->elem));

    /* TODO: add a way for SCSIBusInfo's load_request to fail,

     * and fail migration instead of asserting here.

     * When we do, we might be able to re-enable NDEBUG below.

     */

#ifdef NDEBUG

#error building with NDEBUG is not supported

#endif

    assert(req->elem.in_num <= ARRAY_SIZE(req->elem.in_sg));

    assert(req->elem.out_num <= ARRAY_SIZE(req->elem.out_sg));

    virtio_scsi_parse_req(s, vs->cmd_vqs[n], req);

    scsi_req_ref(sreq);

    req->sreq = sreq;

    if (req->sreq->cmd.mode != SCSI_XFER_NONE) {

        int req_mode =

            (req->elem.in_num > 1 ? SCSI_XFER_FROM_DEV : SCSI_XFER_TO_DEV);

        assert(req->sreq->cmd.mode == req_mode);

    }

    return req;

}


static void phys_sections_free(PhysPageMap *map)

{

    while (map->sections_nb > 0) {

        MemoryRegionSection *section = &map->sections[--map->sections_nb];

        phys_section_destroy(section->mr);

    }

    g_free(map->sections);

    g_free(map->nodes);

    g_free(map);

}


static void fill_buffer(ByteIOContext *s)

{

    int len;

    /* no need to do anything if EOF already reached */

    if (s->eof_reached)

        return;

    if(s->update_checksum){

        if(s->buf_end > s->checksum_ptr)

            s->checksum= s->update_checksum(s->checksum, s->checksum_ptr, s->buf_end - s->checksum_ptr);

        s->checksum_ptr= s->buffer;

    }

    len = s->read_packet(s->opaque, s->buffer, s->buffer_size);

    if (len <= 0) {

        /* do not modify buffer if EOF reached so that a seek back can

           be done without rereading data */

        s->eof_reached = 1;

        if(len<0)

            s->error= len;

    } else {

        s->pos += len;

        s->buf_ptr = s->buffer;

        s->buf_end = s->buffer + len;

    }

}


static int adx_encode_frame(AVCodecContext *avctx, uint8_t *frame,

                            int buf_size, void *data)

{

    ADXContext *c          = avctx->priv_data;

    const int16_t *samples = data;

    uint8_t *dst           = frame;

    int ch;

    if (!c->header_parsed) {

        int hdrsize = adx_encode_header(avctx, dst, buf_size);

        dst += hdrsize;

        c->header_parsed = 1;

    }

    for (ch = 0; ch < avctx->channels; ch++) {

        adx_encode(c, dst, samples + ch, &c->prev[ch], avctx->channels);

        dst += BLOCK_SIZE;

    }

    return dst - frame;

}


static int bmp_parse(AVCodecParserContext *s, AVCodecContext *avctx,

                     const uint8_t **poutbuf, int *poutbuf_size,

                     const uint8_t *buf, int buf_size)

{

    BMPParseContext *bpc = s->priv_data;

    uint64_t state = bpc->pc.state64;

    int next = END_NOT_FOUND;

    int i = 0;

    *poutbuf_size = 0;

restart:

    if (bpc->pc.frame_start_found <= 2+4+4) {

        for (; i < buf_size; i++) {

            state = (state << 8) | buf[i];

            if (bpc->pc.frame_start_found == 0) {

                if ((state >> 48) == (('B' << 8) | 'M')) {

                    bpc->fsize = av_bswap32(state >> 16);

                    bpc->pc.frame_start_found = 1;

                }

            } else if (bpc->pc.frame_start_found == 2+4+4) {

//                 unsigned hsize = av_bswap32(state>>32);

                unsigned ihsize = av_bswap32(state);

                if (ihsize < 12 || ihsize > 200) {

                    bpc->pc.frame_start_found = 0;

                    continue;

                }

                bpc->pc.frame_start_found++;

                bpc->remaining_size = bpc->fsize + i - 17;

                if (bpc->pc.index + i > 17) {

                    next = i - 17;

                    state = 0;

                    break;

                } else {

                    bpc->pc.state64 = 0;

                    goto restart;

                }

            } else if (bpc->pc.frame_start_found)

                bpc->pc.frame_start_found++;

        }

        bpc->pc.state64 = state;

    } else {

        if (bpc->remaining_size) {

            i = FFMIN(bpc->remaining_size, buf_size);

            bpc->remaining_size -= i;

            if (bpc->remaining_size)

                goto flush;

            bpc->pc.frame_start_found = 0;

            goto restart;

        }

    }

flush:

    if (ff_combine_frame(&bpc->pc, next, &buf, &buf_size) < 0)

        return buf_size;

    if (next != END_NOT_FOUND && next < 0)

        bpc->pc.frame_start_found = FFMAX(bpc->pc.frame_start_found - i - 1, 0);

    else

        bpc->pc.frame_start_found = 0;

    *poutbuf      = buf;

    *poutbuf_size = buf_size;

    return next;

}


static int avi_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)

{

    AVIContext *avi = s->priv_data;

    AVStream *st;

    int i, index;

    int64_t pos;

    AVIStream *ast;

    if (!avi->index_loaded) {

        /* we only load the index on demand */

        avi_load_index(s);

        avi->index_loaded = 1;

    }

    assert(stream_index>= 0);

    st = s->streams[stream_index];

    ast= st->priv_data;

    index= av_index_search_timestamp(st, timestamp * FFMAX(ast->sample_size, 1), flags);

    if(index<0)

        return -1;

    /* find the position */

    pos = st->index_entries[index].pos;

    timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);

    av_dlog(s, "XX %"PRId64" %d %"PRId64"\n",

            timestamp, index, st->index_entries[index].timestamp);

    if (CONFIG_DV_DEMUXER && avi->dv_demux) {

        /* One and only one real stream for DV in AVI, and it has video  */

        /* offsets. Calling with other stream indexes should have failed */

        /* the av_index_search_timestamp call above.                     */

        assert(stream_index == 0);

        /* Feed the DV video stream version of the timestamp to the */

        /* DV demux so it can synthesize correct timestamps.        */

        ff_dv_offset_reset(avi->dv_demux, timestamp);

        avio_seek(s->pb, pos, SEEK_SET);

        avi->stream_index= -1;

        return 0;

    }

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

        AVStream *st2 = s->streams[i];

        AVIStream *ast2 = st2->priv_data;

        ast2->packet_size=

        ast2->remaining= 0;

        if (ast2->sub_ctx) {

            seek_subtitle(st, st2, timestamp);

            continue;

        }

        if (st2->nb_index_entries <= 0)

            continue;

//        assert(st2->codec->block_align);

        assert((int64_t)st2->time_base.num*ast2->rate == (int64_t)st2->time_base.den*ast2->scale);

        index = av_index_search_timestamp(

                st2,

                av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1),

                flags | AVSEEK_FLAG_BACKWARD);

        if(index<0)

            index=0;

        if(!avi->non_interleaved){

            while(index>0 && st2->index_entries[index].pos > pos)

                index--;

            while(index+1 < st2->nb_index_entries && st2->index_entries[index].pos < pos)

                index++;

        }

        av_dlog(s, "%"PRId64" %d %"PRId64"\n",

                timestamp, index, st2->index_entries[index].timestamp);

        /* extract the current frame number */

        ast2->frame_offset = st2->index_entries[index].timestamp;

    }

    /* do the seek */

    avio_seek(s->pb, pos, SEEK_SET);

    avi->stream_index= -1;

    return 0;

}


static int opt_streamid(const char *opt, const char *arg)

{

    int idx;

    char *p;

    char idx_str[16];

    av_strlcpy(idx_str, arg, sizeof(idx_str));

    p = strchr(idx_str, ':');

    if (!p) {

        fprintf(stderr,

                "Invalid value '%s' for option '%s', required syntax is 'index:value'\n",

                arg, opt);

        ffmpeg_exit(1);

    }

    *p++ = '\0';

    idx = parse_number_or_die(opt, idx_str, OPT_INT, 0, INT_MAX);

    streamid_map = grow_array(streamid_map, sizeof(*streamid_map), &nb_streamid_map, idx+1);

    streamid_map[idx] = parse_number_or_die(opt, p, OPT_INT, 0, INT_MAX);

    return 0;

}


static void avc_luma_midv_qrt_16w_msa(const uint8_t *src, int32_t src_stride,

                                      uint8_t *dst, int32_t dst_stride,

                                      int32_t height, uint8_t vert_offset)

{

    uint32_t multiple8_cnt;

    for (multiple8_cnt = 2; multiple8_cnt--;) {

        avc_luma_midv_qrt_8w_msa(src, src_stride, dst, dst_stride, height,

                                 vert_offset);

        src += 8;

        dst += 8;

    }

}


static void RENAME(yuv2rgb32_1)(SwsContext *c, const uint16_t *buf0,

                                const uint16_t *ubuf0, const uint16_t *ubuf1,

                                const uint16_t *vbuf0, const uint16_t *vbuf1,

                                const uint16_t *abuf0, uint8_t *dest,

                                int dstW, int uvalpha, enum PixelFormat dstFormat,

                                int flags, int y)

{

    const uint16_t *buf1= buf0; //FIXME needed for RGB1/BGR1

    if (uvalpha < 2048) { // note this is not correct (shifts chrominance by 0.5 pixels) but it is a bit faster

        if (CONFIG_SWSCALE_ALPHA && c->alpPixBuf) {

            __asm__ volatile(

                "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"

                "mov        %4, %%"REG_b"               \n\t"

                "push %%"REG_BP"                        \n\t"

                YSCALEYUV2RGB1(%%REGBP, %5)

                YSCALEYUV2RGB1_ALPHA(%%REGBP)

                WRITEBGR32(%%REGb, 8280(%5), %%REGBP, %%mm2, %%mm4, %%mm5, %%mm7, %%mm0, %%mm1, %%mm3, %%mm6)

                "pop %%"REG_BP"                         \n\t"

                "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"

                :: "c" (buf0), "d" (abuf0), "S" (ubuf0), "D" (ubuf1), "m" (dest),

                   "a" (&c->redDither)

            );

        } else {

            __asm__ volatile(

                "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"

                "mov        %4, %%"REG_b"               \n\t"

                "push %%"REG_BP"                        \n\t"

                YSCALEYUV2RGB1(%%REGBP, %5)

                "pcmpeqd %%mm7, %%mm7                   \n\t"

                WRITEBGR32(%%REGb, 8280(%5), %%REGBP, %%mm2, %%mm4, %%mm5, %%mm7, %%mm0, %%mm1, %%mm3, %%mm6)

                "pop %%"REG_BP"                         \n\t"

                "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"

                :: "c" (buf0), "d" (buf1), "S" (ubuf0), "D" (ubuf1), "m" (dest),

                   "a" (&c->redDither)

            );

        }

    } else {

        if (CONFIG_SWSCALE_ALPHA && c->alpPixBuf) {

            __asm__ volatile(

                "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"

                "mov        %4, %%"REG_b"               \n\t"

                "push %%"REG_BP"                        \n\t"

                YSCALEYUV2RGB1b(%%REGBP, %5)

                YSCALEYUV2RGB1_ALPHA(%%REGBP)

                WRITEBGR32(%%REGb, 8280(%5), %%REGBP, %%mm2, %%mm4, %%mm5, %%mm7, %%mm0, %%mm1, %%mm3, %%mm6)

                "pop %%"REG_BP"                         \n\t"

                "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"

                :: "c" (buf0), "d" (abuf0), "S" (ubuf0), "D" (ubuf1), "m" (dest),

                   "a" (&c->redDither)

            );

        } else {

            __asm__ volatile(

                "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"

                "mov        %4, %%"REG_b"               \n\t"

                "push %%"REG_BP"                        \n\t"

                YSCALEYUV2RGB1b(%%REGBP, %5)

                "pcmpeqd %%mm7, %%mm7                   \n\t"

                WRITEBGR32(%%REGb, 8280(%5), %%REGBP, %%mm2, %%mm4, %%mm5, %%mm7, %%mm0, %%mm1, %%mm3, %%mm6)

                "pop %%"REG_BP"                         \n\t"

                "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"

                :: "c" (buf0), "d" (buf1), "S" (ubuf0), "D" (ubuf1), "m" (dest),

                   "a" (&c->redDither)

            );

        }

    }

}