setup_sigcontext(struct target_sigcontext *sc, struct target_fpstate *fpstate,

		 CPUX86State *env, abi_ulong mask, abi_ulong fpstate_addr)

{

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

    int err = 0;

    uint16_t magic;

	/* already locked in setup_frame() */

    __put_user(env->segs[R_GS].selector, (unsigned int *)&sc->gs);

    __put_user(env->segs[R_FS].selector, (unsigned int *)&sc->fs);

    __put_user(env->segs[R_ES].selector, (unsigned int *)&sc->es);

    __put_user(env->segs[R_DS].selector, (unsigned int *)&sc->ds);

    __put_user(env->regs[R_EDI], &sc->edi);

    __put_user(env->regs[R_ESI], &sc->esi);

    __put_user(env->regs[R_EBP], &sc->ebp);

    __put_user(env->regs[R_ESP], &sc->esp);

    __put_user(env->regs[R_EBX], &sc->ebx);

    __put_user(env->regs[R_EDX], &sc->edx);

    __put_user(env->regs[R_ECX], &sc->ecx);

    __put_user(env->regs[R_EAX], &sc->eax);

    __put_user(cs->exception_index, &sc->trapno);

    __put_user(env->error_code, &sc->err);

    __put_user(env->eip, &sc->eip);

    __put_user(env->segs[R_CS].selector, (unsigned int *)&sc->cs);

    __put_user(env->eflags, &sc->eflags);

    __put_user(env->regs[R_ESP], &sc->esp_at_signal);

    __put_user(env->segs[R_SS].selector, (unsigned int *)&sc->ss);

        cpu_x86_fsave(env, fpstate_addr, 1);

        fpstate->status = fpstate->sw;

        magic = 0xffff;

    __put_user(magic, &fpstate->magic);

    __put_user(fpstate_addr, &sc->fpstate);

	/* non-iBCS2 extensions.. */

    __put_user(mask, &sc->oldmask);

    __put_user(env->cr[2], &sc->cr2);

	return err;

}


static void coroutine_fn qed_aio_complete(QEDAIOCB *acb)

{

    BDRVQEDState *s = acb_to_s(acb);

    /* Free resources */

    qemu_iovec_destroy(&acb->cur_qiov);

    qed_unref_l2_cache_entry(acb->request.l2_table);

    /* Free the buffer we may have allocated for zero writes */

    if (acb->flags & QED_AIOCB_ZERO) {

        qemu_vfree(acb->qiov->iov[0].iov_base);

        acb->qiov->iov[0].iov_base = NULL;

    }

    /* Start next allocating write request waiting behind this one.  Note that

     * requests enqueue themselves when they first hit an unallocated cluster

     * but they wait until the entire request is finished before waking up the

     * next request in the queue.  This ensures that we don't cycle through

     * requests multiple times but rather finish one at a time completely.

     */

    if (acb == s->allocating_acb) {

        s->allocating_acb = NULL;

        if (!qemu_co_queue_empty(&s->allocating_write_reqs)) {

            qemu_co_enter_next(&s->allocating_write_reqs);

        } else if (s->header.features & QED_F_NEED_CHECK) {

            qed_start_need_check_timer(s);

        }

    }

}


static bool vtd_do_iommu_translate(VTDAddressSpace *vtd_as, PCIBus *bus,

                                   uint8_t devfn, hwaddr addr, bool is_write,

                                   IOMMUTLBEntry *entry)

{

    IntelIOMMUState *s = vtd_as->iommu_state;

    VTDContextEntry ce;

    uint8_t bus_num = pci_bus_num(bus);

    VTDContextCacheEntry *cc_entry = &vtd_as->context_cache_entry;

    uint64_t slpte, page_mask;

    uint32_t level;

    uint16_t source_id = vtd_make_source_id(bus_num, devfn);

    int ret_fr;

    bool is_fpd_set = false;

    bool reads = true;

    bool writes = true;

    uint8_t access_flags;

    VTDIOTLBEntry *iotlb_entry;

    /*

     * We have standalone memory region for interrupt addresses, we

     * should never receive translation requests in this region.

     */

    assert(!vtd_is_interrupt_addr(addr));

    /* Try to fetch slpte form IOTLB */

    iotlb_entry = vtd_lookup_iotlb(s, source_id, addr);

    if (iotlb_entry) {

        trace_vtd_iotlb_page_hit(source_id, addr, iotlb_entry->slpte,

                                 iotlb_entry->domain_id);

        slpte = iotlb_entry->slpte;

        access_flags = iotlb_entry->access_flags;

        page_mask = iotlb_entry->mask;

        goto out;

    }

    /* Try to fetch context-entry from cache first */

    if (cc_entry->context_cache_gen == s->context_cache_gen) {

        trace_vtd_iotlb_cc_hit(bus_num, devfn, cc_entry->context_entry.hi,

                               cc_entry->context_entry.lo,

                               cc_entry->context_cache_gen);

        ce = cc_entry->context_entry;

        is_fpd_set = ce.lo & VTD_CONTEXT_ENTRY_FPD;

    } else {

        ret_fr = vtd_dev_to_context_entry(s, bus_num, devfn, &ce);

        is_fpd_set = ce.lo & VTD_CONTEXT_ENTRY_FPD;

        if (ret_fr) {

            ret_fr = -ret_fr;

            if (is_fpd_set && vtd_is_qualified_fault(ret_fr)) {

                trace_vtd_fault_disabled();

            } else {

                vtd_report_dmar_fault(s, source_id, addr, ret_fr, is_write);

            }

            goto error;

        }

        /* Update context-cache */

        trace_vtd_iotlb_cc_update(bus_num, devfn, ce.hi, ce.lo,

                                  cc_entry->context_cache_gen,

                                  s->context_cache_gen);

        cc_entry->context_entry = ce;

        cc_entry->context_cache_gen = s->context_cache_gen;

    }

    /*

     * We don't need to translate for pass-through context entries.

     * Also, let's ignore IOTLB caching as well for PT devices.

     */

    if (vtd_ce_get_type(&ce) == VTD_CONTEXT_TT_PASS_THROUGH) {

        entry->iova = addr & VTD_PAGE_MASK_4K;

        entry->translated_addr = entry->iova;

        entry->addr_mask = ~VTD_PAGE_MASK_4K;

        entry->perm = IOMMU_RW;

        trace_vtd_translate_pt(source_id, entry->iova);

        /*

         * When this happens, it means firstly caching-mode is not

         * enabled, and this is the first passthrough translation for

         * the device. Let's enable the fast path for passthrough.

         *

         * When passthrough is disabled again for the device, we can

         * capture it via the context entry invalidation, then the

         * IOMMU region can be swapped back.

         */

        vtd_pt_enable_fast_path(s, source_id);

        return true;

    }

    ret_fr = vtd_iova_to_slpte(&ce, addr, is_write, &slpte, &level,

                               &reads, &writes);

    if (ret_fr) {

        ret_fr = -ret_fr;

        if (is_fpd_set && vtd_is_qualified_fault(ret_fr)) {

            trace_vtd_fault_disabled();

        } else {

            vtd_report_dmar_fault(s, source_id, addr, ret_fr, is_write);

        }

        goto error;

    }

    page_mask = vtd_slpt_level_page_mask(level);

    access_flags = IOMMU_ACCESS_FLAG(reads, writes);

    vtd_update_iotlb(s, source_id, VTD_CONTEXT_ENTRY_DID(ce.hi), addr, slpte,

                     access_flags, level);

out:

    entry->iova = addr & page_mask;

    entry->translated_addr = vtd_get_slpte_addr(slpte) & page_mask;

    entry->addr_mask = ~page_mask;

    entry->perm = access_flags;

    return true;

error:

    entry->iova = 0;

    entry->translated_addr = 0;

    entry->addr_mask = 0;

    entry->perm = IOMMU_NONE;

    return false;

}


int load_multiboot(void *fw_cfg,

                   FILE *f,

                   const char *kernel_filename,

                   const char *initrd_filename,

                   const char *kernel_cmdline,

                   int kernel_file_size,

                   uint8_t *header)

{

    int i, is_multiboot = 0;

    uint32_t flags = 0;

    uint32_t mh_entry_addr;

    uint32_t mh_load_addr;

    uint32_t mb_kernel_size;

    MultibootState mbs;

    uint8_t bootinfo[MBI_SIZE];

    uint8_t *mb_bootinfo_data;

    /* Ok, let's see if it is a multiboot image.

       The header is 12x32bit long, so the latest entry may be 8192 - 48. */

    for (i = 0; i < (8192 - 48); i += 4) {

        if (ldl_p(header+i) == 0x1BADB002) {

            uint32_t checksum = ldl_p(header+i+8);

            flags = ldl_p(header+i+4);

            checksum += flags;

            checksum += (uint32_t)0x1BADB002;

            if (!checksum) {

                is_multiboot = 1;

                break;

            }

        }

    }

    if (!is_multiboot)

        return 0; /* no multiboot */

    mb_debug("qemu: I believe we found a multiboot image!\n");

    memset(bootinfo, 0, sizeof(bootinfo));

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

    if (flags & 0x00000004) { /* MULTIBOOT_HEADER_HAS_VBE */

        fprintf(stderr, "qemu: multiboot knows VBE. we don't.\n");

    }

    if (!(flags & 0x00010000)) { /* MULTIBOOT_HEADER_HAS_ADDR */

        uint64_t elf_entry;

        uint64_t elf_low, elf_high;

        int kernel_size;

        fclose(f);

        if (((struct elf64_hdr*)header)->e_machine == EM_X86_64) {

            fprintf(stderr, "Cannot load x86-64 image, give a 32bit one.\n");

            exit(1);

        }

        kernel_size = load_elf(kernel_filename, NULL, NULL, &elf_entry,

                               &elf_low, &elf_high, 0, ELF_MACHINE, 0);

        if (kernel_size < 0) {

            fprintf(stderr, "Error while loading elf kernel\n");

            exit(1);

        }

        mh_load_addr = elf_low;

        mb_kernel_size = elf_high - elf_low;

        mh_entry_addr = elf_entry;

        mbs.mb_buf = g_malloc(mb_kernel_size);

        if (rom_copy(mbs.mb_buf, mh_load_addr, mb_kernel_size) != mb_kernel_size) {

            fprintf(stderr, "Error while fetching elf kernel from rom\n");

            exit(1);

        }

        mb_debug("qemu: loading multiboot-elf kernel (%#x bytes) with entry %#zx\n",

                  mb_kernel_size, (size_t)mh_entry_addr);

    } else {

        /* Valid if mh_flags sets MULTIBOOT_HEADER_HAS_ADDR. */

        uint32_t mh_header_addr = ldl_p(header+i+12);

        uint32_t mh_load_end_addr = ldl_p(header+i+20);

        uint32_t mh_bss_end_addr = ldl_p(header+i+24);

        mh_load_addr = ldl_p(header+i+16);

        uint32_t mb_kernel_text_offset = i - (mh_header_addr - mh_load_addr);

        uint32_t mb_load_size = 0;

        mh_entry_addr = ldl_p(header+i+28);

        if (mh_load_end_addr) {

            mb_kernel_size = mh_bss_end_addr - mh_load_addr;

            mb_load_size = mh_load_end_addr - mh_load_addr;

        } else {

            mb_kernel_size = kernel_file_size - mb_kernel_text_offset;

            mb_load_size = mb_kernel_size;

        }

        /* Valid if mh_flags sets MULTIBOOT_HEADER_HAS_VBE.

        uint32_t mh_mode_type = ldl_p(header+i+32);

        uint32_t mh_width = ldl_p(header+i+36);

        uint32_t mh_height = ldl_p(header+i+40);

        uint32_t mh_depth = ldl_p(header+i+44); */

        mb_debug("multiboot: mh_header_addr = %#x\n", mh_header_addr);

        mb_debug("multiboot: mh_load_addr = %#x\n", mh_load_addr);

        mb_debug("multiboot: mh_load_end_addr = %#x\n", mh_load_end_addr);

        mb_debug("multiboot: mh_bss_end_addr = %#x\n", mh_bss_end_addr);

        mb_debug("qemu: loading multiboot kernel (%#x bytes) at %#x\n",

                 mb_load_size, mh_load_addr);

        mbs.mb_buf = g_malloc(mb_kernel_size);

        fseek(f, mb_kernel_text_offset, SEEK_SET);

        if (fread(mbs.mb_buf, 1, mb_load_size, f) != mb_load_size) {

            fprintf(stderr, "fread() failed\n");

            exit(1);

        }

        memset(mbs.mb_buf + mb_load_size, 0, mb_kernel_size - mb_load_size);

        fclose(f);

    }

    mbs.mb_buf_phys = mh_load_addr;

    mbs.mb_buf_size = TARGET_PAGE_ALIGN(mb_kernel_size);

    mbs.offset_mbinfo = mbs.mb_buf_size;

    /* Calculate space for cmdlines and mb_mods */

    mbs.mb_buf_size += strlen(kernel_filename) + 1;

    mbs.mb_buf_size += strlen(kernel_cmdline) + 1;

    if (initrd_filename) {

        const char *r = initrd_filename;

        mbs.mb_buf_size += strlen(r) + 1;

        mbs.mb_mods_avail = 1;

        while (*(r = get_opt_value(NULL, 0, r))) {

           mbs.mb_mods_avail++;

           r++;

        }

        mbs.mb_buf_size += MB_MOD_SIZE * mbs.mb_mods_avail;

    }

    mbs.mb_buf_size = TARGET_PAGE_ALIGN(mbs.mb_buf_size);

    /* enlarge mb_buf to hold cmdlines and mb-info structs */

    mbs.mb_buf          = g_realloc(mbs.mb_buf, mbs.mb_buf_size);

    mbs.offset_cmdlines = mbs.offset_mbinfo + mbs.mb_mods_avail * MB_MOD_SIZE;

    if (initrd_filename) {

        char *next_initrd, not_last;

        mbs.offset_mods = mbs.mb_buf_size;

        do {

            char *next_space;

            int mb_mod_length;

            uint32_t offs = mbs.mb_buf_size;

            next_initrd = (char *)get_opt_value(NULL, 0, initrd_filename);

            not_last = *next_initrd;

            *next_initrd = '\0';

            /* if a space comes after the module filename, treat everything

               after that as parameters */

            target_phys_addr_t c = mb_add_cmdline(&mbs, initrd_filename);

            if ((next_space = strchr(initrd_filename, ' ')))

                *next_space = '\0';

            mb_debug("multiboot loading module: %s\n", initrd_filename);

            mb_mod_length = get_image_size(initrd_filename);

            if (mb_mod_length < 0) {

                fprintf(stderr, "Failed to open file '%s'\n", initrd_filename);

                exit(1);

            }

            mbs.mb_buf_size = TARGET_PAGE_ALIGN(mb_mod_length + mbs.mb_buf_size);

            mbs.mb_buf = g_realloc(mbs.mb_buf, mbs.mb_buf_size);

            load_image(initrd_filename, (unsigned char *)mbs.mb_buf + offs);

            mb_add_mod(&mbs, mbs.mb_buf_phys + offs,

                       mbs.mb_buf_phys + offs + mb_mod_length, c);

            mb_debug("mod_start: %p\nmod_end:   %p\n  cmdline: "TARGET_FMT_plx"\n",

                     (char *)mbs.mb_buf + offs,

                     (char *)mbs.mb_buf + offs + mb_mod_length, c);

            initrd_filename = next_initrd+1;

        } while (not_last);

    }

    /* Commandline support */

    char kcmdline[strlen(kernel_filename) + strlen(kernel_cmdline) + 2];

    snprintf(kcmdline, sizeof(kcmdline), "%s %s",

             kernel_filename, kernel_cmdline);

    stl_p(bootinfo + MBI_CMDLINE, mb_add_cmdline(&mbs, kcmdline));

    stl_p(bootinfo + MBI_MODS_ADDR,  mbs.mb_buf_phys + mbs.offset_mbinfo);

    stl_p(bootinfo + MBI_MODS_COUNT, mbs.mb_mods_count); /* mods_count */

    /* the kernel is where we want it to be now */

    stl_p(bootinfo + MBI_FLAGS, MULTIBOOT_FLAGS_MEMORY

                                | MULTIBOOT_FLAGS_BOOT_DEVICE

                                | MULTIBOOT_FLAGS_CMDLINE

                                | MULTIBOOT_FLAGS_MODULES

                                | MULTIBOOT_FLAGS_MMAP);

    stl_p(bootinfo + MBI_MEM_LOWER,   640);

    stl_p(bootinfo + MBI_MEM_UPPER,   (ram_size / 1024) - 1024);

    stl_p(bootinfo + MBI_BOOT_DEVICE, 0x8000ffff); /* XXX: use the -boot switch? */

    stl_p(bootinfo + MBI_MMAP_ADDR,   ADDR_E820_MAP);

    mb_debug("multiboot: mh_entry_addr = %#x\n", mh_entry_addr);

    mb_debug("           mb_buf_phys   = "TARGET_FMT_plx"\n", mbs.mb_buf_phys);

    mb_debug("           mod_start     = "TARGET_FMT_plx"\n", mbs.mb_buf_phys + mbs.offset_mods);

    mb_debug("           mb_mods_count = %d\n", mbs.mb_mods_count);

    /* save bootinfo off the stack */

    mb_bootinfo_data = g_malloc(sizeof(bootinfo));

    memcpy(mb_bootinfo_data, bootinfo, sizeof(bootinfo));

    /* Pass variables to option rom */

    fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_ENTRY, mh_entry_addr);

    fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_ADDR, mh_load_addr);

    fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_SIZE, mbs.mb_buf_size);

    fw_cfg_add_bytes(fw_cfg, FW_CFG_KERNEL_DATA,

                     mbs.mb_buf, mbs.mb_buf_size);

    fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_ADDR, ADDR_MBI);

    fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_SIZE, sizeof(bootinfo));

    fw_cfg_add_bytes(fw_cfg, FW_CFG_INITRD_DATA, mb_bootinfo_data,

                     sizeof(bootinfo));

    option_rom[nb_option_roms].name = "multiboot.bin";

    option_rom[nb_option_roms].bootindex = 0;

    nb_option_roms++;

    return 1; /* yes, we are multiboot */

}


static void FUNC(hevc_h_loop_filter_luma)(uint8_t *pix, ptrdiff_t stride,

                                          int *beta, int *tc, uint8_t *no_p,

                                          uint8_t *no_q)

{

    FUNC(hevc_loop_filter_luma)(pix, stride, sizeof(pixel),

                                beta, tc, no_p, no_q);

}


static void tcg_out_brcond(TCGContext *s, TCGMemOp ext, TCGCond c, TCGArg a,

                           TCGArg b, bool b_const, TCGLabel *l)

{

    intptr_t offset;

    bool need_cmp;

    if (b_const && b == 0 && (c == TCG_COND_EQ || c == TCG_COND_NE)) {

        need_cmp = false;

    } else {

        need_cmp = true;

        tcg_out_cmp(s, ext, a, b, b_const);

    }

    if (!l->has_value) {

        tcg_out_reloc(s, s->code_ptr, R_AARCH64_CONDBR19, l, 0);

        offset = tcg_in32(s) >> 5;

    } else {

        offset = l->u.value_ptr - s->code_ptr;

        assert(offset == sextract64(offset, 0, 19));

    }

    if (need_cmp) {

        tcg_out_insn(s, 3202, B_C, c, offset);

    } else if (c == TCG_COND_EQ) {

        tcg_out_insn(s, 3201, CBZ, ext, a, offset);

    } else {

        tcg_out_insn(s, 3201, CBNZ, ext, a, offset);

    }

}


static int nbd_negotiate_options(NBDClient *client, Error **errp)

{

    uint32_t flags;

    bool fixedNewstyle = false;

    /* Client sends:

        [ 0 ..   3]   client flags

        [ 0 ..   7]   NBD_OPTS_MAGIC

        [ 8 ..  11]   NBD option

        [12 ..  15]   Data length

        ...           Rest of request

        [ 0 ..   7]   NBD_OPTS_MAGIC

        [ 8 ..  11]   Second NBD option

        [12 ..  15]   Data length

        ...           Rest of request

    */

    if (nbd_read(client->ioc, &flags, sizeof(flags), errp) < 0) {

        error_prepend(errp, "read failed: ");

        return -EIO;

    }

    trace_nbd_negotiate_options_flags();

    be32_to_cpus(&flags);

    if (flags & NBD_FLAG_C_FIXED_NEWSTYLE) {

        trace_nbd_negotiate_options_newstyle();

        fixedNewstyle = true;

        flags &= ~NBD_FLAG_C_FIXED_NEWSTYLE;

    }

    if (flags & NBD_FLAG_C_NO_ZEROES) {

        trace_nbd_negotiate_options_no_zeroes();

        client->no_zeroes = true;

        flags &= ~NBD_FLAG_C_NO_ZEROES;

    }

    if (flags != 0) {

        error_setg(errp, "Unknown client flags 0x%" PRIx32 " received", flags);

        return -EIO;

    }

    while (1) {

        int ret;

        uint32_t option, length;

        uint64_t magic;

        if (nbd_read(client->ioc, &magic, sizeof(magic), errp) < 0) {

            error_prepend(errp, "read failed: ");

            return -EINVAL;

        }

        magic = be64_to_cpu(magic);

        trace_nbd_negotiate_options_check_magic(magic);

        if (magic != NBD_OPTS_MAGIC) {

            error_setg(errp, "Bad magic received");

            return -EINVAL;

        }

        if (nbd_read(client->ioc, &option,

                     sizeof(option), errp) < 0) {

            error_prepend(errp, "read failed: ");

            return -EINVAL;

        }

        option = be32_to_cpu(option);

        if (nbd_read(client->ioc, &length, sizeof(length), errp) < 0) {

            error_prepend(errp, "read failed: ");

            return -EINVAL;

        }

        length = be32_to_cpu(length);

        trace_nbd_negotiate_options_check_option(option);

        if (client->tlscreds &&

            client->ioc == (QIOChannel *)client->sioc) {

            QIOChannel *tioc;

            if (!fixedNewstyle) {

                error_setg(errp, "Unsupported option 0x%" PRIx32, option);

                return -EINVAL;

            }

            switch (option) {

            case NBD_OPT_STARTTLS:

                tioc = nbd_negotiate_handle_starttls(client, length, errp);

                if (!tioc) {

                    return -EIO;

                }

                object_unref(OBJECT(client->ioc));

                client->ioc = QIO_CHANNEL(tioc);

                break;

            case NBD_OPT_EXPORT_NAME:

                /* No way to return an error to client, so drop connection */

                error_setg(errp, "Option 0x%x not permitted before TLS",

                           option);

                return -EINVAL;

            default:

                if (nbd_drop(client->ioc, length, errp) < 0) {

                    return -EIO;

                }

                ret = nbd_negotiate_send_rep_err(client->ioc,

                                                 NBD_REP_ERR_TLS_REQD,

                                                 option, errp,

                                                 "Option 0x%" PRIx32

                                                 "not permitted before TLS",

                                                 option);

                if (ret < 0) {

                    return ret;

                }

                /* Let the client keep trying, unless they asked to

                 * quit. In this mode, we've already sent an error, so

                 * we can't ack the abort.  */

                if (option == NBD_OPT_ABORT) {

                    return 1;

                }

                break;

            }

        } else if (fixedNewstyle) {

            switch (option) {

            case NBD_OPT_LIST:

                ret = nbd_negotiate_handle_list(client, length, errp);

                if (ret < 0) {

                    return ret;

                }

                break;

            case NBD_OPT_ABORT:

                /* NBD spec says we must try to reply before

                 * disconnecting, but that we must also tolerate

                 * guests that don't wait for our reply. */

                nbd_negotiate_send_rep(client->ioc, NBD_REP_ACK, option, NULL);

                return 1;

            case NBD_OPT_EXPORT_NAME:

                return nbd_negotiate_handle_export_name(client, length, errp);

            case NBD_OPT_STARTTLS:

                if (nbd_drop(client->ioc, length, errp) < 0) {

                    return -EIO;

                }

                if (client->tlscreds) {

                    ret = nbd_negotiate_send_rep_err(client->ioc,

                                                     NBD_REP_ERR_INVALID,

                                                     option, errp,

                                                     "TLS already enabled");

                } else {

                    ret = nbd_negotiate_send_rep_err(client->ioc,

                                                     NBD_REP_ERR_POLICY,

                                                     option, errp,

                                                     "TLS not configured");

                }

                if (ret < 0) {

                    return ret;

                }

                break;

            default:

                if (nbd_drop(client->ioc, length, errp) < 0) {

                    return -EIO;

                }

                ret = nbd_negotiate_send_rep_err(client->ioc,

                                                 NBD_REP_ERR_UNSUP,

                                                 option, errp,

                                                 "Unsupported option 0x%"

                                                 PRIx32,

                                                 option);

                if (ret < 0) {

                    return ret;

                }

                break;

            }

        } else {

            /*

             * If broken new-style we should drop the connection

             * for anything except NBD_OPT_EXPORT_NAME

             */

            switch (option) {

            case NBD_OPT_EXPORT_NAME:

                return nbd_negotiate_handle_export_name(client, length, errp);

            default:

                error_setg(errp, "Unsupported option 0x%" PRIx32, option);

                return -EINVAL;

            }

        }

    }

}


static void pl181_fifo_run(pl181_state *s)

{

    uint32_t bits;

    uint32_t value;

    int n;

    int is_read;

    is_read = (s->datactrl & PL181_DATA_DIRECTION) != 0;

    if (s->datacnt != 0 && (!is_read || sd_data_ready(s->card))

            && !s->linux_hack) {

        if (is_read) {

            n = 0;

            value = 0;

            while (s->datacnt && s->fifo_len < PL181_FIFO_LEN) {

                value |= (uint32_t)sd_read_data(s->card) << (n * 8);

                s->datacnt--;

                n++;

                if (n == 4) {

                    pl181_fifo_push(s, value);

                    n = 0;

                    value = 0;

                }

            }

            if (n != 0) {

                pl181_fifo_push(s, value);

            }

        } else { /* write */

            n = 0;

            while (s->datacnt > 0 && (s->fifo_len > 0 || n > 0)) {

                if (n == 0) {

                    value = pl181_fifo_pop(s);

                    n = 4;

                }

                n--;

                s->datacnt--;

                sd_write_data(s->card, value & 0xff);

                value >>= 8;

            }

        }

    }

    s->status &= ~(PL181_STATUS_RX_FIFO | PL181_STATUS_TX_FIFO);

    if (s->datacnt == 0) {

        s->status |= PL181_STATUS_DATAEND;

        /* HACK: */

        s->status |= PL181_STATUS_DATABLOCKEND;

        DPRINTF("Transfer Complete\n");

    }

    if (s->datacnt == 0 && s->fifo_len == 0) {

        s->datactrl &= ~PL181_DATA_ENABLE;

        DPRINTF("Data engine idle\n");

    } else {

        /* Update FIFO bits.  */

        bits = PL181_STATUS_TXACTIVE | PL181_STATUS_RXACTIVE;

        if (s->fifo_len == 0) {

            bits |= PL181_STATUS_TXFIFOEMPTY;

            bits |= PL181_STATUS_RXFIFOEMPTY;

        } else {

            bits |= PL181_STATUS_TXDATAAVLBL;

            bits |= PL181_STATUS_RXDATAAVLBL;

        }

        if (s->fifo_len == 16) {

            bits |= PL181_STATUS_TXFIFOFULL;

            bits |= PL181_STATUS_RXFIFOFULL;

        }

        if (s->fifo_len <= 8) {

            bits |= PL181_STATUS_TXFIFOHALFEMPTY;

        }

        if (s->fifo_len >= 8) {

            bits |= PL181_STATUS_RXFIFOHALFFULL;

        }

        if (s->datactrl & PL181_DATA_DIRECTION) {

            bits &= PL181_STATUS_RX_FIFO;

        } else {

            bits &= PL181_STATUS_TX_FIFO;

        }

        s->status |= bits;

    }

}


static int flv_read_metabody(AVFormatContext *s, int64_t next_pos)

{

    AMFDataType type;

    AVStream *stream, *astream, *vstream;

    AVIOContext *ioc;

    int i;

    // only needs to hold the string "onMetaData".

    // Anything longer is something we don't want.

    char buffer[11];

    astream = NULL;

    vstream = NULL;

    ioc     = s->pb;

    // first object needs to be "onMetaData" string

    type = avio_r8(ioc);

    if (type != AMF_DATA_TYPE_STRING ||

        amf_get_string(ioc, buffer, sizeof(buffer)) < 0)

        return -1;

    if (!strcmp(buffer, "onTextData"))

        return 1;

    if (strcmp(buffer, "onMetaData"))

        return -1;

    // find the streams now so that amf_parse_object doesn't need to do

    // the lookup every time it is called.

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

        stream = s->streams[i];

        if (stream->codec->codec_type == AVMEDIA_TYPE_AUDIO)

            astream = stream;

        else if (stream->codec->codec_type == AVMEDIA_TYPE_VIDEO)

            vstream = stream;

    }

    // parse the second object (we want a mixed array)

    if (amf_parse_object(s, astream, vstream, buffer, next_pos, 0) < 0)

        return -1;

    return 0;

}


static void mptsas_scsi_init(PCIDevice *dev, Error **errp)

{

    DeviceState *d = DEVICE(dev);

    MPTSASState *s = MPT_SAS(dev);

    Error *err = NULL;

    int ret;

    dev->config[PCI_LATENCY_TIMER] = 0;

    dev->config[PCI_INTERRUPT_PIN] = 0x01;

    if (s->msi != ON_OFF_AUTO_OFF) {

        ret = msi_init(dev, 0, 1, true, false, &err);

        /* Any error other than -ENOTSUP(board's MSI support is broken)

         * is a programming error */

        assert(!ret || ret == -ENOTSUP);

        if (ret && s->msi == ON_OFF_AUTO_ON) {

            /* Can't satisfy user's explicit msi=on request, fail */

            error_append_hint(&err, "You have to use msi=auto (default) or "

                    "msi=off with this machine type.\n");

            error_propagate(errp, err);

            s->msi_in_use = false;

            return;

        } else if (ret) {

            /* With msi=auto, we fall back to MSI off silently */

            error_free(err);

            s->msi_in_use = false;

        } else {

            s->msi_in_use = true;

        }

    }

    memory_region_init_io(&s->mmio_io, OBJECT(s), &mptsas_mmio_ops, s,

                          "mptsas-mmio", 0x4000);

    memory_region_init_io(&s->port_io, OBJECT(s), &mptsas_port_ops, s,

                          "mptsas-io", 256);

    memory_region_init_io(&s->diag_io, OBJECT(s), &mptsas_diag_ops, s,

                          "mptsas-diag", 0x10000);

    pci_register_bar(dev, 0, PCI_BASE_ADDRESS_SPACE_IO, &s->port_io);

    pci_register_bar(dev, 1, PCI_BASE_ADDRESS_SPACE_MEMORY |

                                 PCI_BASE_ADDRESS_MEM_TYPE_32, &s->mmio_io);

    pci_register_bar(dev, 2, PCI_BASE_ADDRESS_SPACE_MEMORY |

                                 PCI_BASE_ADDRESS_MEM_TYPE_32, &s->diag_io);

    if (!s->sas_addr) {

        s->sas_addr = ((NAA_LOCALLY_ASSIGNED_ID << 24) |

                       IEEE_COMPANY_LOCALLY_ASSIGNED) << 36;

        s->sas_addr |= (pci_bus_num(dev->bus) << 16);

        s->sas_addr |= (PCI_SLOT(dev->devfn) << 8);

        s->sas_addr |= PCI_FUNC(dev->devfn);

    }

    s->max_devices = MPTSAS_NUM_PORTS;

    s->request_bh = qemu_bh_new(mptsas_fetch_requests, s);

    QTAILQ_INIT(&s->pending);

    scsi_bus_new(&s->bus, sizeof(s->bus), &dev->qdev, &mptsas_scsi_info, NULL);

    if (!d->hotplugged) {

        scsi_bus_legacy_handle_cmdline(&s->bus, errp);

    }

}


static void kvm_arm_gic_realize(DeviceState *dev, Error **errp)

{

    int i;

    GICState *s = KVM_ARM_GIC(dev);

    SysBusDevice *sbd = SYS_BUS_DEVICE(dev);

    KVMARMGICClass *kgc = KVM_ARM_GIC_GET_CLASS(s);

    kgc->parent_realize(dev, errp);

    if (error_is_set(errp)) {

        return;

    }

    i = s->num_irq - GIC_INTERNAL;

    /* For the GIC, also expose incoming GPIO lines for PPIs for each CPU.

     * GPIO array layout is thus:

     *  [0..N-1] SPIs

     *  [N..N+31] PPIs for CPU 0

     *  [N+32..N+63] PPIs for CPU 1

     *   ...

     */

    i += (GIC_INTERNAL * s->num_cpu);

    qdev_init_gpio_in(dev, kvm_arm_gic_set_irq, i);

    /* We never use our outbound IRQ lines but provide them so that

     * we maintain the same interface as the non-KVM GIC.

     */

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

        sysbus_init_irq(sbd, &s->parent_irq[i]);

    }

    /* Distributor */

    memory_region_init_reservation(&s->iomem, OBJECT(s),

                                   "kvm-gic_dist", 0x1000);

    sysbus_init_mmio(sbd, &s->iomem);

    kvm_arm_register_device(&s->iomem,

                            (KVM_ARM_DEVICE_VGIC_V2 << KVM_ARM_DEVICE_ID_SHIFT)

                            | KVM_VGIC_V2_ADDR_TYPE_DIST);

    /* CPU interface for current core. Unlike arm_gic, we don't

     * provide the "interface for core #N" memory regions, because

     * cores with a VGIC don't have those.

     */

    memory_region_init_reservation(&s->cpuiomem[0], OBJECT(s),

                                   "kvm-gic_cpu", 0x1000);

    sysbus_init_mmio(sbd, &s->cpuiomem[0]);

    kvm_arm_register_device(&s->cpuiomem[0],

                            (KVM_ARM_DEVICE_VGIC_V2 << KVM_ARM_DEVICE_ID_SHIFT)

                            | KVM_VGIC_V2_ADDR_TYPE_CPU);

}


static int write_fragments(struct Tracks *tracks, int start_index,

                           AVIOContext *in)

{

    char dirname[100], filename[500];

    int i, j;

    for (i = start_index; i < tracks->nb_tracks; i++) {

        struct Track *track = tracks->tracks[i];

        const char *type    = track->is_video ? "video" : "audio";

        snprintf(dirname, sizeof(dirname), "QualityLevels(%d)", track->bitrate);

        mkdir(dirname, 0777);

        for (j = 0; j < track->chunks; j++) {

            snprintf(filename, sizeof(filename), "%s/Fragments(%s=%"PRId64")",

                     dirname, type, track->offsets[j].time);

            avio_seek(in, track->offsets[j].offset, SEEK_SET);

            write_fragment(filename, in);

        }

    }

    return 0;

}


char *qemu_find_file(int type, const char *name)

{

    int len;

    const char *subdir;

    char *buf;

    /* If name contains path separators then try it as a straight path.  */

    if ((strchr(name, '/') || strchr(name, '\\'))

        && access(name, R_OK) == 0) {

        return g_strdup(name);

    }

    switch (type) {

    case QEMU_FILE_TYPE_BIOS:

        subdir = "";

        break;

    case QEMU_FILE_TYPE_KEYMAP:

        subdir = "keymaps/";

        break;

    default:

        abort();

    }

    len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;

    buf = g_malloc0(len);

    snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);

    if (access(buf, R_OK)) {

        g_free(buf);

        return NULL;

    }

    return buf;

}


static uint64_t elcr_ioport_read(void *opaque, target_phys_addr_t addr,

                                 unsigned size)

{

    PICCommonState *s = opaque;

    return s->elcr;

}


static int inc_refcounts(BlockDriverState *bs,

                         BdrvCheckResult *res,

                         uint16_t *refcount_table,

                         int64_t refcount_table_size,

                         int64_t offset, int64_t size)

{

    BDRVQcowState *s = bs->opaque;

    uint64_t start, last, cluster_offset, k;

    if (size <= 0) {

        return 0;

    }

    start = start_of_cluster(s, offset);

    last = start_of_cluster(s, offset + size - 1);

    for(cluster_offset = start; cluster_offset <= last;

        cluster_offset += s->cluster_size) {

        k = cluster_offset >> s->cluster_bits;

        if (k >= refcount_table_size) {

            fprintf(stderr, "Warning: cluster offset=0x%" PRIx64 " is after "

                "the end of the image file, can't properly check refcounts.\n",

                cluster_offset);

            res->check_errors++;

        } else {

            if (++refcount_table[k] == 0) {

                fprintf(stderr, "ERROR: overflow cluster offset=0x%" PRIx64

                    "\n", cluster_offset);

                res->corruptions++;

            }

        }

    }

    return 0;

}


static int nbd_co_request(BlockDriverState *bs,

                          NBDRequest *request,

                          QEMUIOVector *qiov)

{

    NBDClientSession *client = nbd_get_client_session(bs);

    int ret;

    if (qiov) {

        assert(request->type == NBD_CMD_WRITE || request->type == NBD_CMD_READ);

        assert(request->len == iov_size(qiov->iov, qiov->niov));

    } else {

        assert(request->type != NBD_CMD_WRITE && request->type != NBD_CMD_READ);

    }

    ret = nbd_co_send_request(bs, request,

                              request->type == NBD_CMD_WRITE ? qiov : NULL);

    if (ret < 0) {

        return ret;

    }

    return nbd_co_receive_reply(client, request->handle,

                                request->type == NBD_CMD_READ ? qiov : NULL);

}


static ExitStatus trans_log(DisasContext *ctx, uint32_t insn,

                            const DisasInsn *di)

{

    unsigned r2 = extract32(insn, 21, 5);

    unsigned r1 = extract32(insn, 16, 5);

    unsigned cf = extract32(insn, 12, 4);

    unsigned rt = extract32(insn,  0, 5);

    TCGv tcg_r1, tcg_r2;

    ExitStatus ret;

    if (cf) {

        nullify_over(ctx);

    }

    tcg_r1 = load_gpr(ctx, r1);

    tcg_r2 = load_gpr(ctx, r2);

    ret = do_log(ctx, rt, tcg_r1, tcg_r2, cf, di->f_ttt);

    return nullify_end(ctx, ret);

}


static av_always_inline void xchg_mb_border(H264Context *h, uint8_t *src_y,

                                            uint8_t *src_cb, uint8_t *src_cr,

                                            int linesize, int uvlinesize,

                                            int xchg, int chroma444,

                                            int simple, int pixel_shift)

{

    int deblock_topleft;

    int deblock_top;

    int top_idx = 1;

    uint8_t *top_border_m1;

    uint8_t *top_border;

    if (!simple && FRAME_MBAFF(h)) {

        if (h->mb_y & 1) {

            if (!MB_MBAFF(h))

                return;

        } else {

            top_idx = MB_MBAFF(h) ? 0 : 1;

        }

    }

    if (h->deblocking_filter == 2) {

        deblock_topleft = h->slice_table[h->mb_xy - 1 - h->mb_stride] == h->slice_num;

        deblock_top     = h->top_type;

    } else {

        deblock_topleft = (h->mb_x > 0);

        deblock_top     = (h->mb_y > !!MB_FIELD(h));

    }

    src_y  -= linesize   + 1 + pixel_shift;

    src_cb -= uvlinesize + 1 + pixel_shift;

    src_cr -= uvlinesize + 1 + pixel_shift;

    top_border_m1 = h->top_borders[top_idx][h->mb_x - 1];

    top_border    = h->top_borders[top_idx][h->mb_x];

#define XCHG(a, b, xchg)                        \

    if (pixel_shift) {                          \

        if (xchg) {                             \

            AV_SWAP64(b + 0, a + 0);            \

            AV_SWAP64(b + 8, a + 8);            \

        } else {                                \

            AV_COPY128(b, a);                   \

        }                                       \

    } else if (xchg)                            \

        AV_SWAP64(b, a);                        \

    else                                        \

        AV_COPY64(b, a);

    if (deblock_top) {

        if (deblock_topleft) {

            XCHG(top_border_m1 + (8 << pixel_shift),

                 src_y - (7 << pixel_shift), 1);

        }

        XCHG(top_border + (0 << pixel_shift), src_y + (1 << pixel_shift), xchg);

        XCHG(top_border + (8 << pixel_shift), src_y + (9 << pixel_shift), 1);

        if (h->mb_x + 1 < h->mb_width) {

            XCHG(h->top_borders[top_idx][h->mb_x + 1],

                 src_y + (17 << pixel_shift), 1);

        }

    }

    if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {

        if (chroma444) {

            if (deblock_topleft) {

                XCHG(top_border_m1 + (24 << pixel_shift), src_cb - (7 << pixel_shift), 1);

                XCHG(top_border_m1 + (40 << pixel_shift), src_cr - (7 << pixel_shift), 1);

            }

            XCHG(top_border + (16 << pixel_shift), src_cb + (1 << pixel_shift), xchg);

            XCHG(top_border + (24 << pixel_shift), src_cb + (9 << pixel_shift), 1);

            XCHG(top_border + (32 << pixel_shift), src_cr + (1 << pixel_shift), xchg);

            XCHG(top_border + (40 << pixel_shift), src_cr + (9 << pixel_shift), 1);

            if (h->mb_x + 1 < h->mb_width) {

                XCHG(h->top_borders[top_idx][h->mb_x + 1] + (16 << pixel_shift), src_cb + (17 << pixel_shift), 1);

                XCHG(h->top_borders[top_idx][h->mb_x + 1] + (32 << pixel_shift), src_cr + (17 << pixel_shift), 1);

            }

        } else {

            if (deblock_top) {

                if (deblock_topleft) {

                    XCHG(top_border_m1 + (16 << pixel_shift), src_cb - (7 << pixel_shift), 1);

                    XCHG(top_border_m1 + (24 << pixel_shift), src_cr - (7 << pixel_shift), 1);

                }

                XCHG(top_border + (16 << pixel_shift), src_cb + 1 + pixel_shift, 1);

                XCHG(top_border + (24 << pixel_shift), src_cr + 1 + pixel_shift, 1);

            }

        }

    }

}


static int gif_image_write_image(AVCodecContext *avctx,

                                 uint8_t **bytestream, uint8_t *end,

                                 const uint8_t *buf, int linesize)

{

    GIFContext *s = avctx->priv_data;

    int len, height;

    const uint8_t *ptr;

    /* image block */

    bytestream_put_byte(bytestream, 0x2c);

    bytestream_put_le16(bytestream, 0);

    bytestream_put_le16(bytestream, 0);

    bytestream_put_le16(bytestream, avctx->width);

    bytestream_put_le16(bytestream, avctx->height);

    bytestream_put_byte(bytestream, 0x00); /* flags */

    /* no local clut */

    bytestream_put_byte(bytestream, 0x08);

    ff_lzw_encode_init(s->lzw, s->buf, avctx->width*avctx->height,

                       12, FF_LZW_GIF, put_bits);

    ptr = buf;

    for (height = avctx->height; height--;) {

        len += ff_lzw_encode(s->lzw, ptr, avctx->width);

        ptr += linesize;

    }

    len += ff_lzw_encode_flush(s->lzw, flush_put_bits);

    ptr = s->buf;

    while (len > 0) {

        int size = FFMIN(255, len);

        bytestream_put_byte(bytestream, size);

        if (end - *bytestream < size)

            return -1;

        bytestream_put_buffer(bytestream, ptr, size);

        ptr += size;

        len -= size;

    }

    bytestream_put_byte(bytestream, 0x00); /* end of image block */

    bytestream_put_byte(bytestream, 0x3b);

    return 0;

}


static int mov_write_stbl_tag(AVIOContext *pb, MOVTrack *track)

{

    int64_t pos = avio_tell(pb);

    avio_wb32(pb, 0); /* size */

    ffio_wfourcc(pb, "stbl");

    mov_write_stsd_tag(pb, track);

    mov_write_stts_tag(pb, track);

    if ((track->enc->codec_type == AVMEDIA_TYPE_VIDEO ||

         track->enc->codec_tag == MKTAG('r','t','p',' ')) &&

        track->has_keyframes && track->has_keyframes < track->entry)

        mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);

    if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)

        mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);

    if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO &&

        track->flags & MOV_TRACK_CTTS && track->entry)

        mov_write_ctts_tag(pb, track);

    mov_write_stsc_tag(pb, track);

    mov_write_stsz_tag(pb, track);

    mov_write_stco_tag(pb, track);

    return update_size(pb, pos);

}


uint64_t qcow2_get_cluster_offset(BlockDriverState *bs, uint64_t offset,

    int *num)

{

    BDRVQcowState *s = bs->opaque;

    int l1_index, l2_index;

    uint64_t l2_offset, *l2_table, cluster_offset;

    int l1_bits, c;

    int index_in_cluster, nb_available, nb_needed, nb_clusters;

    index_in_cluster = (offset >> 9) & (s->cluster_sectors - 1);

    nb_needed = *num + index_in_cluster;

    l1_bits = s->l2_bits + s->cluster_bits;

    /* compute how many bytes there are between the offset and

     * the end of the l1 entry

     */

    nb_available = (1 << l1_bits) - (offset & ((1 << l1_bits) - 1));

    /* compute the number of available sectors */

    nb_available = (nb_available >> 9) + index_in_cluster;

    if (nb_needed > nb_available) {

        nb_needed = nb_available;

    }

    cluster_offset = 0;

    /* seek the the l2 offset in the l1 table */

    l1_index = offset >> l1_bits;

    if (l1_index >= s->l1_size)

        goto out;

    l2_offset = s->l1_table[l1_index];

    /* seek the l2 table of the given l2 offset */

    if (!l2_offset)

        goto out;

    /* load the l2 table in memory */

    l2_offset &= ~QCOW_OFLAG_COPIED;

    l2_table = l2_load(bs, l2_offset);

    if (l2_table == NULL)

        return 0;

    /* find the cluster offset for the given disk offset */

    l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1);

    cluster_offset = be64_to_cpu(l2_table[l2_index]);

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

    if (!cluster_offset) {

        /* how many empty clusters ? */

        c = count_contiguous_free_clusters(nb_clusters, &l2_table[l2_index]);

    } else {

        /* how many allocated clusters ? */

        c = count_contiguous_clusters(nb_clusters, s->cluster_size,

                &l2_table[l2_index], 0, QCOW_OFLAG_COPIED);

    }

   nb_available = (c * s->cluster_sectors);

out:

    if (nb_available > nb_needed)

        nb_available = nb_needed;

    *num = nb_available - index_in_cluster;

    return cluster_offset & ~QCOW_OFLAG_COPIED;

}


static inline int RENAME(yuv420_rgb16)(SwsContext *c, uint8_t* src[], int srcStride[], int srcSliceY,

             int srcSliceH, uint8_t* dst[], int dstStride[]){

    int y, h_size;

    if(c->srcFormat == PIX_FMT_YUV422P){

	srcStride[1] *= 2;

	srcStride[2] *= 2;

    }

    h_size= (c->dstW+7)&~7;

    if(h_size*2 > FFABS(dstStride[0])) h_size-=8;

    __asm__ __volatile__ ("pxor %mm4, %mm4;" /* zero mm4 */ );

//printf("%X %X %X %X %X %X %X %X %X %X\n", (int)&c->redDither, (int)&b5Dither, (int)src[0], (int)src[1], (int)src[2], (int)dst[0],

//srcStride[0],srcStride[1],srcStride[2],dstStride[0]);

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

	uint8_t *_image = dst[0] + (y+srcSliceY)*dstStride[0];

	uint8_t *_py = src[0] + y*srcStride[0];

	uint8_t *_pu = src[1] + (y>>1)*srcStride[1];

	uint8_t *_pv = src[2] + (y>>1)*srcStride[2];

	long index= -h_size/2;

	b5Dither= dither8[y&1];

	g6Dither= dither4[y&1];

	g5Dither= dither8[y&1];

	r5Dither= dither8[(y+1)&1];

	    /* this mmx assembly code deals with SINGLE scan line at a time, it convert 8

	       pixels in each iteration */

	    __asm__ __volatile__ (

	/* load data for start of next scan line */

		     "movd (%2, %0), %%mm0;" /* Load 4 Cb 00 00 00 00 u3 u2 u1 u0 */

		     "movd (%3, %0), %%mm1;" /* Load 4 Cr 00 00 00 00 v3 v2 v1 v0 */

		     "movq (%5, %0, 2), %%mm6;" /* Load 8  Y Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y0 */

//		    ".balign 16			\n\t"

		    "1:				\n\t"

/* no speed diference on my p3@500 with prefetch,

 * if it is faster for anyone with -benchmark then tell me

			PREFETCH" 64(%0) \n\t"

			PREFETCH" 64(%1) \n\t"

			PREFETCH" 64(%2) \n\t"

*/

YUV2RGB

#ifdef DITHER1XBPP

			"paddusb "MANGLE(b5Dither)", %%mm0;"

			"paddusb "MANGLE(g6Dither)", %%mm2;"

			"paddusb "MANGLE(r5Dither)", %%mm1;"

#endif

		     /* mask unneeded bits off */

		     "pand "MANGLE(mmx_redmask)", %%mm0;" /* b7b6b5b4 b3_0_0_0 b7b6b5b4 b3_0_0_0 */

		     "pand "MANGLE(mmx_grnmask)", %%mm2;" /* g7g6g5g4 g3g2_0_0 g7g6g5g4 g3g2_0_0 */

		     "pand "MANGLE(mmx_redmask)", %%mm1;" /* r7r6r5r4 r3_0_0_0 r7r6r5r4 r3_0_0_0 */

		     "psrlw $3,%%mm0;" /* 0_0_0_b7 b6b5b4b3 0_0_0_b7 b6b5b4b3 */

		     "pxor %%mm4, %%mm4;" /* zero mm4 */

		     "movq %%mm0, %%mm5;" /* Copy B7-B0 */

		     "movq %%mm2, %%mm7;" /* Copy G7-G0 */

		     /* convert rgb24 plane to rgb16 pack for pixel 0-3 */

		     "punpcklbw %%mm4, %%mm2;" /* 0_0_0_0 0_0_0_0 g7g6g5g4 g3g2_0_0 */

		     "punpcklbw %%mm1, %%mm0;" /* r7r6r5r4 r3_0_0_0 0_0_0_b7 b6b5b4b3 */

		     "psllw $3, %%mm2;" /* 0_0_0_0 0_g7g6g5 g4g3g2_0 0_0_0_0 */

		     "por %%mm2, %%mm0;" /* r7r6r5r4 r3g7g6g5 g4g3g2b7 b6b5b4b3 */

		     "movq 8 (%5, %0, 2), %%mm6;" /* Load 8 Y Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y0 */

		     MOVNTQ " %%mm0, (%1);" /* store pixel 0-3 */

		     /* convert rgb24 plane to rgb16 pack for pixel 0-3 */

		     "punpckhbw %%mm4, %%mm7;" /* 0_0_0_0 0_0_0_0 g7g6g5g4 g3g2_0_0 */

		     "punpckhbw %%mm1, %%mm5;" /* r7r6r5r4 r3_0_0_0 0_0_0_b7 b6b5b4b3 */

		     "psllw $3, %%mm7;" /* 0_0_0_0 0_g7g6g5 g4g3g2_0 0_0_0_0 */

		     "movd 4 (%2, %0), %%mm0;" /* Load 4 Cb 00 00 00 00 u3 u2 u1 u0 */

		     "por %%mm7, %%mm5;" /* r7r6r5r4 r3g7g6g5 g4g3g2b7 b6b5b4b3 */

		     "movd 4 (%3, %0), %%mm1;" /* Load 4 Cr 00 00 00 00 v3 v2 v1 v0 */

		     MOVNTQ " %%mm5, 8 (%1);" /* store pixel 4-7 */

		     "add $16, %1			\n\t"

		     "add $4, %0			\n\t"

		     " js 1b				\n\t"

		     : "+r" (index), "+r" (_image)

		     : "r" (_pu - index), "r" (_pv - index), "r"(&c->redDither), "r" (_py - 2*index)

		     );

    }

    __asm__ __volatile__ (EMMS);

    return srcSliceH;

}


void memory_region_add_eventfd(MemoryRegion *mr,

                               hwaddr addr,

                               unsigned size,

                               bool match_data,

                               uint64_t data,

                               EventNotifier *e)

{

    MemoryRegionIoeventfd mrfd = {

        .addr.start = int128_make64(addr),

        .addr.size = int128_make64(size),

        .match_data = match_data,

        .data = data,

        .e = e,

    };

    unsigned i;

    adjust_endianness(mr, &mrfd.data, size);

    memory_region_transaction_begin();

    for (i = 0; i < mr->ioeventfd_nb; ++i) {

        if (memory_region_ioeventfd_before(mrfd, mr->ioeventfds[i])) {

            break;

        }

    }

    ++mr->ioeventfd_nb;

    mr->ioeventfds = g_realloc(mr->ioeventfds,

                                  sizeof(*mr->ioeventfds) * mr->ioeventfd_nb);

    memmove(&mr->ioeventfds[i+1], &mr->ioeventfds[i],

            sizeof(*mr->ioeventfds) * (mr->ioeventfd_nb-1 - i));

    mr->ioeventfds[i] = mrfd;

    ioeventfd_update_pending |= mr->enabled;

    memory_region_transaction_commit();

}


enum AVPixelFormat choose_pixel_fmt(AVStream *st, AVCodec *codec, enum AVPixelFormat target)

{

    if (codec && codec->pix_fmts) {

        const enum AVPixelFormat *p = codec->pix_fmts;

        int has_alpha= av_pix_fmt_desc_get(target)->nb_components % 2 == 0;

        enum AVPixelFormat best= AV_PIX_FMT_NONE;

        if (st->codec->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {

            if (st->codec->codec_id == AV_CODEC_ID_MJPEG) {

                p = (const enum AVPixelFormat[]) { AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_NONE };

            } else if (st->codec->codec_id == AV_CODEC_ID_LJPEG) {

                p = (const enum AVPixelFormat[]) { AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_YUV420P,

                                                 AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P, AV_PIX_FMT_BGRA, AV_PIX_FMT_NONE };

            }

        }

        for (; *p != AV_PIX_FMT_NONE; p++) {

            best= avcodec_find_best_pix_fmt_of_2(best, *p, target, has_alpha, NULL);

            if (*p == target)

                break;

        }

        if (*p == AV_PIX_FMT_NONE) {

            if (target != AV_PIX_FMT_NONE)

                av_log(NULL, AV_LOG_WARNING,

                       "Incompatible pixel format '%s' for codec '%s', auto-selecting format '%s'\n",

                       av_get_pix_fmt_name(target),

                       codec->name,

                       av_get_pix_fmt_name(best));

            return best;

        }

    }

    return target;

}


static void gic_set_irq(void *opaque, int irq, int level)

{

    /* Meaning of the 'irq' parameter:

     *  [0..N-1] : external interrupts

     *  [N..N+31] : PPI (internal) interrupts for CPU 0

     *  [N+32..N+63] : PPI (internal interrupts for CPU 1

     *  ...

     */

    GICState *s = (GICState *)opaque;

    int cm, target;

    if (irq < (s->num_irq - GIC_INTERNAL)) {

        /* The first external input line is internal interrupt 32.  */

        cm = ALL_CPU_MASK;

        irq += GIC_INTERNAL;

        target = GIC_TARGET(irq);

    } else {

        int cpu;

        irq -= (s->num_irq - GIC_INTERNAL);

        cpu = irq / GIC_INTERNAL;

        irq %= GIC_INTERNAL;

        cm = 1 << cpu;

        target = cm;

    }

    assert(irq >= GIC_NR_SGIS);

    if (level == GIC_TEST_LEVEL(irq, cm)) {

        return;

    }

    if (s->revision == REV_11MPCORE || s->revision == REV_NVIC) {

        gic_set_irq_11mpcore(s, irq, level, cm, target);

    } else {

        gic_set_irq_generic(s, irq, level, cm, target);

    }

    gic_update(s);

}


static int decode_mb_info(IVI5DecContext *ctx, IVIBandDesc *band,
                          IVITile *tile, AVCodecContext *avctx)
{
    int         x, y, mv_x, mv_y, mv_delta, offs, mb_offset,
                mv_scale, blks_per_mb;
    IVIMbInfo   *mb, *ref_mb;
    int         row_offset = band->mb_size * band->pitch;
    mb     = tile->mbs;
    ref_mb = tile->ref_mbs;
    offs   = tile->ypos * band->pitch + tile->xpos;
    /* scale factor for motion vectors */
    mv_scale = (ctx->planes[0].bands[0].mb_size >> 3) - (band->mb_size >> 3);
    mv_x = mv_y = 0;
    for (y = tile->ypos; y < (tile->ypos + tile->height); y += band->mb_size) {
        mb_offset = offs;
        for (x = tile->xpos; x < (tile->xpos + tile->width); x += band->mb_size) {
            mb->xpos     = x;
            mb->ypos     = y;
            mb->buf_offs = mb_offset;
            if (get_bits1(&ctx->gb)) {
                if (ctx->frame_type == FRAMETYPE_INTRA) {
                    av_log(avctx, AV_LOG_ERROR, "Empty macroblock in an INTRA picture!\n");
                    return -1;
                }
                mb->type = 1; /* empty macroblocks are always INTER */
                mb->cbp  = 0; /* all blocks are empty */
                mb->q_delta = 0;
                if (!band->plane && !band->band_num && (ctx->frame_flags & 8)) {
                    mb->q_delta = get_vlc2(&ctx->gb, ctx->mb_vlc.tab->table,
                                           IVI_VLC_BITS, 1);
                    mb->q_delta = IVI_TOSIGNED(mb->q_delta);
                }
                mb->mv_x = mb->mv_y = 0; /* no motion vector coded */
                if (band->inherit_mv){
                    /* motion vector inheritance */
                    if (mv_scale) {
                        mb->mv_x = ivi_scale_mv(ref_mb->mv_x, mv_scale);
                        mb->mv_y = ivi_scale_mv(ref_mb->mv_y, mv_scale);
                    } else {
                        mb->mv_x = ref_mb->mv_x;
                        mb->mv_y = ref_mb->mv_y;
                    }
                }
            } else {
                if (band->inherit_mv) {
                    mb->type = ref_mb->type; /* copy mb_type from corresponding reference mb */
                } else if (ctx->frame_type == FRAMETYPE_INTRA) {
                    mb->type = 0; /* mb_type is always INTRA for intra-frames */
                } else {
                    mb->type = get_bits1(&ctx->gb);
                }
                blks_per_mb = band->mb_size != band->blk_size ? 4 : 1;
                mb->cbp = get_bits(&ctx->gb, blks_per_mb);
                mb->q_delta = 0;
                if (band->qdelta_present) {
                    if (band->inherit_qdelta) {
                        if (ref_mb) mb->q_delta = ref_mb->q_delta;
                    } else if (mb->cbp || (!band->plane && !band->band_num &&
                                           (ctx->frame_flags & 8))) {
                        mb->q_delta = get_vlc2(&ctx->gb, ctx->mb_vlc.tab->table,
                                               IVI_VLC_BITS, 1);
                        mb->q_delta = IVI_TOSIGNED(mb->q_delta);
                    }
                }
                if (!mb->type) {
                    mb->mv_x = mb->mv_y = 0; /* there is no motion vector in intra-macroblocks */
                } else {
                    if (band->inherit_mv){
                        /* motion vector inheritance */
                        if (mv_scale) {
                            mb->mv_x = ivi_scale_mv(ref_mb->mv_x, mv_scale);
                            mb->mv_y = ivi_scale_mv(ref_mb->mv_y, mv_scale);
                        } else {
                            mb->mv_x = ref_mb->mv_x;
                            mb->mv_y = ref_mb->mv_y;
                        }
                    } else {
                        /* decode motion vector deltas */
                        mv_delta = get_vlc2(&ctx->gb, ctx->mb_vlc.tab->table,
                                            IVI_VLC_BITS, 1);
                        mv_y += IVI_TOSIGNED(mv_delta);
                        mv_delta = get_vlc2(&ctx->gb, ctx->mb_vlc.tab->table,
                                            IVI_VLC_BITS, 1);
                        mv_x += IVI_TOSIGNED(mv_delta);
                        mb->mv_x = mv_x;
                        mb->mv_y = mv_y;
                    }
                }
            }
            mb++;
            if (ref_mb)
                ref_mb++;
            mb_offset += band->mb_size;
        }
        offs += row_offset;
    }
    align_get_bits(&ctx->gb);
    return 0;
}


VIOsPAPRDevice *vty_lookup(sPAPRMachineState *spapr, target_ulong reg)
{
    VIOsPAPRDevice *sdev;
    sdev = spapr_vio_find_by_reg(spapr->vio_bus, reg);
    if (!sdev && reg == 0) {
        /* Hack for kernel early debug, which always specifies reg==0.
         * We search all VIO devices, and grab the vty with the lowest
         * reg.  This attempts to mimic existing PowerVM behaviour
         * (early debug does work there, despite having no vty with
         * reg==0. */
        return spapr_vty_get_default(spapr->vio_bus);
    return sdev;


void coroutine_fn block_job_pause_point(BlockJob *job)

{

    assert(job && block_job_started(job));

    if (!block_job_should_pause(job)) {

        return;

    }

    if (block_job_is_cancelled(job)) {

        return;

    }

    if (job->driver->pause) {

        job->driver->pause(job);

    }

    if (block_job_should_pause(job) && !block_job_is_cancelled(job)) {

        job->paused = true;

        job->busy = false;

        qemu_coroutine_yield(); /* wait for block_job_resume() */

        job->busy = true;

        job->paused = false;

    }

    if (job->driver->resume) {

        job->driver->resume(job);

    }

}


int bdrv_pread(BlockDriverState *bs, int64_t offset,
               void *buf1, int count1)
{
    BlockDriver *drv = bs->drv;
    if (!drv)
        return -ENOMEDIUM;
    if (!drv->bdrv_pread)
        return bdrv_pread_em(bs, offset, buf1, count1);
    return drv->bdrv_pread(bs, offset, buf1, count1);
}


int avpriv_dca_convert_bitstream(const uint8_t *src, int src_size, uint8_t *dst,

                             int max_size)

{

    uint32_t mrk;

    int i, tmp;

    const uint16_t *ssrc = (const uint16_t *) src;

    uint16_t *sdst = (uint16_t *) dst;

    PutBitContext pb;

    if ((unsigned) src_size > (unsigned) max_size)

        src_size = max_size;

    mrk = AV_RB32(src);

    switch (mrk) {

    case DCA_SYNCWORD_CORE_BE:

        memcpy(dst, src, src_size);

        return src_size;

    case DCA_SYNCWORD_CORE_LE:

        for (i = 0; i < (src_size + 1) >> 1; i++)

            *sdst++ = av_bswap16(*ssrc++);

        return src_size;

    case DCA_SYNCWORD_CORE_14B_BE:

    case DCA_SYNCWORD_CORE_14B_LE:

        init_put_bits(&pb, dst, max_size);

        for (i = 0; i < (src_size + 1) >> 1; i++, src += 2) {

            tmp = ((mrk == DCA_SYNCWORD_CORE_14B_BE) ? AV_RB16(src) : AV_RL16(src)) & 0x3FFF;

            put_bits(&pb, 14, tmp);

        }

        flush_put_bits(&pb);

        return (put_bits_count(&pb) + 7) >> 3;

    default:

        return AVERROR_INVALIDDATA;

    }

}


static TRBCCode xhci_disable_ep(XHCIState *xhci, unsigned int slotid,
                               unsigned int epid)
{
    XHCISlot *slot;
    XHCIEPContext *epctx;
    int i;
    trace_usb_xhci_ep_disable(slotid, epid);
    assert(slotid >= 1 && slotid <= xhci->numslots);
    assert(epid >= 1 && epid <= 31);
    slot = &xhci->slots[slotid-1];
    if (!slot->eps[epid-1]) {
        DPRINTF("xhci: slot %d ep %d already disabled\n", slotid, epid);
        return CC_SUCCESS;
    xhci_ep_nuke_xfers(xhci, slotid, epid);
    epctx = slot->eps[epid-1];
    if (epctx->nr_pstreams) {
        xhci_free_streams(epctx);
    xhci_set_ep_state(xhci, epctx, NULL, EP_DISABLED);
    timer_free(epctx->kick_timer);
    g_free(epctx);
    slot->eps[epid-1] = NULL;
    return CC_SUCCESS;


int pvpanic_init(ISABus *bus)

{

    isa_create_simple(bus, TYPE_ISA_PVPANIC_DEVICE);

    return 0;

}


static uint32_t gic_dist_readb(void *opaque, hwaddr offset, MemTxAttrs attrs)

{

    GICState *s = (GICState *)opaque;

    uint32_t res;

    int irq;

    int i;

    int cpu;

    int cm;

    int mask;

    cpu = gic_get_current_cpu(s);

    cm = 1 << cpu;

    if (offset < 0x100) {

        if (offset == 0)

            return s->enabled;

        if (offset == 4)

            /* Interrupt Controller Type Register */

            return ((s->num_irq / 32) - 1)

                    | ((NUM_CPU(s) - 1) << 5)

                    | (s->security_extn << 10);

        if (offset < 0x08)

            return 0;

        if (offset >= 0x80) {

            /* Interrupt Group Registers: these RAZ/WI if this is an NS

             * access to a GIC with the security extensions, or if the GIC

             * doesn't have groups at all.

             */

            res = 0;

            if (!(s->security_extn && !attrs.secure) && gic_has_groups(s)) {

                /* Every byte offset holds 8 group status bits */

                irq = (offset - 0x080) * 8 + GIC_BASE_IRQ;

                if (irq >= s->num_irq) {

                    goto bad_reg;

                }

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

                    if (GIC_TEST_GROUP(irq + i, cm)) {

                        res |= (1 << i);

                    }

                }

            }

            return res;

        }

        goto bad_reg;

    } else if (offset < 0x200) {

        /* Interrupt Set/Clear Enable.  */

        if (offset < 0x180)

            irq = (offset - 0x100) * 8;

        else

            irq = (offset - 0x180) * 8;

        irq += GIC_BASE_IRQ;

        if (irq >= s->num_irq)

            goto bad_reg;

        res = 0;

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

            if (GIC_TEST_ENABLED(irq + i, cm)) {

                res |= (1 << i);

            }

        }

    } else if (offset < 0x300) {

        /* Interrupt Set/Clear Pending.  */

        if (offset < 0x280)

            irq = (offset - 0x200) * 8;

        else

            irq = (offset - 0x280) * 8;

        irq += GIC_BASE_IRQ;

        if (irq >= s->num_irq)

            goto bad_reg;

        res = 0;

        mask = (irq < GIC_INTERNAL) ?  cm : ALL_CPU_MASK;

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

            if (gic_test_pending(s, irq + i, mask)) {

                res |= (1 << i);

            }

        }

    } else if (offset < 0x400) {

        /* Interrupt Active.  */

        irq = (offset - 0x300) * 8 + GIC_BASE_IRQ;

        if (irq >= s->num_irq)

            goto bad_reg;

        res = 0;

        mask = (irq < GIC_INTERNAL) ?  cm : ALL_CPU_MASK;

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

            if (GIC_TEST_ACTIVE(irq + i, mask)) {

                res |= (1 << i);

            }

        }

    } else if (offset < 0x800) {

        /* Interrupt Priority.  */

        irq = (offset - 0x400) + GIC_BASE_IRQ;

        if (irq >= s->num_irq)

            goto bad_reg;

        res = GIC_GET_PRIORITY(irq, cpu);

    } else if (offset < 0xc00) {

        /* Interrupt CPU Target.  */

        if (s->num_cpu == 1 && s->revision != REV_11MPCORE) {

            /* For uniprocessor GICs these RAZ/WI */

            res = 0;

        } else {

            irq = (offset - 0x800) + GIC_BASE_IRQ;

            if (irq >= s->num_irq) {

                goto bad_reg;

            }

            if (irq >= 29 && irq <= 31) {

                res = cm;

            } else {

                res = GIC_TARGET(irq);

            }

        }

    } else if (offset < 0xf00) {

        /* Interrupt Configuration.  */

        irq = (offset - 0xc00) * 4 + GIC_BASE_IRQ;

        if (irq >= s->num_irq)

            goto bad_reg;

        res = 0;

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

            if (GIC_TEST_MODEL(irq + i))

                res |= (1 << (i * 2));

            if (GIC_TEST_EDGE_TRIGGER(irq + i))

                res |= (2 << (i * 2));

        }

    } else if (offset < 0xf10) {

        goto bad_reg;

    } else if (offset < 0xf30) {

        if (s->revision == REV_11MPCORE || s->revision == REV_NVIC) {

            goto bad_reg;

        }

        if (offset < 0xf20) {

            /* GICD_CPENDSGIRn */

            irq = (offset - 0xf10);

        } else {

            irq = (offset - 0xf20);

            /* GICD_SPENDSGIRn */

        }

        res = s->sgi_pending[irq][cpu];

    } else if (offset < 0xfe0) {

        goto bad_reg;

    } else /* offset >= 0xfe0 */ {

        if (offset & 3) {

            res = 0;

        } else {

            res = gic_id[(offset - 0xfe0) >> 2];

        }

    }

    return res;

bad_reg:

    qemu_log_mask(LOG_GUEST_ERROR,

                  "gic_dist_readb: Bad offset %x\n", (int)offset);

    return 0;

}


static inline int get_segment_6xx_tlb(CPUPPCState *env, mmu_ctx_t *ctx,

                                      target_ulong eaddr, int rw, int type)

{

    hwaddr hash;

    target_ulong vsid;

    int ds, pr, target_page_bits;

    int ret;

    target_ulong sr, pgidx;

    pr = msr_pr;

    ctx->eaddr = eaddr;

    sr = env->sr[eaddr >> 28];

    ctx->key = (((sr & 0x20000000) && (pr != 0)) ||

                ((sr & 0x40000000) && (pr == 0))) ? 1 : 0;

    ds = sr & 0x80000000 ? 1 : 0;

    ctx->nx = sr & 0x10000000 ? 1 : 0;

    vsid = sr & 0x00FFFFFF;

    target_page_bits = TARGET_PAGE_BITS;

    qemu_log_mask(CPU_LOG_MMU,

            "Check segment v=" TARGET_FMT_lx " %d " TARGET_FMT_lx

            " nip=" TARGET_FMT_lx " lr=" TARGET_FMT_lx

            " ir=%d dr=%d pr=%d %d t=%d\n",

            eaddr, (int)(eaddr >> 28), sr, env->nip, env->lr, (int)msr_ir,

            (int)msr_dr, pr != 0 ? 1 : 0, rw, type);

    pgidx = (eaddr & ~SEGMENT_MASK_256M) >> target_page_bits;

    hash = vsid ^ pgidx;

    ctx->ptem = (vsid << 7) | (pgidx >> 10);

    qemu_log_mask(CPU_LOG_MMU,

            "pte segment: key=%d ds %d nx %d vsid " TARGET_FMT_lx "\n",

            ctx->key, ds, ctx->nx, vsid);

    ret = -1;

    if (!ds) {

        /* Check if instruction fetch is allowed, if needed */

        if (type != ACCESS_CODE || ctx->nx == 0) {

            /* Page address translation */

            qemu_log_mask(CPU_LOG_MMU, "htab_base " TARGET_FMT_plx

                    " htab_mask " TARGET_FMT_plx

                    " hash " TARGET_FMT_plx "\n",

                    env->htab_base, env->htab_mask, hash);

            ctx->hash[0] = hash;

            ctx->hash[1] = ~hash;

            /* Initialize real address with an invalid value */

            ctx->raddr = (hwaddr)-1ULL;

            /* Software TLB search */

            ret = ppc6xx_tlb_check(env, ctx, eaddr, rw, type);

#if defined(DUMP_PAGE_TABLES)

            if (qemu_loglevel_mask(CPU_LOG_MMU)) {

                CPUState *cs = ENV_GET_CPU(env);

                hwaddr curaddr;

                uint32_t a0, a1, a2, a3;

                qemu_log("Page table: " TARGET_FMT_plx " len " TARGET_FMT_plx

                         "\n", env->htab_base, env->htab_mask + 0x80);

                for (curaddr = env->htab_base;

                     curaddr < (env->htab_base + env->htab_mask + 0x80);

                     curaddr += 16) {

                    a0 = ldl_phys(cs->as, curaddr);

                    a1 = ldl_phys(cs->as, curaddr + 4);

                    a2 = ldl_phys(cs->as, curaddr + 8);

                    a3 = ldl_phys(cs->as, curaddr + 12);

                    if (a0 != 0 || a1 != 0 || a2 != 0 || a3 != 0) {

                        qemu_log(TARGET_FMT_plx ": %08x %08x %08x %08x\n",

                                 curaddr, a0, a1, a2, a3);

                    }

                }

            }

#endif

        } else {

            qemu_log_mask(CPU_LOG_MMU, "No access allowed\n");

            ret = -3;

        }

    } else {

        target_ulong sr;

        qemu_log_mask(CPU_LOG_MMU, "direct store...\n");

        /* Direct-store segment : absolutely *BUGGY* for now */

        /* Direct-store implies a 32-bit MMU.

         * Check the Segment Register's bus unit ID (BUID).

         */

        sr = env->sr[eaddr >> 28];

        if ((sr & 0x1FF00000) >> 20 == 0x07f) {

            /* Memory-forced I/O controller interface access */

            /* If T=1 and BUID=x'07F', the 601 performs a memory access

             * to SR[28-31] LA[4-31], bypassing all protection mechanisms.

             */

            ctx->raddr = ((sr & 0xF) << 28) | (eaddr & 0x0FFFFFFF);

            ctx->prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;

            return 0;

        }

        switch (type) {

        case ACCESS_INT:

            /* Integer load/store : only access allowed */

            break;

        case ACCESS_CODE:

            /* No code fetch is allowed in direct-store areas */

            return -4;

        case ACCESS_FLOAT:

            /* Floating point load/store */

            return -4;

        case ACCESS_RES:

            /* lwarx, ldarx or srwcx. */

            return -4;

        case ACCESS_CACHE:

            /* dcba, dcbt, dcbtst, dcbf, dcbi, dcbst, dcbz, or icbi */

            /* Should make the instruction do no-op.

             * As it already do no-op, it's quite easy :-)

             */

            ctx->raddr = eaddr;

            return 0;

        case ACCESS_EXT:

            /* eciwx or ecowx */

            return -4;

        default:

            qemu_log_mask(CPU_LOG_MMU, "ERROR: instruction should not need "

                          "address translation\n");

            return -4;

        }

        if ((rw == 1 || ctx->key != 1) && (rw == 0 || ctx->key != 0)) {

            ctx->raddr = eaddr;

            ret = 2;

        } else {

            ret = -2;

        }

    }

    return ret;

}


static void slirp_socket_save(QEMUFile *f, struct socket *so)

{

    qemu_put_be32(f, so->so_urgc);

    qemu_put_be16(f, so->so_ffamily);

    switch (so->so_ffamily) {

    case AF_INET:

        qemu_put_be32(f, so->so_faddr.s_addr);

        qemu_put_be16(f, so->so_fport);

        break;

    default:

        error_report(

                "so_ffamily unknown, unable to save so_faddr and so_fport\n");

    }

    qemu_put_be16(f, so->so_lfamily);

    switch (so->so_lfamily) {

    case AF_INET:

        qemu_put_be32(f, so->so_laddr.s_addr);

        qemu_put_be16(f, so->so_lport);

        break;

    default:

        error_report(

                "so_ffamily unknown, unable to save so_laddr and so_lport\n");

    }

    qemu_put_byte(f, so->so_iptos);

    qemu_put_byte(f, so->so_emu);

    qemu_put_byte(f, so->so_type);

    qemu_put_be32(f, so->so_state);

    slirp_sbuf_save(f, &so->so_rcv);

    slirp_sbuf_save(f, &so->so_snd);

    slirp_tcp_save(f, so->so_tcpcb);

}


void object_property_allow_set_link(Object *obj, const char *name,

                                    Object *val, Error **errp)

{

    /* Allow the link to be set, always */

}


static inline void mix_3f_1r_to_mono(AC3DecodeContext *ctx)

{

    int i;

    float (*output)[256] = ctx->audio_block.block_output;

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

        output[1][i] = (output[2][i] + output[3][i] + output[4][i]);

    memset(output[2], 0, sizeof(output[2]));

    memset(output[3], 0, sizeof(output[3]));

    memset(output[4], 0, sizeof(output[4]));

}


static inline void RENAME(nv21ToUV)(uint8_t *dstU, uint8_t *dstV,

                                    const uint8_t *src1, const uint8_t *src2,

                                    long width, uint32_t *unused)

{

    RENAME(nvXXtoUV)(dstV, dstU, src1, width);

}


static uint64_t lan9118_readl(void *opaque, target_phys_addr_t offset,

                              unsigned size)

{

    lan9118_state *s = (lan9118_state *)opaque;

    //DPRINTF("Read reg 0x%02x\n", (int)offset);

    if (offset < 0x20) {

        /* RX FIFO */

        return rx_fifo_pop(s);

    }

    switch (offset) {

    case 0x40:

        return rx_status_fifo_pop(s);

    case 0x44:

        return s->rx_status_fifo[s->tx_status_fifo_head];

    case 0x48:

        return tx_status_fifo_pop(s);

    case 0x4c:

        return s->tx_status_fifo[s->tx_status_fifo_head];

    case CSR_ID_REV:

        return 0x01180001;

    case CSR_IRQ_CFG:

        return s->irq_cfg;

    case CSR_INT_STS:

        return s->int_sts;

    case CSR_INT_EN:

        return s->int_en;

    case CSR_BYTE_TEST:

        return 0x87654321;

    case CSR_FIFO_INT:

        return s->fifo_int;

    case CSR_RX_CFG:

        return s->rx_cfg;

    case CSR_TX_CFG:

        return s->tx_cfg;

    case CSR_HW_CFG:

        return s->hw_cfg;

    case CSR_RX_DP_CTRL:

        return 0;

    case CSR_RX_FIFO_INF:

        return (s->rx_status_fifo_used << 16) | (s->rx_fifo_used << 2);

    case CSR_TX_FIFO_INF:

        return (s->tx_status_fifo_used << 16)

               | (s->tx_fifo_size - s->txp->fifo_used);

    case CSR_PMT_CTRL:

        return s->pmt_ctrl;

    case CSR_GPIO_CFG:

        return s->gpio_cfg;

    case CSR_GPT_CFG:

        return s->gpt_cfg;

    case CSR_GPT_CNT:

        return ptimer_get_count(s->timer);

    case CSR_WORD_SWAP:

        return s->word_swap;

    case CSR_FREE_RUN:

        return (qemu_get_clock_ns(vm_clock) / 40) - s->free_timer_start;

    case CSR_RX_DROP:

        /* TODO: Implement dropped frames counter.  */

        return 0;

    case CSR_MAC_CSR_CMD:

        return s->mac_cmd;

    case CSR_MAC_CSR_DATA:

        return s->mac_data;

    case CSR_AFC_CFG:

        return s->afc_cfg;

    case CSR_E2P_CMD:

        return s->e2p_cmd;

    case CSR_E2P_DATA:

        return s->e2p_data;

    }

    hw_error("lan9118_read: Bad reg 0x%x\n", (int)offset);

    return 0;

}


static int read_low_coeffs(AVCodecContext *avctx, int16_t *dst, int size, int width, ptrdiff_t stride)

{

    PixletContext *ctx = avctx->priv_data;

    GetBitContext *b = &ctx->gbit;

    unsigned cnt1, nbits, k, j = 0, i = 0;

    int64_t value, state = 3;

    int rlen, escape, flag = 0;

    while (i < size) {

        nbits = FFMIN(ff_clz((state >> 8) + 3) ^ 0x1F, 14);

        cnt1 = get_unary(b, 0, 8);

        if (cnt1 < 8) {

            value = show_bits(b, nbits);

            if (value <= 1) {

                skip_bits(b, nbits - 1);

                escape = ((1 << nbits) - 1) * cnt1;

            } else {

                skip_bits(b, nbits);

                escape = value + ((1 << nbits) - 1) * cnt1 - 1;

            }

        } else {

            escape = get_bits(b, 16);

        }

        value = -((escape + flag) & 1) | 1;

        dst[j++] = value * ((escape + flag + 1) >> 1);

        i++;

        if (j == width) {

            j = 0;

            dst += stride;

        }

        state = 120 * (escape + flag) + state - (120 * state >> 8);

        flag = 0;

        if (state * 4 > 0xFF || i >= size)

            continue;

        nbits = ((state + 8) >> 5) + (state ? ff_clz(state) : 32) - 24;

        escape = av_mod_uintp2(16383, nbits);

        cnt1 = get_unary(b, 0, 8);

        if (cnt1 > 7) {

            rlen = get_bits(b, 16);

        } else {

            value = show_bits(b, nbits);

            if (value > 1) {

                skip_bits(b, nbits);

                rlen = value + escape * cnt1 - 1;

            } else {

                skip_bits(b, nbits - 1);

                rlen = escape * cnt1;

            }

        }

        if (i + rlen > size)

            return AVERROR_INVALIDDATA;

        i += rlen;

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

            dst[j++] = 0;

            if (j == width) {

                j = 0;

                dst += stride;

            }

        }

        state = 0;

        flag = rlen < 0xFFFF ? 1 : 0;

    }

    align_get_bits(b);

    return get_bits_count(b) >> 3;

}


static int nbd_co_readv_1(BlockDriverState *bs, int64_t sector_num,

                          int nb_sectors, QEMUIOVector *qiov,

                          int offset)

{

    BDRVNBDState *s = bs->opaque;

    struct nbd_request request;

    struct nbd_reply reply;

    request.type = NBD_CMD_READ;

    request.from = sector_num * 512;

    request.len = nb_sectors * 512;

    nbd_coroutine_start(s, &request);

    if (nbd_co_send_request(s, &request, NULL, 0) == -1) {

        reply.error = errno;

    } else {

        nbd_co_receive_reply(s, &request, &reply, qiov->iov, offset);

    }

    nbd_coroutine_end(s, &request);

    return -reply.error;

}


static int request_frame(AVFilterLink *link)

{

    AVFilterContext *ctx = link->src;

    IDETContext *idet = ctx->priv;

    do {

        int ret;

        if (idet->eof)

            return AVERROR_EOF;

        ret = ff_request_frame(link->src->inputs[0]);

        if (ret == AVERROR_EOF && idet->cur) {

            AVFrame *next = av_frame_clone(idet->next);

            if (!next)

                return AVERROR(ENOMEM);

            filter_frame(link->src->inputs[0], next);

            idet->eof = 1;

        } else if (ret < 0) {

            return ret;

        }

    } while (!idet->cur);

    return 0;

}


static int dpcm_decode_frame(AVCodecContext *avctx,
                             void *data, int *data_size,
                             uint8_t *buf, int buf_size)
{
    DPCMContext *s = avctx->priv_data;
    int in, out = 0;
    int predictor[2];
    int channel_number = 0;
    short *output_samples = data;
    int shift[2];
    unsigned char byte;
    short diff;
    if (!buf_size)
        return 0;
    switch(avctx->codec->id) {
    case CODEC_ID_ROQ_DPCM:
        if (s->channels == 1)
            predictor[0] = AV_RL16(&buf[6]);
        else {
            predictor[0] = buf[7] << 8;
            predictor[1] = buf[6] << 8;
        }
        SE_16BIT(predictor[0]);
        SE_16BIT(predictor[1]);
        /* decode the samples */
        for (in = 8, out = 0; in < buf_size; in++, out++) {
            predictor[channel_number] += s->roq_square_array[buf[in]];
            predictor[channel_number] = av_clip_int16(predictor[channel_number]);
            output_samples[out] = predictor[channel_number];
            /* toggle channel */
            channel_number ^= s->channels - 1;
        }
        break;
    case CODEC_ID_INTERPLAY_DPCM:
        in = 6;  /* skip over the stream mask and stream length */
        predictor[0] = AV_RL16(&buf[in]);
        in += 2;
        SE_16BIT(predictor[0])
        output_samples[out++] = predictor[0];
        if (s->channels == 2) {
            predictor[1] = AV_RL16(&buf[in]);
            in += 2;
            SE_16BIT(predictor[1])
            output_samples[out++] = predictor[1];
        }
        while (in < buf_size) {
            predictor[channel_number] += interplay_delta_table[buf[in++]];
            predictor[channel_number] = av_clip_int16(predictor[channel_number]);
            output_samples[out++] = predictor[channel_number];
            /* toggle channel */
            channel_number ^= s->channels - 1;
        }
        break;
    case CODEC_ID_XAN_DPCM:
        in = 0;
        shift[0] = shift[1] = 4;
        predictor[0] = AV_RL16(&buf[in]);
        in += 2;
        SE_16BIT(predictor[0]);
        if (s->channels == 2) {
            predictor[1] = AV_RL16(&buf[in]);
            in += 2;
            SE_16BIT(predictor[1]);
        }
        while (in < buf_size) {
            byte = buf[in++];
            diff = (byte & 0xFC) << 8;
            if ((byte & 0x03) == 3)
                shift[channel_number]++;
            else
                shift[channel_number] -= (2 * (byte & 3));
            /* saturate the shifter to a lower limit of 0 */
            if (shift[channel_number] < 0)
                shift[channel_number] = 0;
            diff >>= shift[channel_number];
            predictor[channel_number] += diff;
            predictor[channel_number] = av_clip_int16(predictor[channel_number]);
            output_samples[out++] = predictor[channel_number];
            /* toggle channel */
            channel_number ^= s->channels - 1;
        }
        break;
    case CODEC_ID_SOL_DPCM:
        in = 0;
        if (avctx->codec_tag != 3) {
            if(*data_size/4 < buf_size)
            while (in < buf_size) {
                int n1, n2;
                n1 = (buf[in] >> 4) & 0xF;
                n2 = buf[in++] & 0xF;
                s->sample[0] += s->sol_table[n1];
                 if (s->sample[0] < 0) s->sample[0] = 0;
                if (s->sample[0] > 255) s->sample[0] = 255;
                output_samples[out++] = (s->sample[0] - 128) << 8;
                s->sample[s->channels - 1] += s->sol_table[n2];
                if (s->sample[s->channels - 1] < 0) s->sample[s->channels - 1] = 0;
                if (s->sample[s->channels - 1] > 255) s->sample[s->channels - 1] = 255;
                output_samples[out++] = (s->sample[s->channels - 1] - 128) << 8;
            }
        } else {
            while (in < buf_size) {
                int n;
                n = buf[in++];
                if (n & 0x80) s->sample[channel_number] -= s->sol_table[n & 0x7F];
                else s->sample[channel_number] += s->sol_table[n & 0x7F];
                s->sample[channel_number] = av_clip_int16(s->sample[channel_number]);
                output_samples[out++] = s->sample[channel_number];
                /* toggle channel */
                channel_number ^= s->channels - 1;
            }
        }
        break;
    }
    *data_size = out * sizeof(short);
    return buf_size;
}


int ff_rm_read_mdpr_codecdata(AVFormatContext *s, AVIOContext *pb,

                              AVStream *st, RMStream *rst,

                              unsigned int codec_data_size, const uint8_t *mime)

{

    unsigned int v;

    int size;

    int64_t codec_pos;

    int ret;

    if (codec_data_size > INT_MAX)

        return AVERROR_INVALIDDATA;

    avpriv_set_pts_info(st, 64, 1, 1000);

    codec_pos = avio_tell(pb);

    v = avio_rb32(pb);

    if (v == MKBETAG('M', 'L', 'T', 'I')) {

        int number_of_streams = avio_rb16(pb);

        int number_of_mdpr;

        int i;

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

            avio_rb16(pb);

        number_of_mdpr = avio_rb16(pb);

        if (number_of_mdpr != 1) {

            avpriv_request_sample(s, "MLTI with multiple MDPR");

        }

        avio_rb32(pb);

        v = avio_rb32(pb);

    }

    if (v == MKTAG(0xfd, 'a', 'r', '.')) {

        /* ra type header */

        if (rm_read_audio_stream_info(s, pb, st, rst, 0))

            return -1;

    } else if (v == MKBETAG('L', 'S', 'D', ':')) {

        avio_seek(pb, -4, SEEK_CUR);

        if ((ret = rm_read_extradata(pb, st->codec, codec_data_size)) < 0)

            return ret;

        st->codec->codec_type = AVMEDIA_TYPE_AUDIO;

        st->codec->codec_tag  = AV_RL32(st->codec->extradata);

        st->codec->codec_id   = ff_codec_get_id(ff_rm_codec_tags,

                                                st->codec->codec_tag);

    } else if(mime && !strcmp(mime, "logical-fileinfo")){

        int stream_count, rule_count, property_count, i;

        ff_free_stream(s, st);

        if (avio_rb16(pb) != 0) {

            av_log(s, AV_LOG_WARNING, "Unsupported version\n");

            goto skip;

        }

        stream_count = avio_rb16(pb);

        avio_skip(pb, 6*stream_count);

        rule_count = avio_rb16(pb);

        avio_skip(pb, 2*rule_count);

        property_count = avio_rb16(pb);

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

            uint8_t name[128], val[128];

            avio_rb32(pb);

            if (avio_rb16(pb) != 0) {

                av_log(s, AV_LOG_WARNING, "Unsupported Name value property version\n");

                goto skip; //FIXME skip just this one

            }

            get_str8(pb, name, sizeof(name));

            switch(avio_rb32(pb)) {

            case 2: get_strl(pb, val, sizeof(val), avio_rb16(pb));

                av_dict_set(&s->metadata, name, val, 0);

                break;

            default: avio_skip(pb, avio_rb16(pb));

            }

        }

    } else {

        int fps;

        if (avio_rl32(pb) != MKTAG('V', 'I', 'D', 'O')) {

        fail1:

            av_log(s, AV_LOG_WARNING, "Unsupported stream type %08x\n", v);

            goto skip;

        }

        st->codec->codec_tag = avio_rl32(pb);

        st->codec->codec_id  = ff_codec_get_id(ff_rm_codec_tags,

                                               st->codec->codec_tag);

        av_dlog(s, "%X %X\n", st->codec->codec_tag, MKTAG('R', 'V', '2', '0'));

        if (st->codec->codec_id == AV_CODEC_ID_NONE)

            goto fail1;

        st->codec->width  = avio_rb16(pb);

        st->codec->height = avio_rb16(pb);

        avio_skip(pb, 2); // looks like bits per sample

        avio_skip(pb, 4); // always zero?

        st->codec->codec_type = AVMEDIA_TYPE_VIDEO;

        st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;

        fps = avio_rb32(pb);

        if ((ret = rm_read_extradata(pb, st->codec, codec_data_size - (avio_tell(pb) - codec_pos))) < 0)

            return ret;

        if (fps > 0) {

            av_reduce(&st->avg_frame_rate.den, &st->avg_frame_rate.num,

                      0x10000, fps, (1 << 30) - 1);

#if FF_API_R_FRAME_RATE

            st->r_frame_rate = st->avg_frame_rate;

#endif

        } else if (s->error_recognition & AV_EF_EXPLODE) {

            av_log(s, AV_LOG_ERROR, "Invalid framerate\n");

            return AVERROR_INVALIDDATA;

        }

    }

skip:

    /* skip codec info */

    size = avio_tell(pb) - codec_pos;

    avio_skip(pb, codec_data_size - size);

    return 0;

}


int sd_do_command(SDState *sd, SDRequest *req,

                  uint8_t *response) {

    uint32_t last_status = sd->card_status;

    sd_rsp_type_t rtype;

    int rsplen;

    if (!sd->bdrv || !bdrv_is_inserted(sd->bdrv) || !sd->enable) {

        return 0;

    }

    if (sd_req_crc_validate(req)) {

        sd->card_status &= ~COM_CRC_ERROR;

        return 0;

    }

    sd->card_status &= ~CARD_STATUS_B;

    sd_set_status(sd);

    if (last_status & CARD_IS_LOCKED) {

        if (!cmd_valid_while_locked(sd, req)) {

            sd->card_status |= ILLEGAL_COMMAND;

            fprintf(stderr, "SD: Card is locked\n");

            return 0;

        }

    }

    if (last_status & APP_CMD) {

        rtype = sd_app_command(sd, *req);

        sd->card_status &= ~APP_CMD;

    } else

        rtype = sd_normal_command(sd, *req);

    sd->current_cmd = req->cmd;

    switch (rtype) {

    case sd_r1:

    case sd_r1b:

        sd_response_r1_make(sd, response, last_status);

        rsplen = 4;

        break;

    case sd_r2_i:

        memcpy(response, sd->cid, sizeof(sd->cid));

        rsplen = 16;

        break;

    case sd_r2_s:

        memcpy(response, sd->csd, sizeof(sd->csd));

        rsplen = 16;

        break;

    case sd_r3:

        sd_response_r3_make(sd, response);

        rsplen = 4;

        break;

    case sd_r6:

        sd_response_r6_make(sd, response);

        rsplen = 4;

        break;

    case sd_r7:

        sd_response_r7_make(sd, response);

        rsplen = 4;

        break;

    case sd_r0:

    default:

        rsplen = 0;

        break;

    }

    if (sd->card_status & ILLEGAL_COMMAND)

        rsplen = 0;

#ifdef DEBUG_SD

    if (rsplen) {

        int i;

        DPRINTF("Response:");

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

            printf(" %02x", response[i]);

        printf(" state %d\n", sd->state);

    } else {

        DPRINTF("No response %d\n", sd->state);

    }

#endif

    return rsplen;

}


static int dpcm_decode_frame(AVCodecContext *avctx,

                             void *data, int *data_size,

                             AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    DPCMContext *s = avctx->priv_data;

    int in, out = 0;

    int predictor[2];

    int ch = 0;

    int stereo = s->channels - 1;

    short *output_samples = data;

    int shift[2];

    unsigned char byte;

    short diff;

    if (!buf_size)

        return 0;

    // almost every DPCM variant expands one byte of data into two

    if(*data_size/2 < buf_size)

        return -1;

    switch(avctx->codec->id) {

    case CODEC_ID_ROQ_DPCM:

        if (stereo) {

            predictor[0] = buf[7] << 8;

            predictor[1] = buf[6] << 8;

        } else {

            predictor[0] = AV_RL16(&buf[6]);

        }

        SE_16BIT(predictor[0]);

        SE_16BIT(predictor[1]);

        /* decode the samples */

        for (in = 8, out = 0; in < buf_size; in++, out++) {

            predictor[ch] += s->roq_square_array[buf[in]];

            predictor[ch] = av_clip_int16(predictor[ch]);

            output_samples[out] = predictor[ch];

            /* toggle channel */

            ch ^= stereo;

        }

        break;

    case CODEC_ID_INTERPLAY_DPCM:

        in = 6;  /* skip over the stream mask and stream length */

        predictor[0] = AV_RL16(&buf[in]);

        in += 2;

        SE_16BIT(predictor[0])

        output_samples[out++] = predictor[0];

        if (stereo) {

            predictor[1] = AV_RL16(&buf[in]);

            in += 2;

            SE_16BIT(predictor[1])

            output_samples[out++] = predictor[1];

        }

        while (in < buf_size) {

            predictor[ch] += interplay_delta_table[buf[in++]];

            predictor[ch] = av_clip_int16(predictor[ch]);

            output_samples[out++] = predictor[ch];

            /* toggle channel */

            ch ^= stereo;

        }

        break;

    case CODEC_ID_XAN_DPCM:

        in = 0;

        shift[0] = shift[1] = 4;

        predictor[0] = AV_RL16(&buf[in]);

        in += 2;

        SE_16BIT(predictor[0]);

        if (stereo) {

            predictor[1] = AV_RL16(&buf[in]);

            in += 2;

            SE_16BIT(predictor[1]);

        }

        while (in < buf_size) {

            byte = buf[in++];

            diff = (byte & 0xFC) << 8;

            if ((byte & 0x03) == 3)

                shift[ch]++;

            else

                shift[ch] -= (2 * (byte & 3));

            /* saturate the shifter to a lower limit of 0 */

            if (shift[ch] < 0)

                shift[ch] = 0;

            diff >>= shift[ch];

            predictor[ch] += diff;

            predictor[ch] = av_clip_int16(predictor[ch]);

            output_samples[out++] = predictor[ch];

            /* toggle channel */

            ch ^= stereo;

        }

        break;

    case CODEC_ID_SOL_DPCM:

        in = 0;

        if (avctx->codec_tag != 3) {

            if(*data_size/4 < buf_size)

                return -1;

            while (in < buf_size) {

                int n1, n2;

                n1 = (buf[in] >> 4) & 0xF;

                n2 = buf[in++] & 0xF;

                s->sample[0] += s->sol_table[n1];

                if (s->sample[0] < 0)   s->sample[0] = 0;

                if (s->sample[0] > 255) s->sample[0] = 255;

                output_samples[out++] = (s->sample[0] - 128) << 8;

                s->sample[stereo] += s->sol_table[n2];

                if (s->sample[stereo] < 0)   s->sample[stereo] = 0;

                if (s->sample[stereo] > 255) s->sample[stereo] = 255;

                output_samples[out++] = (s->sample[stereo] - 128) << 8;

            }

        } else {

            while (in < buf_size) {

                int n;

                n = buf[in++];

                if (n & 0x80) s->sample[ch] -= s->sol_table[n & 0x7F];

                else s->sample[ch] += s->sol_table[n & 0x7F];

                s->sample[ch] = av_clip_int16(s->sample[ch]);

                output_samples[out++] = s->sample[ch];

                /* toggle channel */

                ch ^= stereo;

            }

        }

        break;

    }

    *data_size = out * sizeof(short);

    return buf_size;

}


static void picmemset(PicContext *s, AVFrame *frame, unsigned value, int run,

                      int *x, int *y, int *plane, int bits_per_plane)

{

    uint8_t *d;

    int shift = *plane * bits_per_plane;

    unsigned mask  = ((1 << bits_per_plane) - 1) << shift;

    value   <<= shift;

    while (run > 0) {

        int j;

        for (j = 8-bits_per_plane; j >= 0; j -= bits_per_plane) {

            d = frame->data[0] + *y * frame->linesize[0];

            d[*x] |= (value >> j) & mask;

            *x += 1;

            if (*x == s->width) {

                *y -= 1;

                *x = 0;

                if (*y < 0) {

                   *y = s->height - 1;

                   *plane += 1;

                   if (*plane >= s->nb_planes)

                       return;

                   value <<= bits_per_plane;

                   mask  <<= bits_per_plane;

                }

            }

        }

        run--;

    }

}